I'm looking for a solution which automatically generates POJO classfiles from a given .yaml-Files but have not found anything like this yet.
I can not imagine that it should be the only way to write these classes yourself.
The problem is that YAML describes objects, not classes. In general, you cannot automatically derive a POJO structure from a given YAML file. Take, for example, this YAML:
one: foo
two: bar
In YAML, this is a mapping with scalar keys and values. However, there are multiple possibilities to map it to Java. Here are two:
HashMap<String, String>
class Root {
String one;
String bar;
}
To know which one is the right mapping, you would need a schema definition like those for XML. Sadly, YAML currently does not provide a standard way of defining a schema. Therefore, you define the schema by writing the class hierarchy your YAML should be deserialised into.
So, in contrary to what you may think, writing the POJOs is not a superfluous action that could be automated, but instead is a vital step for including YAML in your application.
Note: In the case that you actually want to use YAML to define some data layout and then generate Java source code from it, that is of course possible. However, you'd need to be much more precise in your description to get help on that.
As pointed out in the comments by Jack Flamp, you can use an online tool (jsonschema2pojo) to convert a sample yaml file to its equivalent POJO classes. This tool can convert json or yaml data to corresponding POJO classes and I have used it successfully in the past.
That being said, the tool is forced to make certain "assumptions" when you are using a yaml file(instead of yaml schema). So, it would be a good idea to look at the generated classes carefully before you start using them.
You can find more information about how to use this online tool from its wiki page.
The Accepted Answer is incomplete.
You can try to use https://editor.swagger.io/
After importing yaml file You can generate Java REST Client project through menu with correspondent POJO classes.
Related
I've inherited a project which essentially maps large documents from one structure to another. The source and target documents are POJOs, and there are a number of transformer classes that map the source POJO to the target by using the getters/setters of each field.
For example, say we have:
public void transform(SourceDocument source, TargetDocument target) {
target.setField1(source.getField1());
target.setField2(source.getField5());
target.setField3(source.getField2());
target.setField4(source.getField4());
target.setField5(source.getField3());
}
We're looking to refactor large parts of this project and as part of it, our customer has requested that we document these mappings before we look to refactor with a better implementation.
There are several hundred of these mappings and before we get one of team to go through them all by hand, does anyone know of any tools that could analyse this code and produce a simple mapping document. All mapping have been strictly performed using getters/setters with no direct property access.
We can't give the actual code to our customer due to IP restrictions, and also it's the (non-technical) business who need this information, so ideally we need a very simple output, describing the mapping from source to target.
These transformers are still occasionally updated while we work on a new version, so I'd really prefer something that could generate the documentation we're after directly from the code rather than comments/annotations that would have to be manually updated by developers.
I'm new in Play 2 Framework v. 2.1.1 with Java and I'm looking for the best way to do the following without duplicating code.
To simplify, I have a Play 2 backoffice that uses an external API. I don't manage this API, but I call REST Services to perform operations over the api.
This API's objects are exactly the same as Play 2 Model Objects. But I don't want to duplicate the api objects to add Play validations and other annotations.
Is there any way to add this type of behavior using configuration files? I'm thinking about something like Hibernate hbm's for example.
For example:
Object in the unmanaged api: (I omit getters and setters for simplicity)
public class Entity{
public String field1;
public String field2;
}
Object that I want to avoid: (I omit getters and setters for simplicity)
public class Entity1{
#Required
#NonEmpty
#MinLength(3)
public String field1;
#Required
#NonEmpty
public String field2;
}
Config example: (I need something like this)
<class name="Entity1">
<property name="field1" >
<required/>
<nonEmpty/>
<minLength value="3"/>
</property>
<property name="field2" >
<required/>
<nonEmpty/>
</property>
</class>
Using annotations seems better than using xmls or any other configuration file, so I don't necessarily want to use configuration files, I'm open to any suggestions to solve this problem.
Thanks
I can't see how duplicating the API model in a non typesafe descriptor like XML is better than using a typesafe language. Moreover, I would not want to couple my model and application to a model from the API under my control.
I think it is far better to duplicate the model in Java/Scala and use a simple bean copier like dozer to move between the two.
One problem is ebean as the persistence provider - in ebean there is no way to externalize the bean persistence configuration as it is possible in hibernate (except for sql queries). Is a switch of the persistence provider possible? Play seems to allow that.
Since you wrote that you are unable to modify the entities source code and you don't want to copy the source, the only other possibility I see is bytecode enhancement.
What you need is a library that would allow you to externalize annotations in a xml file. This library would use the instrumentation api, read the xml file at jvm statup and modify the bytecode of each listed class in order to add annotations to the class and fields at runtime.
There are two problems with this approach:
There is no such library (at least I couldn't find it)
Play and EBean use their own agent / classloader in order to allow hot deployment and persistence
The first problem is the easy and fun part, see for example https://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html. With javaassist it is easy to add annotations to classes and fields. The mapping from xml to annotations is straight foreward. And it would be a nice open source project.
The second problem looks much harder, because you must install your annotation agent so that it executes before play and ebean start to parse the annotations.
It is not clear to me why can't add annotations in your own app, but if you have such constraints why don't you just extend the class, override the variables, add the annotations, and use that as an EBean model?
Play has dynamic forms, which let you validate against a map of key,value pairs. If validation is what you want you could copy an entity's data to a map and validate that.
Simple answer: There is not always code duplication also if the code lines are the same.
Robert C. Martin shows this in one of his talks: the single responsible principle. There are two ways to break this principle: On the one hand two responsibilities in one code fragment on the other hand one responsibility handled independently bei two code fragments.
Code duplication is a matter responsibility and semantics not of code lines that are the same (which may be at most an indicator for having code duplication).
In your case the responsibilities are clearly separated: You have an external API and your code. So there is no code duplication.
I am experimenting with JAXB library to read xml files and I see that I need to define the Class objects along with annotations to indicate the xml element structure. I was wondering if there is a way that I can read the xml file without having to define such a class. this will permit the user to add a new tag without having to redefine my class.
I am not particular about jaxb usage, any other java libraries are ok too.
Sure, if you just want to work with raw XML without binding it onto POJOs, you can use javax.xml.parsers.DocumentBuilderFactory/javax.xml.parsers.DocumentBuilder to read any arbitrary XML directly into a org.w3c.dom.Document and just work with it as a document instead of as mapped data.
Need to serialize java objects to JSON while doing compression such as name change, exclusion etc. Objects use class from jar, source code of which is not available.
Looked through many libraries(Jackson , Gson), but found none solving this particular problem. Most of them are annotations based, which I can't use given I don't have source code.
One way to solve this problems is, use reflection and recursively go through object until you find a property name of which should be replaced or object is excluded in serialized JSON.
Need solution for this. Better if it is already implemented and tested.
You can also have a look at Genson library http://code.google.com/p/genson/.
You can rename and filter with quite concise code:
// renames all "fieldOfName" to "toName", excludes from serialization
// and deserialization fields named "fieldNamed" and declared in DefinedInClass
// and uses fields with all visibility (protected, private, etc)
Genson genson = new Genson.Builder().rename("fieldOfName", "toName")
.exclude("fieldNamed", DefinedInClass.class)
.setFieldFilter(VisibilityFilter.ALL)
.create();
genson.serialize(myObject);
If you want to do some more complex filtering (based on annotations for example) you can implement BeanMutatorAccessorResolver or extend BaseResolver.
Same for property renaming you can implement PropertyNameResolver and have full control.
And finally if you want to filter fields, methods or constructors according to their modifiers you can define your own VisiblityFilter.
Concerning performances of filtering/renaming there should be no problem as it is done only once per class and then cached.
To start using Genson you can have a look at the Getting Started Guide.
Found solution to the problem.
Google gson has class called GsonBuilder which has methods for exclusion strategy and naming strategy.
Using these two methods implemented a custom solution, where all the mapping and exclusion rules are stored using a xml and used at the time of serialization and de-serialization.
Works perfectly, though not sure about the performance of same.
I am required to move some of our application configuration classes to XMLs. The classes mainly have enums, which are used by other classes. These enums are extensively used in our application.
For instance, we have classes like
enum ColumnType{
type1("Type1"),type2("type2"),type3("type3")
}
Also we need these types to instantiate classes.
for instance,
Processor p = new StringValueProcessor(ColumnType.type1);
How can I move this to an XML file without changing the dependecies in my application?
Edit:
It is not mandatory to keep these enums and I don't want to compile the code against the classes created from xml. The config needs to be dynamic, that's the whole point of moving to XML, so that we can configure things in XML and there is no need of compiling and re-deploying.
My main concern is to be able to restrict instances for all column types to one and make them accessible throughout my application.
Edit: After thinking over the design for some more time, I have narrowed down to two essential requirements.
1) I would define some xml tags with some properties and I would need to convert it to object
2) I would also define some tags (the way servlets are defined in web.xml) and I would need to initialise the corresponding class
3) I would further define some mapping tags which will map the objects created in step 1) to instances initialised in step 2). This should be converted to java HashMap, where there can be only one instance of objects defined in step 1) but there will be a new instance of objects defined in step 2) for each mapping.
Is there a framework which can provide this functionality out-of-the-box?
You can use the XML files to generate the enums. This has to be done at compile/build time, or you cannot use them in your code like the second example (as they don't exist at compile time)
Why do you want to migrate the enums to XML?
I think the answer your looking for is to use JAXB. It lets you turn XML into POJOs and vice-versa. It even has some functionality for using enums. All you have to do is add some annotations to your java and you can convert to and from XML.
By using annotations, you won't affect any existing functionality.