Spring template engine for rendering JSON - java

I come from Ruby and have just started testing Spring and find it fairly nice.
However i'm used to being able to customize the rendered JSON output with libraries like rabl and it feels really wrong to expose internal models straight out into the JSON as i do now with the annotation #ResponseBody and just returning the model.
Does anyone have any tips on libraries similar to rabl but for java/spring or is there an existing way to do it easily with spring without manually writing templates in JSON?

Spring uses Jackson to do the JSON (de-)serialisation. Take a look at the Jackson wiki; it describes several ways to customise the way JSON is generated or interpreted.
As I understand from your comment, you have a couple of customisations in mind.
Renaming fields can be achieved by annotating the field with #JsonProperty("name")
Not rendering fields can be achieved by annotating the field with #JsonIgnore
But these do require you to touch your model. As far as I know, there is no way you could achieve that without at least changing your model classes slightly. There's the concept of "views" in Jackson but they still require putting annotations on your model. In practice, I've never experienced problems with Java classes being annotated with both JPA and Jackson annotations, by the way.
Finally, you can consider creating two versions of your model - one that comes from your database (or whatever source of data you have), and one that is used to interact with the user interface. However, that would require a layover of transformers or converters. Whether or not that is an option is up to you.

Related

What is the best way to reliable store a complex Java object hierarcy?

I'm currently developing a software where the user can define a complex hierarchy of objects as settings.
Also this settings objects will provide interfaces as an API for other developers.
Now I want to store these setting and reload it.
I'm currently considering different ways to do exactly that, but none of my solutions are "good" in my opinion.
The main goals should be:
It should output a String, because i prefer a human readable configuration over a fast one.
It should be reliable even when the the code is changing. This means not it should do magic, but it should be obvious that an change could break already stored configuration. (Eg. How do I prevent that my colleague renaming a class and breaking production. )
Storing and loading should work with object, interfaces and generics.
Keep configuration of what is stored how as low as possible. I would prefer convention over configuration.
I know many of you faced the same or a similar issue while developing.
So what was your solution? Which framework did you use and why?
All solutions I came up with are either not reliant, a huge configuration or to much code.
So I'm looking forward to get some good new perspectives on this topic from all of you.
Thanks.
I would recommend XStream. Without any configuration it has similar capabilities as java.io.*ObjectStream but outputs XML instead of binary blob. You will only want to add few aliases for class names to make file more readable.
I recommend to specify a XSD and use JAXB to generate the Java classes and marshal and unmarshal XML based settings files.
Make sure the root tag contains the version of the XSD. You can use StAX to read the version first and determine the correct version of JAXB classes if you need to support several versions.
For further information this how i solved this problem now:
I used Gson for serializing the object hierarchy to JSON. Added an Generic TypeAdapter to it for serializing and deserializing all known Interfaces. This adapter saves the class name into the JSON object and constructs this class while deserializing. No additional configuration is needed, besides registering this TypeAdapter for each used Interface.
In order to make it reliable I will add an Unit Test to the project that will deserialize the complete possible configuration. So any changes to the code will break the tests.
In this way i can fulfill all of the points mentioned above.
I hope this helps anyone.

Over exposure of hibernate pojo

Well I have recently started reading up on Hibernate so my knowledge is very raw.
I read somewhere that you should not expose your hibernate pojo classes directly on your application rather you should create classes which represents Pojo classes on your application. It's like custom classes which use only some or all of the fields of the Pojo classes.
Can someone put some light onto this as to how in an application we can stop the over exposure of Pojos or what is the correct way of using Pojos and custom classes which are returned from the server.
Better you right your own POJOs classes with required fields... And also write translators to translate data from hibernate POJOS to you Pojos.
Note:- If you are evaluating Hibernate for something, have a look on JOOQ.....
Tomorrow is a world with out ORMss........
http://www.jooq.org/doc/3.6/manual-single-page/
In general, I'd say it depends on your needs, but if you want to do it right, I suggest you have create custom classes for your DTOs that contain just the information you need. I have written an article about why using entities might lead to problems and how you can implement DTOs with Blaze-Persistence Entity Views to solve your problems. That might help you a bit to understand the implications.

Design pattern for modular application (how to reuse entities)

I have the following scenario:
A JAX-RS Webservice that is responsable for the business logic and database interactions.
A webapp that will be used by the end users.
A webapp that will be used by administrators.
My problem is that I want to reuse the entities from the webservice on the other apps, but it is highly wrapped with frameworks like JPA, JAX-RS, CDI, among others... So I am having a hard time to isolate them. What I want is to know the best workaround and why should I use it instead of others.
Maybe DTO is the way to go (with support from some object mapper library like Dozer)
Please take a look at following article for more details: http://zezutom.blogspot.com/2012/02/thoughts-on-data-transfer-objects.html
Write you entity objects as Plain Old Java Objects (POJOs), with proper constructors, setters, etc. Apply the annotations that allow the JPA to persist them and do the object to relational mapping in such a way that, if those annotations were all stripped away you could still create and manipulate those objects fully, using the public methods of the class. It can be helpful if you create the POJO first, then add the annotations afterwards.
As the POJOs stand alone they are not at all part of your repository layer. You can use them without using the JPA at all.

Design for service discovery of an API

I am working on a rather large API (390+ functions) and I am trying to pull together all the information that the documentation team would need in order to create docs for the project.
I have decided to use JSON Hyperschema to represent this.
I created an annotation processor to look for all of the javax.ws.rs.Path annotation from my code and grab the Javadoc, http method (from annotation) and other parameter information but I am running into a problem.
Hyper schema recommends, and my project spec requires, that the objects sent across an API are to be included as schema in the hyper schema. Typically I would use Jackson to accomplish this. However, as I am in an annotation processor that is not in the main API project, I cannot use class references (ex. User.class where user is an object in my API project and not in my processor) without generating errors. (This is explained here).
My question is, what is the best way around this limitation? I have come up with one way, explained below, but I want this to be pluggable into any other service (of the same format) to document them as well.
As a solution to this, I have thought to break my generator across compile time and runtime. At compile time I would generate JSON hyperschema with placeholders to reference the object schemas. It would also generate a resource file with full names of all of the objects.
At runtime I was planning on generating the schemas for the returned objects then inserting the links to them into the JSON.
IMHO this solution doesn't seem very "elegant". Does anyone have any insight into other ways to accomplish this?
I would recommend following projects:-
jsonschema-hypermedia-support which confirms to enter link description here
OR
Use Spring HATEOAS
Also see
this stackoveflow thread about Restful API

Xml configuration versus Annotation based configuration [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability.
My questions are: what are the advantages of XML-based configuration over Annotation-based configuration and what are the advantages of Annotation-based configuration over XML-based configuration?
Annotations have their use, but they are not the one silver bullet to kill XML configuration. I recommend mixing the two!
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code's dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.
However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.
I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information. But if you like JPA (I don't have any expirience with it), by all means, go for it.
In general:
If an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.
There is a wider issue here, that of externalised vs inlined meta-data. If your object model is only ever going to persisted in one way, then inlined meta-data (i.e. annotations) are more compact and readable.
If, however, your object model was reused in different applications in such a way that each application wanted to persist the model in different ways, then externalising the meta-data (i.e. XML descriptors) becomes more appropriate.
Neither one is better, and so both are supported, although annotations are more fashionable. As a result, new hair-on-fire frameworks like JPA tend to put more emphasis on them. More mature APIs like native Hibernate offer both, because it's known that neither one is enough.
I always think about annotations as some kind of indicator of what a class is capable of, or how it interacts with others.
Spring XML configuration on the other hand to me is just that, configuration
For instance, information about the ip and port of a proxy, is definetly going into an XML file, it is the runtime configuration.
Using #Autowire,#Element to indicate the framework what to do with the class is good use of annotations.
Putting the URL into the #Webservice annotation is bad style.
But this is just my opinion.
The line between interaction and configuration is not always clear.
I've been using Spring for a few years now and the amount of XML that was required was definitely getting tedious. Between the new XML schemas and annotation support in Spring 2.5 I usually do these things:
Using "component-scan" to autoload classes which use #Repository, #Service or #Component. I usually give every bean a name and then wire them together using #Resource. I find that this plumbing doesn't change very often so annotations make sense.
Using the "aop" namespace for all AOP. This really works great. I still use it for transactions too because putting #Transactional all over the place is kind of a drag. You can create named pointcuts for methods on any service or repository and very quickly apply the advice.
I use LocalContainerEntityManagerFactoryBean along with HibernateJpaVendorAdapter to configure Hibernate. This lets Hibernate easily auto-discover #Entity classes on the classpath. Then I create a named SessionFactory bean using "factory-bean" and "factory-method" referring to the LCEMFB.
An important part in using an annotation-only approach is that the concept of a "bean name" more or less goes away (becomes insignificant).
The "bean names" in Spring form an additional level of abstraction over the implementing classes. With XML beans are defined and referenced relative to their bean name. With annotations they are referenced by their class/interface. (Although the bean name exists, you do not need to know it)
I strongly believe that getting rid of superfluous abstractions simplifies systems and improves productivity. For large projects I think the gains by getting rid of XML can be substantial.
It depends on what everything you want to configure, because there are some options that cannot be configured with anotations. If we see it from the side of annotations:
plus: annotations are less talky
minus: annotations are less visible
It's up to you what is more important...
In general I would recommend to choose one way and use it all over some closed part of product...
(with some exceptions: eg if you choose XML based configurations, it's ok to use #Autowire annotation. It's mixing, but this one helps both readability and maintainability)
I think that visibility is a big win with an XML based approach. I find that the XML isn't really that bad, given the various tools out there for navigating XML documents (i.e. Visual Studio + ReSharper's File Structure window).
You can certainly take a mixed approach, but that seems dangerous to me if only because, potentially, it would make it difficult for new developers on a project to figure out where different objects are configured or mapped.
I don't know; in the end XML Hell doesn't seem all that bad to me.
There are other aspect to compare like refactoring and other code changes. when using XML it takes serous effort to make refactoring because you have to take care of all the XML content. But it is easy when using Annotations.
My preferred way is the Java based configuration without (or minimal) annotations. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java
I might be wrong, but I thought Annotations (as in Java's #Tag and C#'s [Attribute]) were a compile-time option, and XML was a run-time option. That to me says the are not equivalent and have different pros and cons.
I also think a mix is the best thing, but it also depends on the type of configuration parameters.
I'm working on a Seam project which also uses Spring and I usually deploy it to different development and test servers. So I have split:
Server specific configuration (Like absolute paths to resources on server): Spring XML file
Injecting beans as members of other beans (or reusing a Spring XML defined value in many beans): Annotations
The key difference is that you don't have to recompile the code for all changing server-specific configurations, just edit the xml file.
There's also the advantage that some configuration changes can be done by team members who don't understand all the code involved.
In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.
If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.
You should try to avoid using DI container in its wrong context.
Configuration information that is always going to be linked to a specific Java component (class, method, or field) is a good candidate to be represented by annotations. Annotations work especially well in this case when the configuration is core to the purpose of the code. Because of the limitations on annotations, it's also best when each component can only ever have one configuration. If you need to deal with multiple configurations, especially ones that are conditional on anything outside the Java class containing an annotation, annotations may create more problems than they solve. Finally, annotations cannot be modified without recompiling the Java source code, so anything that needs to be reconfigurable at run time can't use annotations.
Please refer following links. They might be useful too.
Annotations vs XML, advantages and disadvantages
http://www.ibm.com/developerworks/library/j-cwt08025/
This is the classic 'Configuration versus Convention' question. Personal taste dictates the answer in most cases. However, personally I prefer Configuration (i.e. XML based) over Convention. IMO IDE's are sufficiently robust enough to overcome some of the XML hell people often associate w/ the building and maintaining an XML based approach. In the end, I find the benefits of Configuration (such as building utilities to build, maintain and deploy the XML config file) outweighs Convention in the long run.
I use both. Mostly XML, but when I have a bunch of beans that inherit from a common class and have common properties, I use annotations for those, in the superclass, so I don't have to set the same properties for each bean. Because I'm a bit of a control freak, I use #Resource(name="referredBean") instead of just autowiring stuff (and save myself a lot of trouble if I ever need another bean of the same class as the original referredBean).
There are some pros and cons of annotation configuration from my experience:
When it comes to JPA configuration since it is done once and usually are not changed quite often I prefer to stick to annotation configuration. There maybe a concern regarding possibility to see a bigger picture of configuration - in this case I use MSQLWorkbench diagrams.
Xml configuration is very good to get a bigger picture of application but it maybe cumbersome to find some errors until runtime. In this case Spring #Configuration annotation sounds as a better choice since it let you see a bigger picture as well and also allows to validate configuration on compile time.
As for Spring configuration I prefer to combine both approaches: use #Configuration annotation with Services and Query interfaces and xml configuration for dataSource and spring configuration stuff like context:component-scan base-package="..."
But xml configuration bits java annotations when it comes to flow configuration(Spring Web Flow or Lexaden Web Flow) since it is extremely important to see a bigger picture of the whole business process. And it sounds cumbersome to have it implemented with annotations approach.
I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.
For Spring Framework I like the idea of being able to use the #Component annotation and setting the "component-scan" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig. For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well. In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration. I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration.
For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates The Clean Architecture which is a layering architectural style I have adopted over the past few years. The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant. In fact the Core Layer is not supposed to depend on any other infrastructure at all.
However, if The Clean Architecture is not your "cup of tea" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.

Categories