I want to leverage on the new features of Objectify4 however my application is build and is working with version 3. My application largely builds upon the ObjectifyGenericDao pattern and that the Objectify4 design pattern is quite different from this:
ObjectifyGenericDao.java
public class ObjectifyGenericDao<T> extends DAOBase
{
static final int BAD_MODIFIERS = Modifier.FINAL | Modifier.STATIC | Modifier.TRANSIENT;
static
{
// Register all your entity classes here
}
protected Class<T> clazz;
/**
* We've got to get the associated domain class somehow
*
* #param clazz
*/
protected ObjectifyGenericDao(Class<T> clazz)
{
this.clazz = clazz;
}
public ObjectifyGenericDao(ObjectifyOpts opts) {
super(opts);
//this.clazz = clazz;
}
public Key<T> put(T entity)
{
return ofy().put(entity);
}
// TODO This code was modified
// and need to be tested
public List<Key<T>> putAll(Iterable<T> entities)
{
Map<Key<T>, T> map = ofy().put(entities);
return new ArrayList<Key<T>>(map.keySet());
//return ofy().put(entities);
}
public void delete(T entity)
{
ofy().delete(entity);
}
public void deleteKey(Key<T> entityKey)
{
ofy().delete(entityKey);
}
public void deleteAll(Iterable<T> entities)
{
ofy().delete(entities);
}
public void deleteKeys(Iterable<Key<T>> keys)
{
ofy().delete(keys);
}
public T get(Long id) throws EntityNotFoundException
{
return ofy().get(this.clazz, id);
}
public T get(String id) throws EntityNotFoundException
{
return ofy().get(this.clazz, id);
}
public T get(Key<T> key) throws EntityNotFoundException
{
return ofy().get(key);
}
/**
* Convenience method to get all objects matching a single property
*
* #param propName
* #param propValue
* #return T matching Object
*/
public T getByProperty(String propName, Object propValue)
{
Query<T> q = ofy().query(clazz);
q.filter(propName, propValue);
return q.get();
}
public List<T> listByProperty(String propName, Object propValue)
{
Query<T> q = ofy().query(clazz);
q.filter(propName, propValue);
return asList(q.fetch());
}
public List<Key<T>> listKeysByProperty(String propName, Object propValue)
{
Query<T> q = ofy().query(clazz);
q.filter(propName, propValue);
return asKeyList(q.fetchKeys());
}
public T getByExample(T exampleObj)
{
Query<T> queryByExample = buildQueryByExample(exampleObj);
Iterable<T> iterableResults = queryByExample.fetch();
Iterator<T> i = iterableResults.iterator();
T obj = i.next();
if (i.hasNext())
throw new RuntimeException("Too many results");
return obj;
}
public List<T> listByExample(T exampleObj)
{
Query<T> queryByExample = buildQueryByExample(exampleObj);
return asList(queryByExample.fetch());
}
private List<T> asList(Iterable<T> iterable)
{
ArrayList<T> list = new ArrayList<T>();
for (T t : iterable)
{
list.add(t);
}
return list;
}
private List<Key<T>> asKeyList(Iterable<Key<T>> iterableKeys)
{
ArrayList<Key<T>> keys = new ArrayList<Key<T>>();
for (Key<T> key : iterableKeys)
{
keys.add(key);
}
return keys;
}
private Query<T> buildQueryByExample(T exampleObj)
{
Query<T> q = ofy().query(clazz);
// Add all non-null properties to query filter
for (Field field : clazz.getDeclaredFields())
{
// Ignore transient, embedded, array, and collection properties
if (field.isAnnotationPresent(Transient.class)
|| (field.isAnnotationPresent(Embedded.class))
|| (field.getType().isArray())
|| (Collection.class.isAssignableFrom(field.getType()))
|| ((field.getModifiers() & BAD_MODIFIERS) != 0))
continue;
field.setAccessible(true);
Object value;
try
{
value = field.get(exampleObj);
}
catch (IllegalArgumentException e)
{
throw new RuntimeException(e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
if (value != null)
{
q.filter(field.getName(), value);
}
}
return q;
}
// Added, but may not be really useful
public Query<T> query(String filter, String value) {
Query<T> q = ofy().query(clazz).filter(filter, value);
return q;
}
The bottleneck with Objectify4 is that it does not have DAOBase so it not very easy to migrate existing codes.
How can I have this pattern while using Objectify4 features?
As mentioned on the Objectify Google Group, just drop the extends DAOBase.
You can get code for OfyService here:
https://code.google.com/p/objectify-appengine/wiki/BestPractices
Add static import in ObjectifyGenericDao and then you can use methods like:
public Key<T> save(T entity){
return ofy().save().entity(entity).now();
}
public void delete(T entity){
ofy().delete().entity(entity);
}
public T get(Long id){
return ofy().load().type(clazz).id(id).get();
}
and so on ...
Related
I have hazelcast client that is putting generic message class into a iQueue and hazelcast member consume this generic message via Listener do the logic and remove the object from the queue. But it is not removing all the objects. On mancenter i can see that there are still items into the queue (not all for example from 100 objects in queue it is removing around 80 from them) and i don`t know why it is not removing some of the objects.
Currently in mancenter it is showing 12 items into the queue (from arround 100 requests) but it shouldn't have any.Still the code is working and returning results. The only problem is that i can see in mancenter that this items are getting more and more into the queue until i stop the hazelcast server.
My generic message class:
public class GenericMessage<T> implements Message<T>, Serializable {
private static final long serialVersionUID = -1927585972068115172L;
private final T payload;
private MessageHeaders headers;
public GenericMessage(T payload) {
Assert.notNull(payload, "payload must not be null");
HashMap<Object, Object> headers = new HashMap<>();
this.headers = new MessageHeaders(headers);
this.payload = payload;
}
#Override
public MessageHeaders getHeaders() {
return this.headers;
}
#Override
public T getPayload() {
return this.payload;
}
#Override
public String toString() {
return "[Payload=" + this.payload + "][Headers=" + this.headers + "]";
}
#Override
public int hashCode() {
return this.headers.hashCode() * 23 + ObjectUtils.nullSafeHashCode(this.payload);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj instanceof GenericMessage<?>) {
GenericMessage<?> other = (GenericMessage<?>) obj;
if (this.headers.getKey() != null && other.headers.getKey() != null) {
return this.headers.getKey().equals(other.headers.getKey());
} else {
return false;
}
}
return false;
}
}
MessageHeaders class:
public class MessageHeaders implements Map<Object, Object>, Serializable {
private static final long serialVersionUID = 4469807275189880042L;
protected Map<Object, Object> headers;
public static final String KEY = "key";
public MessageHeaders(Map<Object, Object> headers) {
this.headers = (headers != null) ? headers : new HashMap<>();
}
#SuppressWarnings("unchecked")
public <T> T get(Object key, Class<T> type) {
Object value = this.headers.get(key);
if (value == null) {
return null;
}
if (!type.isAssignableFrom(value.getClass())) {
throw new IllegalArgumentException("Incorrect type specified for header '"
+ key
+ "'. Expected ["
+ type
+ "] but actual type is ["
+ value.getClass()
+ "]");
}
return (T) value;
}
#Override
public int hashCode() {
return this.headers.hashCode();
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj instanceof MessageHeaders) {
MessageHeaders other = (MessageHeaders) obj;
return this.headers.equals(other.headers);
}
return false;
}
#Override
public boolean containsKey(Object key) {
return this.headers.containsKey(key);
}
#Override
public boolean containsValue(Object value) {
return this.headers.containsValue(value);
}
#Override
public Set<Map.Entry<Object, Object>> entrySet() {
return Collections.unmodifiableSet(this.headers.entrySet());
}
#Override
public Object get(Object key) {
return this.headers.get(key);
}
#Override
public boolean isEmpty() {
return this.headers.isEmpty();
}
#Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(this.headers.keySet());
}
#Override
public int size() {
return this.headers.size();
}
#Override
public Collection<Object> values() {
return Collections.unmodifiableCollection(this.headers.values());
}
#Override
public Object put(Object key, Object value) {
throw new UnsupportedOperationException("MessageHeaders is immutable.");
}
#Override
public void putAll(Map<? extends Object, ? extends Object> t) {
throw new UnsupportedOperationException("MessageHeaders is immutable.");
}
#Override
public Object remove(Object key) {
throw new UnsupportedOperationException("MessageHeaders is immutable.");
}
#Override
public void clear() {
throw new UnsupportedOperationException("MessageHeaders is immutable.");
}
private void writeObject(ObjectOutputStream out) throws IOException {
List<String> keysToRemove = new ArrayList<>();
for (Map.Entry<Object, Object> entry : this.headers.entrySet()) {
if (!(entry.getValue() instanceof Serializable)) {
keysToRemove.add(String.valueOf(entry.getKey()));
}
}
for (String key : keysToRemove) {
// if (logger.isInfoEnabled()) {
// logger.info("removing non-serializable header: " +
// key);
// }
this.headers.remove(key);
}
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
public String getKey() {
return this.get(KEY, String.class);
}
public void setKey(String key) {
this.headers.put(KEY, key);
}
}
Putting into queue implementation:
User user = new User();
GenericMessage<User> message = new GenericMessage<User>(user);
String key="123";
message.getHeaders().setKey(key);
IQueue<Object> queue = hazelcastInstance.getQueue("user_queue");
queue.add(message);
Hazelcast listener configuration:
IQueue<Object> userQueue = hazelcastInstance.getQueue("user_queue");
UserListener userListener = context.getBean(UserListener.class);
userQueue.addItemListener(userListener, true);
Listener:
public class UserListener implements ItemListener<Object> {
#Autowired
private UserService service;
#Override
public void itemAdded(ItemEvent<Object> arg0) {
service.process(arg0);
}
}
Service:
public class UserService {
#Async("userTaskExecutor")
public void process(ItemEvent<Object> item) {
GenericMessage<User> message = (GenericMessage<User>) item.getItem();
hazelcastInstance.getQueue("user_queue").remove(message);
}
With a lot of testing and debugging i found the problem.
It turns out that the documentation of the remove(object) method is misleading. In the documentation is says that this method rely on .equals() class method but it turns out that hazelcast compares the serialized object against each serialized object. So i implement a custom compare:
GenericMessage<?> incomeMessage = (GenericMessage<?>) object;
boolean removed = hazelcastInstance.getQueue(queueId).remove(object);
if (!removed) {
Iterator<Object> iterator = hazelcastInstance.getQueue(queueId).iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
GenericMessage<?> message = (GenericMessage<?>) next;
if (incomeMessage.getHeaders().getKey()
.equals(message.getHeaders().getKey())) {
object = next;
removed = hazelcastInstance.getQueue(queueId).remove(object);
break;
}
}
}
Example I have data layer after
public class DemoData implements Cloneable {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
I want to assign data values (DemoData) to a duplicate data (DemoData clone) layer as follows
public static void main(String[] args) {
DemoData demoData = new DemoData();
demoData.setName("Class Sources");
testReflectionDemo(demoData);
}
private static DemoData testReflectionDemo(DemoData demoData) {
try {
DemoData clone = (DemoData) demoData.clone();
clone.setName(demoData.getName());
clone.setValue(demoData.getValue());
return clone;
} catch (CloneNotSupportedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I want to convert the method testReflectionDemo(DemoData demoData) to method testReflectionDemo(T t) reflection as shown below.I do not know how to continue, please help me
public <T> T testReflectionDemo(T t){
Class<?> aClass = t.getClass();
for (Method method : aClass.getMethods()) {
}
return null;
}
Thank you all for the help for my question,I've removed the clone method, I just applied reflection.Hi #dabaicai.Your code helped me with the idea,I thought passing the value to the private field would be easier a little.
public static <T> T clazzClone(T t) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
Class<?> clazzRoot = t.getClass();
Object newInstance = clazzRoot.newInstance();
Field[] fieldsClone = newInstance.getClass().getDeclaredFields();
for (Field fieldClone : fieldsClone) {
fieldClone.setAccessible(true);
fieldClone.set(newInstance, getContent(t, fieldClone.getName()));
}
return (T) newInstance;
}
private static String getContent(Object aClass, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field declaredField = aClass.getClass().getDeclaredField(name);
declaredField.setAccessible(true);
return (String) declaredField.get(aClass);
}
My program means when I need to edit user input data to output the results I want,with a common filter function
fieldClone.set(newInstance,methodYourEdit(getContent(t, fieldClone.getName())));
If the argument of testReflectionDemo is a javabean,it means that the class of argument have several a pair method of setXXX and 'getXXX,and thegetXXXdon't have argument,thesetXXX` just have one argument.If is this,the following code can copy the property from old object to new object.
Class<?> aClass = t.getClass();
Object result = aClass.newInstance();
Map<String,MethodHolder> map=new HashMap<>();
for (Method method : aClass.getMethods()) {
if(method.getName().startsWith("get") && method.getParameterTypes().length==0){
String property=method.getName().substring(3);
MethodHolder hodler = map.get(property);
if(hodler ==null){
map.put(property, new MethodHolder(property, method, null));
continue;
}
hodler.getMethod=method;
}else if (method.getName().startsWith("set") && method.getParameterTypes().length==1) {
String property=method.getName().substring(3);
MethodHolder holder = map.get(property);
if(holder ==null){
map.put(property, new MethodHolder(property, null, method));
continue;
}
holder.setMethod=method;
}
}
List<MethodHolder> collect = map.values().stream().filter(item -> item.setMethod != null && item.getMethod != null).collect(Collectors.toList());
for (MethodHolder holder : collect) {
Object property = holder.getMethod.invoke(t);
holder.setMethod.invoke(result,property);
}
return (T)result;
The MethodHolder just have some field:
public static class MethodHolder{
private String property;
private Method getMethod;
private Method setMethod;
public MethodHolder() {
}
public MethodHolder(String property, Method getMethod, Method setMethod) {
this.property = property;
this.getMethod = getMethod;
this.setMethod = setMethod;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MethodHolder)) return false;
MethodHolder that = (MethodHolder) o;
return Objects.equals(property, that.property);
}
#Override
public int hashCode() {
return Objects.hash(property);
}
}
Pay attention of that the following code just make shallow copy.
#Entity
#NamedQueries({
#NamedQuery(
name = "FolderNode.findByName",
query = "SELECT f FROM FolderNode f WHERE f.name = :name AND f.parentNode = :parentNode"),
#NamedQuery(
name = "FolderNode.findRootNodeByName",
query = "SELECT f FROM FolderNode f WHERE f.name = :name AND f.parentNode is null")
})
public class FolderNode extends InstructorTreeNode {
public FolderNode() {
super();
}
public FolderNode(String name) {
this();
setName(name);
}
public FolderNode(int sortOrder, String name) {
this(name);
this.sortOrder = sortOrder;
}
public FolderNode(int sortOrder, String name, EmployeeState status) {
this(sortOrder, name);
this.status = status;
}
public static FolderNode addWaitingListNode(String name) {
EntityManager em = getDao().getEntityManager();
em.getTransaction().begin();
FolderNode waitingListNode = getWaitingListFolder();
FolderNode folderNode = new FolderNode(0, name);
waitingListNode.addChild(folderNode);
em.merge(waitingListNode);
em.getTransaction().commit();
em.close();
return folderNode;
}
public static void addWaitingListStudent(String waitingList, Student s) {
EntityManager em = FolderNode.getDao().getEntityManager();
em.getTransaction().begin();
FolderNode waitingListsNode = getWaitingListFolder();
FolderNode waitingListNode = getDao().findFolderNodeByName(waitingListsNode, waitingList);
waitingListNode.addChild(new EmployeeLeaf(s.getInmate()));
em.merge(waitingListNode);
em.getTransaction().commit();
em.close();
}
public static FolderNode getAMClassFolder() {
return getDao().findFolderNodeByName(getStudentsFolder(), "AM Class");
}
public static FolderNode getAttendanceFolder() {
return getDao().findFolderNodeByName(getRootFolder(), "Employee Attendance");
}
public static FolderNode getFormerParaprosFolder() {
return getDao().findFolderNodeByName(getParaprosFolder(), "Former");
}
public static FolderNode getFormerStudentsFolder() {
return getDao().findFolderNodeByName(getStudentsFolder(), "Former");
}
public static FolderNode getPMClassFolder() {
return getDao().findFolderNodeByName(getStudentsFolder(), "PM Class");
}
public static FolderNode getParaprosFolder() {
return getDao().findFolderNodeByName(getRootFolder(), "Parapros");
}
public static FolderNode getPendingStudentsFolder() {
return getDao().findFolderNodeByName(getRootFolder(), "Pending Students");
}
public static FolderNode getRootFolder() {
return getDao().findFolderNodeByName(null, EducationPreferences.getInstructor().getInstructorName());
}
public static FolderNode getStudentsFolder() {
return getDao().findFolderNodeByName(getRootFolder(), "Students");
}
public static FolderNode getWaitingListFolder(String name) {
FolderNode waitingListsNode = getWaitingListFolder();
return getDao().findFolderNodeByName(waitingListsNode, name);
}
public static FolderNode getWaitingListFolder() {
return getDao().findFolderNodeByName(getRootFolder(), "Waiting List");
}
public static void setClassFolder(Student aStudent, EntityManager entityManager) {
EntityManager em = entityManager;
if (entityManager == null) {
em = FolderNode.getDao().getEntityManager();
em.getTransaction().begin();
}
EmployeeLeaf leaf = EmployeeLeaf.findActiveStudentLeaf(aStudent);
FolderNode node = aStudent.getShift() == Shift.AM ? getAMClassFolder() : getPMClassFolder();
leaf.setParentNode(node);
em.merge(leaf);
GlobalEntityMethods.updateHistory(leaf);
if (entityManager == null) {
em.getTransaction().commit();
em.close();
}
}
public static void transferWaitingListStudent(String currentFolder, String toFolder, Student student) {
EntityManager em = FolderNode.getDao().getEntityManager();
em.getTransaction().begin();
FolderNode waitingListsNode = getWaitingListFolder();
FolderNode currentWaitingListNode = getDao().findFolderNodeByName(waitingListsNode, currentFolder);
EmployeeLeaf employeeLeaf = EmployeeLeaf.getDao().findWaitingListLeafByInmate(student.getInmate());
currentWaitingListNode.removeChild(employeeLeaf);
FolderNode toWaitingListNode = getDao().findFolderNodeByName(waitingListsNode, toFolder);
toWaitingListNode.addChild(employeeLeaf);
em.merge(currentWaitingListNode);
em.merge(toWaitingListNode);
em.getTransaction().commit();
em.close();
}
public void addChild(InstructorTreeNode node) {
childNodes.add(node);
node.setParentNode(this);
}
public List<InstructorTreeNode> getChildNodes() {
Collections.sort(childNodes);
return childNodes;
}
#Override
public Set<Inmate> getInmates() {
Set<Inmate> inmateSet = new HashSet<> (50);
for (InstructorTreeNode node: getChildNodes()) {
inmateSet.addAll(node.getInmates());
}
return inmateSet;
}
public int getSortOrder() {
return sortOrder;
}
public EmployeeState getStatus() {
return status;
}
#Override
public List<InstructorTreeNode> getTree() {
List <InstructorTreeNode> result = new ArrayList<> (25);
for (InstructorTreeNode childNode: getChildNodes()) {
if (childNode instanceof FolderNode) {
result.add(childNode);
}
result.addAll(childNode.getTree());
}
return result;
}
#Override
public JPanel getView(EmployeeViewController controller) {
if ("Employee Attendance".equals(getName())) {
return new AttendanceView();
} else if ("Waiting List".equals(getName())) {
return new AllWaitingListsPanel(controller);
} else if (getParentNode().getName().equals("Waiting List")) {
return new WaitingListPanel(controller);
} else if ("Pending Students".equals(getName())) {
return new PendingStudentsPanel(controller);
} else if ("Students".equals(getName())) {
return new AllStudentsPanel(controller);
} else if ("AM Class".equals(getName())) {
return new AllStudentsPanel(controller, Shift.AM);
} else if ("PM Class".equals(getName())) {
return new AllStudentsPanel(controller, Shift.PM);
} else if (getParentNode().getName().equals("Students") && "Former".equals(getName())) {
return new FormerStudentsPanel(controller);
} else if ("Parapros".equals(getName())) {
return new AllParaprosPanel(controller);
} else if (getParentNode().getName().equals("Parapros") && "Former".equals(getName())) {
return new FormerParaprosPanel(controller);
}
throw new UnsupportedOperationException("unknown folder");
}
public void removeChild(InstructorTreeNode node) {
childNodes.remove(node);
node.setParentNode(null);
}
public void removeEmployeeLeaf(Inmate inmate) {
for (InstructorTreeNode node: childNodes) {
if (node instanceof EmployeeLeaf) {
EmployeeLeaf employeeLeaf = (EmployeeLeaf) node;
if (employeeLeaf.getInmate().equals(inmate)) {
childNodes.remove(employeeLeaf);
break;
}
}
}
}
public void setChildNodes(List<InstructorTreeNode> childNodes) {
this.childNodes = childNodes;
}
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
public void setStatus(EmployeeState status) {
this.status = status;
}
#OneToMany(mappedBy = "parentNode", cascade = CascadeType.ALL, orphanRemoval = true)
private List<InstructorTreeNode> childNodes;
private int sortOrder;
#Enumerated(EnumType.STRING)
private EmployeeState status;
}
#Entity
#Table(catalog = "education", name = "instructortreenode", uniqueConstraints = #UniqueConstraint(columnNames = {
"PARENTNODE_ID", "NAME"
}))
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class InstructorTreeNode implements Comparable<InstructorTreeNode> {
public InstructorTreeNode() {
super();
}
public static InstructorTreeNodeDAO getDao() {
return dao;
}
#Override
public int compareTo(InstructorTreeNode o) {
if (o instanceof FolderNode && this instanceof FolderNode) {
FolderNode thisFolder = (FolderNode) this;
FolderNode otherFolder = (FolderNode) o;
if (thisFolder.getSortOrder() != otherFolder.getSortOrder()) {
return thisFolder.getSortOrder() - otherFolder.getSortOrder();
} else {
return thisFolder.getName().compareToIgnoreCase(otherFolder.getName());
}
} else if (o instanceof EmployeeLeaf && this instanceof EmployeeLeaf) {
return getName().compareToIgnoreCase(((InstructorTreeNode) o).getName());
}
return (o instanceof FolderNode) ? -1 : +1;
}
public int getCount() {
return getTree().size();
}
public abstract Set<Inmate> getInmates();
public String getName() {
return name;
}
public FolderNode getParentNode() {
return parentNode;
}
public abstract List<InstructorTreeNode> getTree();
public abstract JPanel getView(EmployeeViewController theController);
public void setName(String name) {
this.name = name;
}
public void setParentNode(FolderNode parentNode) {
this.parentNode = parentNode;
}
#Override
public String toString() {
return name;
}
private static final InstructorTreeNodeDAO dao = new InstructorTreeNodeDAO();
private String name;
#ManyToOne
private FolderNode parentNode;
}
Here is my problem:
The Collections.sort line works just fine in Java 8u5 and before, but
in Java 8u20 they seem to have changed the code for Collections.sort
and it no longer uses anything but the natural order, even if you specify
a Comparator.
Should I be using another method to sort my list, or is there an error in
Collections.sort.
Any help would be much appreciated, as this is driving me crazy.
I forgot to say that this code does not use a specified comparator, but according to the documentation it is supposed to use the CompareTo, if your class implements Comparable, which is what I am using.
I tried also specifying a comparator, but it did not work either.
Since Collections.sort now delegates to List.sort, the actual List implementation has an impact. Implementations like ArrayList and Vector take the opportunity to implement List.sort in a more efficient manner than the default implementation as they pass their internal array directly to Arrays.sort omitting the copy steps of the default implementation.
This works seamlessly unless programmers use the anti-pattern of subclassing an implementation (rather than using delegation) overriding methods to implement a contradicting behavior. Lazily populated lists like these from EclipseLink/JPA are known to have problems with this as they try to intercept every reading method to populate the list before proceeding but miss the new sort method. If the list hasn’t populated yet when sort is called, sort will see an empty list state.
In your code, there is no indication where the list does come from and which actual implementation class it has, but since I see a lot of familiar looking annotations, I guess, you are using such a framework…
If you use the method Collections#sort(List<T> list), it defers to the method List#sort(Comparator comparator) with comparator given as null. The source code from java.util.Collections is as follows:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
list.sort(null);
}
If you want to specify your own Comparator, you need to use the method Collections#sort(List<T> list, Comparator<T> comparator), which passes on your comparator to the list sorting method. The source code from java.util.Collections is as follows:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
So far so good. Now, as you have correctly pointed out, if you do not specify a comparator, the natural ordering of the class, that is, the compareTo method you have defined, is used.
However, the Comparable class documentation also states the following:
It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.
Since the class InstructorTreeNode does not override Object#equals, your compareTo method may return 0 even if == returns false. I reckon this is leading to what the documentation calls "strangely".
You might not like this answer because it doesn't give you a quick-fix for your situation, but it will help you more in the long run.
This is the kind of bug that you can figure out yourself with a little debugging. I don't know what IDE you are using, but with Eclipse, you can even step into code that is in the JDK!
So, what I would do, is set a breakpoint at the line where you call sort() on the childNodes. Then I would step into the JDK code and just walk through it myself. It will become very clear what is going on and why it isn't calling your compare function.
You could try to build a custom comparator. Here is an example how that should look. This is for comparing BigDecimals.
class YourComparator implements Comparator<InstructorTreeNode> {
#Override
public int compare(final InstructorTreeNode 01, final InstructorTreeNode o2) {
return o2.getYourCompVal().compareTo(o1.getYourCompVal());
}
}
public List<InstructorTreeNode> getChildNodes() {
Collections.sort(childNodes, new YourComparator());
return childNodes;}
In an attempt to create a N-ary tree with multiple node with different type of node objects[Country | State etc], I tried modifying the below generic class from -
https://github.com/vivin/GenericTree/blob/master/src/main/java/net/vivin/GenericTreeNode.java
I tried the following -
package com.mycompany.ds;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GenericTreeNode<T>{
private T data;
private List<GenericTreeNode<? super T>> children;
private GenericTreeNode<? super T> parent;
public GenericTreeNode() {
super();
children = new ArrayList<GenericTreeNode<? super T>>();
}
public GenericTreeNode(T data) {
this();
setData(data);
}
public GenericTreeNode<? super T> getParent() {
return this.parent;
}
public List<GenericTreeNode<? super T>> getChildren() {
return this.children;
}
public int getNumberOfChildren() {
return getChildren().size();
}
public boolean hasChildren() {
return (getNumberOfChildren() > 0);
}
public void setChildren(List<GenericTreeNode<? super T>> children) {
for(GenericTreeNode<? super T> child : children) {
child.parent = this;
}
this.children = children;
}
public void addChild(GenericTreeNode<? super T> child) {
child.parent = this;
children.add(child);
}
public void addChildAt(int index, GenericTreeNode<T> child) throws IndexOutOfBoundsException {
child.parent = this;
children.add(index, child);
}
public void removeChildren() {
this.children = new ArrayList<GenericTreeNode<? super T>>();
}
public void removeChildAt(int index) throws IndexOutOfBoundsException {
children.remove(index);
}
public GenericTreeNode<? super T> getChildAt(int index) throws IndexOutOfBoundsException {
return children.get(index);
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public String toString() {
return getData().toString();
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GenericTreeNode<?> other = (GenericTreeNode<?>) obj;
if (data == null) {
if (other.data != null) {
return false;
}
} else if (!data.equals(other.data)) {
return false;
}
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
public String toStringVerbose() {
String stringRepresentation = getData().toString() + ":[";
for (GenericTreeNode<? super T> node : getChildren()) {
stringRepresentation += node.getData().toString() + ", ";
}
//Pattern.DOTALL causes ^ and $ to match. Otherwise it won't. It's retarded.
Pattern pattern = Pattern.compile(", $", Pattern.DOTALL);
Matcher matcher = pattern.matcher(stringRepresentation);
stringRepresentation = matcher.replaceFirst("");
stringRepresentation += "]";
return stringRepresentation;
}
}
But errors in the following methods -
public void setChildren(List<GenericTreeNode<? super T>> children) {
for(GenericTreeNode<? super T> child : children) {
child.parent = this;
}
this.children = children;
}
public void addChild(GenericTreeNode<? super T> child) {
child.parent = this;
children.add(child);
}
Errors -
1 - Type mismatch: cannot convert from GenericTreeNode<T> to GenericTreeNode<? super capture#2-of ? super
T>
2 - Type mismatch: cannot convert from GenericTreeNode<T> to GenericTreeNode<? super capture#4-of ? super
T>
How can I fix these?
You could create a class / interface that represents a GISEntity and create the generic tree node whose generic type T extends GISEntity. This would allow you to have nodes of different kinds of GISEntity subclasses-- Country / State etc.
To build up on the answer of ditkin:
after having made all your classes implement or extend GISEntity, you would write your tree this way:
public class GenericTreeNode<T extends GISEntity>{
private T data;
private List<GenericTreeNode<? extends GISEntity>> children;
private GenericTreeNode<? extends GISEntity> parent;
public GenericTreeNode() {
super();
children = new ArrayList<GenericTreeNode<? extends GISEntity>>();
}
////////
......
////////
public void addChild(GenericTreeNode<? extends GISEntity> child) {
child.parent = this;
children.add(child);
}
public void addChildAt(int index, GenericTreeNode<? extends GISEntity> child) throws IndexOutOfBoundsException {
child.parent = this;
children.add(index, child);
}
////////
......
////////
}
Note that it will not really help you to avoid class casting. The thing is that as soon as you have added children to your node, when you retrieve them you just know that they are GISEntity, because of type erasure. So this technique only give you a bit of type safety.
It's not a good idea to use Generic in order to store different types of objects in the same collection. What you should do is to create an hierarchy and use it to store your objects. With a good design, the base class will have all that's necessary to access the different objects without casting; otherwise you will have to write some cast here and there. Here is an example of code (please note that the design here is far from beeing optimal and is simply to show the use of virtual function and polymorphism) :
static class GISEntity {
final String name;
public GISEntity (String name) { this.name = name; }
public String getName() { return name; }
public String getTypeName() { return "GISEntity"; }
public String toString() { return name; }
}
//
static class Country extends GISEntity {
final String typeName = "country";
public Country (String name) { super(name); }
public String getTypeName() { return typeName; }
public String toString() { return name; }
}
//
static class State extends GISEntity {
public State (String name) { super(name); }
public String getTypeName() { return "state"; }
public String toString() { return name; }
}
//
static class Territory extends GISEntity {
public Territory (String name) { super(name); }
public String getTypeName() { return "territory"; }
public String toString() { return name; }
}
//
// Here's an example of subclassing GenericTreeNode<GISEntity>:
//
static class IsATerritory extends GenericTreeNode<GISEntity> {
IsATerritory (String name) { super (new Territory (name)); }
public GISEntity getData() {
State s = new State (super.getData().getName().toUpperCase());
return s; }
};
//
// Here we put some data. Note that the order of insertion is important
// for the tree and that it's not alphabetical in this example.
//
GenericTree<GISEntity> earth = new GenericTree<GISEntity>() ;
//
GenericTreeNode<GISEntity> ListOfCountries = new GenericTreeNode<GISEntity>(new GISEntity("List of countries"));
//
GenericTreeNode<GISEntity> US = new GenericTreeNode<GISEntity>(new Country("United States"));
GenericTreeNode<GISEntity> Washington = new GenericTreeNode<GISEntity>(new State("Washington"));
GenericTreeNode<GISEntity> Florida = new GenericTreeNode<GISEntity>(new State("Florida"));
//
GenericTreeNode<GISEntity> Canada = new GenericTreeNode<GISEntity>(new Country("Canada"));
//
// We are now using some different ways for creating the nodes:
//
#SuppressWarnings("unchecked")
List<GenericTreeNode<GISEntity>> CanadaProvinces = new ArrayList<GenericTreeNode<GISEntity>>(
Arrays.asList(new GenericTreeNode<GISEntity>(new State("Quebec")),
new GenericTreeNode<GISEntity>(new State("Ontario")))
);
//
US.addChild(Washington);
US.addChild(Florida);
//
// Here's are two examples of subclassing; this time with anonymous classes.
// Don't forget that these two anonymous classes will hold an hidden reference
// to the outer classe as they are not static!
//
GenericTreeNode<GISEntity> alberta = new GenericTreeNode<GISEntity>() {
{ setData(new State ("Alberta")); }
public GISEntity getData() {
State s = new State (super.getData().getName().toUpperCase());
return s;
}
};
//
GenericTreeNode<GISEntity> saskatchewan = new GenericTreeNode<GISEntity>(new State ("saskatchewan")) {
public GISEntity getData() {
State s = new State (super.getData().getName().toUpperCase());
return s; }
};
//
CanadaProvinces.add(alberta);
CanadaProvinces.add(saskatchewan);
//
// Other ways for creating the nodes:
CanadaProvinces.add(new GenericTreeNode<GISEntity>(new State("Manitoba")));
//
// Note the use of the IsATerritory subclass:
CanadaProvinces.add(new IsATerritory("Northwest Territories"));
//
Canada.setChildren(CanadaProvinces);
//
ListOfCountries.addChild(Canada);
ListOfCountries.addChild(US);
//
earth.setRoot(ListOfCountries);
//
System.out.println(earth.toString());
System.out.println();
System.out.println(earth.toStringWithDepth());
System.out.println();
System.out.println(ListOfCountries.toStringVerbose());
//
List<GenericTreeNode<GISEntity>> loc = earth.build(GenericTreeTraversalOrderEnum.PRE_ORDER);
System.out.println(loc);
//
Map<GenericTreeNode<GISEntity>, Integer> locd = earth.buildWithDepth(GenericTreeTraversalOrderEnum.PRE_ORDER);
System.out.println(locd);
//
Map<GenericTreeNode<GISEntity>, Integer> locd2 = earth.buildWithDepth(GenericTreeTraversalOrderEnum.POST_ORDER);
System.out.println(locd2);
//
// Two examples of iteration; showing both the use of the instanceof operator
// and of virtual (or override) functions:
//
for (GenericTreeNode<GISEntity> gen: loc) {
GISEntity data = gen.getData();
if (data instanceof State) {
System.out.println("Is State: " + data.getName());
} else if (data instanceof Country) {
System.out.println("Is Country: " + data.getName());
} else {
System.out.println(data.getTypeName() + data.getName());
}
}
//
for (Entry<GenericTreeNode<GISEntity>, Integer> entry: locd.entrySet()) {
GISEntity data = entry.getKey().getData();
Integer depth = entry.getValue();
if (data instanceof State) {
System.out.println(depth.toString() + ": Is State: " + data.getName());
} else if (data instanceof Country) {
System.out.println(depth.toString() + ": Is Country: " + data.getName());
} else {
System.out.println(depth.toString() + ": " + data.getTypeName() + data.getName());
}
}
In this example, I have subclassed the class GenericTreeNode in three different ways (two anonymous classes, one a named class) in order to change the getData so that it will return a new GISEntity where the name has been replaced with its UpperCase copy.
Note that will all these three subclasses, I'm using GenericTreeNode<GISEntity> and not something like GenericTreeNode<Territory>. This is because that even if Territory is a subclass of GISEntry, the class GenericTreeNode<Territory> is not a subclass of GenericTreeNode<GISEntry>.
For using something like a mix of GenericTreeNode<Territory> with GenericTreeNode<GISEntry>, we have to use the ? extends GISEntry and ? super GISEntry and this will multiply by one thousand the complexity of the generic code. Unless that you want to make some heavy subclassing of the generic classes GenericTree<> and GenericTreeNode<>, it's totally useless to use the ? type; even for a collecting different types of objects. Unless that you have years of experience in generic code, don't use the ? notation. Most projects will do totally fine with the simpler generic code.
I've also added some examples of iterations over the generic tree for both the build() and the buildWithDepth() functions for those interested.
Finally, as a reference, this generic tree is explained in http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/ (3 pages).
I've done some fancy wrapping to avoid unchecked warnings in the past, but after 90 mins of poring over http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html, I can't write the findMatch method below and make it work without #SuppressWarnings("unchecked"). The parameterized class isn't known at compile time.
public interface Matchable<T>
{
public boolean matches(T toMatch);
}
public class PlaceForMatching
{
public static Object findMatch(Object toMatch, Object[] toSearch)
{
if(!(toMatch instanceof Matchable)) return null;
Matchable matchObj = (Matchable)toMatch;
Class<?> matchClass = matchObj.getClass();
for(Object obj : toSearch)
{
/**
* Check here verifies that the search list object we're about
* to check is the same class as the toMatch object.
* This means Matchable will work without a ClassCastException.
**/
if(matchClass.isInstance(obj) && matchObj.matches(obj))
return obj;
}
//Didn't find it
return null;
}
}
Note the code works because in every case Matchable is implemented by T.
Apple implements Matchable<Apple>
Orange implements Matchable<Orange>
EDIT: Add some test code
public static void main(String[] args)
{
Object[] randomList = createAppleArray();
Object apple = new Apple("Red");
Object match = findMatch(apple, randomList);
}
private static Object[] createAppleArray()
{
return new Object[] { new Apple("Pink"), new Apple("Red"), new Apple("Green") };
}
public class Apple implements Matchable<Apple>
{
String color;
public Apple(String color)
{
this.color = color;
}
public boolean matches(Apple apple)
{
return color.equals(apple.color);
}
}
public static <T extends Matchable<T>> T findMatch(T toMatch, T[] toSearch) {
if (toMatch == null)
return null;
Matchable<T> matchObj = toMatch;
Class<?> matchClass = matchObj.getClass();
for (T obj : toSearch) {
if (matchClass.isInstance(obj) && matchObj.matches(obj))
return obj;
}
return null;
}