Object tree navigation language in Java - java

In the system which I'm currently developing I often have to navigate an object tree and based on its state and values take actions. In normal Java this results in tedious for loops, if statements etc... Are there alternative ways to achieve tree navigation, similar to XPath for XML? I know there is JXPath and OGNL, but do you know any other libraries for such purpose? Do you know any libraries which generate bytecodes for specific tree navigation expressions to make the processing as fast as Java native fors and ifs?

You may want to consider Jakarta Bean Utils
String street = (String) PropertyUtils.getProperty(user, "address.street");
You can navigate through the object graph using a dot notation. You can access also indexed properties. More details on the docs.
One drawback is that Bean Utils expects that the graph you are navigating does not contain null references.
The code snippet below would throw a NPE
Person person = new Person();
person.setAddress(null);
String street = (String) PropertyUtils.getProperty(person, "address.street");
To overcome this limitation my team implemented a class that creates instances of all null references of a graph on demand. This code is based on reflection and dynamic proxies (CGLIB).

Can I ask you why you would not like OGNL/JXPath ? Obviously you may have done your research to say no but I would like to know why OGNL is not solving a purpose that it was designed to solve.
Also google-collections has some functors (in addition to commons collections mentioned above) which may be worth looking at.

Jakarta collections ( http://commons.apache.org/collections/apidocs/ ) allow you to apply predicates, functors, etc... on collection members. Is this the direction you are looking for?

Related

Should I avoid commonly used class names?

Some class names are so "generic" that they are often found in several different packages, including in libraries and application code. Some examples:
Comment
Component
Factory
Location
Region
In my IDE, attempting to auto-complete the import for a class like one of these summons several competing suggestions.
When naming classes, is it a good idea to avoid class names already used elsewhere?
For some of these examples, I would imagine that using such class name is discouraged because it is simply not meaningful enough (e.g. Factory), but I am wondering whether it is discouraged to use a class name because it is used (frequently) elsewhere.
You should use class names where they make the most sense for you. None of the names above that you've proposed are off limits, and there's no reason why you can't use them (assuming a language that supports namespaces and can avoid naming conflicts in this way).
However, you may consider drilling down to class names that are more specific and precise, which will better describe the meaning of the objects in your code. For example:
Instead of Comment: LineComment or BreakComment could easily be class names in a compiler project where you would like to create semantic blocks for comments.
Instead of Component: ListComponent, CalendarComponent, or ViewComponent make particular sense when implementing a UI library where you have class-based components.
Instead of Factory: PizzaFactory makes more sense if you're trying to make pizzas!
Instead of Location: GeographicLocation or SemanticLocation makes more sense when implementing a directions based navigation app, and you're trying to distinguish between '45 deg N, 77 deg W' and 'next to the pizza place'.
Region: CodeRegion could be used in a compiler, and GeographicRegion could be used in a Maps app.
If you're afraid to be specific, namespaces and packages help. However, there is nothing discouraging you from using the same name for a class as another package where it makes sense. The class names specifically aren't copyrighted, and most IDEs now are smart enough to make distinctions between what packages you're referring to when using autocompletion.
For the most part, specificity is helpful in assisting other developers to read your code, which every developer can appreciate!
Comment, Region, and Location seem fine. Personally, so subjectively, Component and Factory are definitely too common to use but objectively I can't think of any conventional reason not to use them as names. I'd definitely try and couple those names with their respective usage, for example; TaskFactory, WidgetComponent, ButtonFactory, etc.
Depends if we are talking about business or technical part.
In technical part: using common names is actually a way to let others know about the patterns used, Factory is a good example - when you see a class named like SomethingFactory, you can expect a Factory Pattern. It goes further to frameworks, libraries etc. - SomethingAutoConfiguration with Spring-Boot, SomethingEntity with JPA, I think with frontend frameworks (React, Angular) Component is a really common word. So ye, by all means, use them, as long as you use them correctly.
In business part: simple, if those words describe your business domain, then by all means use them. Don't try to invent some fancy names (or thesaurus!) just because the words seem common, it's your business domain - it's sacred.

What's the design pattern for object to object conversion?

The question is simple. I need to convert the content of a bean into an other bean with different getters and setters. What's the right design pattern for doing this?
I think an adapter pattern is mainly referring to a mapping of a signature or interface to an other. Not a real mapping between objects.
Many people talks about "mapper" but I think this is not a design pattern.
So, is there actually a pattern for mapping an object to an other?
I'm not aware of any popular design pattern for object mapping.
I have been using Dozer framework for transfering the content from one bean to another.
It is simple to use and easily integrates with Spring.
Refer:
http://dozer.sourceforge.net/documentation/gettingstarted.html
A great "design pattern" would be to not tightly couple the mapped objects to each other. A copy constructor, for example, means that if you edit the source class, you also have to edit the destination class, and that can cause all sorts of downstream issues in a large project. Think about it this way. A very frequent mapping is from UI data structures to back-end data structures. You should be able to scrap your UI and not have to change the back-end for a new UI. An MVC design pattern is frequently used for this sort of work.
There is a nice Translator pattern published by Microsoft. The tutorial is in C++ but it should be easy to convert to Java.
Here is a tutorial: http://richhewlett.com/2010/06/11/a-useful-entity-translator-pattern-object-mapper-template/
The general idea is you have a generic Translator abstract class, parametrized with the class types you want to translate between. The concrete implementations provide the "to" and "from" conversion methods.
This pattern has the advantage that it does not require coupling between the two classes in the conversion. It does this in a reusable, generic framework that won't clutter your code with one-off conversion decoupling logic.
The related pattern is Assembler where you assemble some object given the contents of another. Since writing assemblers can be tedious and error-prone, you can use an object mapping library to do the work for you.
One object mapper you might check out is ModelMapper, which I authored, that uses actual code to map properties, fields and methods, in a safe way.
I agree with Javakid, what you need is not a design pattern but a good solution to handle te conversion from one bean to another.
If you really need to name, that should something like dto pattern since you are using data transfer object. You can use a visitor to inspect all your bean tree while building the converted one.
so I would suggest using a framework or developping the mapping by yourself, it depends on the size of the graph. Dozer is goode solution to do it but it uses Reflection API all the way and hide the mapping code. So you won't be able to debug it easily, there are also few other runtime mapping library like Orika the best I know.
But, If you want to be able to see the code, debug it and have compiler feedback you can also use Selma.
Last thing, you can also report to this thread for a big picture of solutions to handle bean to bean mapping in java: any tool for java object to object mapping?

How to make an efficient and fast mapping between owl classes and java classes?

I'm trying to make an application that makes use of the Hermit OWL reasoner to reason on user input data. I've already made the mapping from OWL classes to Java classes and the other way by using the various OWLAPI methods.
The only thing left to do now is to make some kind of mapping that allows a Java program to automatically convert a lot of OWL individuals, extracted from the ontology, to the associated Java classes.
Currently I have the following in mind: a hashmap that contains a list of the names of the OWL classes as keys and then as value to the key the name of the Java class. When looking up a key, the class can then be instantiated through the use of Java Reflection. The only downside to this way is that it will probably be very slow?
Does anybody have a better idea to do the above?
Thanks in advance!
Tom DC
EDIT:
An example of an OWL class that I converted into a Java class (the class was too big to post here): http://pastebin.com/aEsjvDN7
As you can see in the example, I already tried to make it easier for a mapping by creating a function that looks at the OWL IRI and then decides what object it has to choose to make. This function is probably obsolete and useless when using JAXB or the hashmap.
If you need to instantiate a particular Java class starting from a match in the map, I would put as values builders for these classes rather than class names to be built through reflection, since it gives you better flexibility and possibly better performances.
An example of such builders:
public interface BuilderClass<O, P>{
O build(P parameter);
}
public class BuilderSpecificClass<SpecificClass, Object>{
#Override
public SpecificClass build(Object parameter){
return new SpecificClass(parameter);
}
}
Then the map would look something like:
Map<String, BuilderClass<SpecificClass, Object>> map=new HashMap<String, BuilderClass<SpecificClass, Object>>();
map.put("<class_iri>", new BuilderSpecificClass<SpecificClass, Object>());
That said, I'm not clear how your specific classes work, so there might be a better way. Can you add an example of how you built them?
Edited after Tom's extra details:
Ok, if I understand what your class is doing, you have half the approach I described already implemented.
Your class is basically wrapping sets of OWL assertion axioms, either asserted or inferred - i.e., values for your fields come either from the ontology or from a reasoner, and relate individuals with individuals or with values.
You also have methods to populate a class instance from an ontology and a reasoner; these correspond to what I proposed above as build() method, where the parameters would be the ontology and the reasoner. You can skip passing the ontology manager since an instance of OWLOntologyManager is already accessible through the ontology: ontology.getOWLOntologyManager()
What I would do here is create builders pretty much like I described and have them call your methods to populate the objects.
In terms of performances, it's hard to tell whether there are any serious hot spots - at a guess, there shouldn't be anything particularly hard in this code. The ontology is the place where such problems usually arise.
What I can suggest in this class is the following:
private final String personURI = ThesisOntologyTools.PERSON_URI + "Person";
You have a few member variables which look like this one. I believe these are constants, so rather than having a copy in each of your instances, you might save memory by making them static final.
OWLDataProperty isLocationConfirmed = dataFactory.getOWLDataProperty(IRI.create(isLocationConfirmedURI));
You are creating a number of objects in a way similar to this. Notice that IRI.create() will return an immutable object, as well as dataFactory.getOWLDataProperty(), so rather than accessing the data factory each time you can reuse such objects.
All objects produced by a data factory are not linked to a specific ontology and are immutable, so you can reuse them freely across your classes, to reduce the number of new objects created. A data factory might cache some of them, but some others might be recreated from scratch on each call, so reducing the number of calls should improve speed and memory requirements.
Other than this, the approach looks fine. If the memory required or the speed are too high (or too low), you may want to start using a profiler to pinpoint the issues. and if the hotspots are in the OWL API, please raise an issue in OWLAPI issue tracker :-) we don't get enough performance reports from real users.
I would recommend strongly against Reflection, as powerful as it is, and recommend instead JAXB. It allows you to derive Java classes based on XML schema, and OWL would just be a specific instance of that.
Otherwise, take a look on the web. I feel like you aren't the first to want such a thing.

detect circular reference in an object

Suppose you have a java object, would it be possible to detect where exists circular references inside that java object?
I would like to hear if there is a library to deal with this problem.
Thanks in advance.
Beware, this is not trivial task, but you already know this, right? ;)
In Java there is implementation of IdentityHashMap that is designed to be uses in such cases.
Conceptually simple, but can be quite complex to implement.
First off, a lot depends on what type of objects you're dealing with. If only a small number of object classes, and you "own" the classes and can modify them to add "search yourself" code, then it becomes much easier:
Add an interface to each class and implement the "search yourself" method in each class. The method receives a list of objects, and returns a return code. The method compares its own address to each object on the list, returning true (ie, loop found) if one matches. Then (if no match) it adds its own address to the list and calls, in turn, the "search yourself" method of each object reference it contains. If any of these calls results in a true return code, that is returned, otherwise false is returned. (This is a "depth-first, recursive" search.)
If you don't "own" the classes then you must use reflections to implement essentially the above algorithm without modifying the classes.
There are other search algorithms that can be used -- "breadth-first", and various non-recursive versions of depth-first, but they all represent trade-offs of one sort or another of between heap storage, stack storage, and performance.
A bit of a lateral answer, but how about using net.sf.json.JSONObject.fromObject(...) which checks for circular references and throws an exception if any are found. Also, you can configure the library to handle circular references differently if necessary. You would have to write a getter for those class members that exist in the cyclical relationship, since that is what JSONObject uses to create the JSON.
It seems to be simple task to code. Use Java Reflection API to crawl the graph of java objects and collect visited objects. If you visit object that is already in the set that means that there has to be a circuit. To crawl use BFS or DFS algorithms.
You don't need any library. It's simple breadth-first search alghoritm and reflection API. Of course you can try to find a library implementing this alghoritm.

Need to get my hands dirty on reflection

I have read about Java Reflections but till date it has been a vague concept to me. Can someone give a brief details with short example on how to use reflections in Java ?
Thanks.
I have read about Java Reflections but
till date it has been a vague concept
to me.
Here is a quick into to reflection in java:
Structural introspection. Basic reflection deals with the introspection of object at run-time. This means that you can learn the structure of objects and classes at run-time programmatically, e.g. get the class of the object, list the methods of the class, list the fields defined in the class, etc.
Reflective invocation and instantiation. With reflection you can invoke a method at run-time which is not defined at compile-time, e.g. invoke method named M on object O, where M is read in a configuration file. You can also instantiate object dynamically without knowing the class at compile-time.
Annotations. Then you can move one level up in the meta levels, and play with annotations. Annotations describe other elements such as class, method and fields. Many framework rely on this.
Dynamic proxy. Dynamic proxy can be generated at run-time. In this case, it's really like if you create a class dynamically at run-time. To use with care, but definitively handy and powerful in some cases.
I guess you will start with structural introspection. There are links to tutorials in the other answers, but I hope this gives you an overview of what else can be done.
I guess the article 'Using Java Reflection' found on sun.com might be a good starting point.
It's primarily to be used to access classes/methods/fields programmatically (i.e. during runtime instead of compiletime). Good real world API's which uses reflection intensively are ORM's like Hibernate/JPA.
You can find here a Sun tutorial on the subject (click Next link at the bottom to paginate through it).
Something worth mentioning as well is Javassist. Not only does it have reflective abilities, but it also allows run-time bytecode manipulation using ordinary source syntax! Once you've gotten into reflection a bit more (which you probably have by now), you'll truly appreciate it's beauty.

Categories