Can Lombok toString() output include newlines? - java

I would like Lombok's toString() output to put each value on its own line. Enabling it like this would be great:
#ToString(includeNewLines = true)
public class MyClass {
...
}
Anything like that possible?

There is currently no direct #ToString annotation support for output formatting as described in your question. In fact, the Lombok #ToString documentationref includes the following disclaimer:
We don't promise to keep the output of the generated toString() methods the same between lombok versions. You should never design your API so that other code is forced to parse your toString() output anyway!
You could use: #ToString(onlyExplicitlyIncluded = true) to suppress normal toString field processing along with #ToString.Include to call an instance (non-static) method that takes no arguments to implement custom formatting, but that pretty much defeats the whole purpose.
If custom toString output formatting is important to you, a better option is available in the Apache Commons Langref org.apache.commons.lang3.builder package, which provides output format control using the ToStringBuilderapi and ToStringStyleapi classes.

Related

Lombok's #Builder and Javadoc Creation

In one of my projects, I'm handling some POJOs that may have 20+ fields. I'm using the Builder Pattern to make object creation less cumbersome. Lombok's #Builder annotation really removes a lot of boilerplate code and speeds up my process. Thing is that I want to add Javadoc to the 'setter'-like methods in the various builders of my project. I've tried to put the Javadoc to the fields just like Lombok's recommendation on #Getter/#Setter but it doesn't seem to work. Is there any possible method to achieve what I want?
You can also use #Accessors(chain = true) instead of #Builder.
Your Getter and Setter will return your instance and you can also use Method-Chaining like in Builder Pattern.
The syntax will be like
Model model = new Model().setId(23L).setTitle("test");
We always use this instead of #Builder.
Lomboks recommendation should work with this solution

autogenerate pojos with builder methods

Presently I am using swagger codegen tool to convert a RAML definition into swagger format and generating java client from this format. This gives me POJOs for all the data types mentioned in the RAML. Every time I change some data field in the RAML types, I have to regenerate the POJOs and all the code implementation in service layers has to be rewritten. It is becoming very cumbersome to repeatedly do the same things.
I am thinking if only these POJOs were generated with builder pattern, like,
mydataobject.builder.addfield1(10).addfield2(2);
it will greatly help me keep the code in service layer untouched.
Is there a way to auto-generate pojos that have builder methods in them?
You can use Lombok for that.
#lombok.Builder// Builder companion class, and static method
#lombok.Value // Getters, setters, and contructors
class Pojo {
String value;
Number number;
}
Which gives you this code:
final Pojo pojo = Pojo.builder()
.value("foo")
.number(100)
.build();
You have to proceed your generated code in order to add this annotations, see Add lombok (or any) annotation to swagger generated class for discussion of that.

GWT interface like Constants

In my application I need to use dynamic localization, so I cannot use Constants interface. I did use Constants for a while, but now I need texts to be changed without compiling so I had to find some other way.
So I am using Dictionary now. The thing is, when I now want to use text in UiBinder, I can only use methods without arguments. So I created class "StringIdentifiers" where I have the same methods I previously had in MyConstants, but I have to specify a body here for every method to return the specified String.
So for example I have:
Dictionary locale = Dictionary.getDictionary("myJsObjectWithStrings");
//and then the methods for returning the actual strings from the JS object
String loading(){
return locale.get("loading");
}
I would like the method to only be
String loading();
since the rest is always the same with the name of the method appearing as String parameter in the get() method. Possibly even returning some default value when the String is missing in the JS object. But I do not know how to do that. I checked the Constants interface, but I do not really understand the code there. Can someone please give me an example how to implement such a thing?
There is no standard feature in GWT to do this, but you could create one yourself. It's a bit of a stretch, but it should work by using the GWT generator mechanisch. In global terms it should work as follows:
Create an interface (say MyMessages) with a the method names.
To use it use MyMessages message = GWT.create(MyMessages.class). Where you need the text message.loading().
Create a generator that generates an class implementing the interface. This class will created at compile time and should contain the implementation of the interface methods, like in your example.
Add a generate-with tag in your gwt.xml file to make it work.
This is a bit of a brief explanation, but I hope it helps. For more background information about generators see: What is the use GWT generator? or http://blog.arcbees.com/2015/05/26/how-to-write-gwt-generators-efficiently/
You could even reuse some of GWT's annotation's of the i18n to add for example default texts. Add the annotation to your interface and in the generator scan the annotation and use it in the code generation part.

Swagger with Spring-MVC and custom serializers

I am trying to use Swagger to document a Spring-MVC based REST-API and am having problems getting Swagger to reflect the use of custom serializers and deserializers.
Because the JSON must conform to an established format (which is not particularly well designed) and I wanted to have a properly designed API model in the Java classes, I have used a few custom implementations of JsonSerializer to generate the JSON output. When I enable Swagger with annotations in the Spring-MVC controllers, the generated documentation ignores the custom serializers and describes the model as if it had been serialized with the default Jackson settings. So far so good, I didn't really expect Swagger to automatically understand the implementation of the serializers.
What I however would expect (and I can't find anything about this in the Swagger documentation) is a way to use Swagger annotations on the relevant attributes in the model classes to manually describe the model. Am I missing something or is it really not possible to Swagger as a documentation tool in connection with custom serializers (or deserializers for that matter)?
Edit: The Swagger documentation is not particularly good, but I have already tried to work with #ApiModelProperty on the deviating properties. As far as I can see, it has absolutely no effect on the generated output (tested with Swagger-SpringMVC 0.8.5 and 0.9.5).
You can use model substitutes for e.g. Lets say you have a service
#RequestMapping(value = { "/some-resource" }, method = POST,
consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<Void>
businessTypeEcho(#RequestBody CustomSerializableResource business) {
return new CustomSerializableResource();
}
you can setup a type substitution rule that tells springmvc how to represent the custom serializable type in the swagger ui.
#Bean //Don't forget the #Bean annotation
public SwaggerSpringMvcPlugin customImplementation(){
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.directModelSubstitute(CustomSerializableResource.class, SubstitutedSerializableResource.class)
.includePatterns(".*pet.*");
}
class SubstitutedSerializableResource {
//getters and setters that describe what
//CustomSerializableResource should look like in the UI
}
Unfortunately, this is going to create a parallel universe of types that aren't used at runtime.
Update:
If I understand your comment correctly, you're using it to format system-wide types i.e. booleans to Y/N or dates to mm/dd/yyyy perhaps. IMO, what you're probably looking for is to use model substitutes (see example above).
Substitute Date with String (this is the prescriptive guidance) In the case of dates your only option to communicate the format expected unfortunately is only via a textual description of the particular field or property.
Substitute Boolean with a enum you can create i.e. YesNoEnum that represents how you expect the objects to be serialized. This will provide the documentation with a set of allowed values.
At the end of the day, its a trade-off between creating these meta classes just for documentation vs. standardizing the API models to use serialization primitives as much as possible.

How To Populate A JavaBean Other Than Using Reflection

do you know if there is anyway that I can populate a javabean but i don't want to use reflection.
For example I have this xml template to pouplate it
Sample XML File
<property name = "card" value = "cdd"/>
public class Customer {
private String card;
public void setCard(String card) {
this.card = card;
}
public String getCard() {
}
}
I want to call setCard on the Java bean but I don't want to use reflection
since I've used it before and it's quite slow,
Are there any alternatives? How does Hibernate do it for example?
Thanks
Carlo
The only faster way (i.e. faster than using reflection) to populate a JavaBean from XML is to either write or generate some binding code that calls the setters with values extracted from the XML (in this case, from the XML attributes).
Hand writing the binding code is the simplest approach ... provided you don't have much to write.
Code could be generated as source code and compiled.
Code could be generated using a bytecode generation technology such as BCEL or ASM.
There may some existing XML-to-JavaBean binding generator, though existing bindings may well use reflection rather than code generation.
However, it is not clear this is worth going to the bother of avoiding reflection. While reflection is relatively expensive, XML is probably significantly more expensive. I'd recommend doing some profiling before you decide to use a more complicated implementation approach.
I'm pretty sure Hibernate uses reflection APIs deep under the hood. Groovy also has some nice support for automatically generating and using bean getters/setters which also ultimately use reflection under the hood as well.
Now there is an option where you could hard code your parser to read the xml and call the appropriate setter given the name attribute, but you run into the problem of your parser becoming brittle (when your model changes if that makes sense).
If the Bean is your's you may implement an interface like this:
/** Tries to set the property named key with the value given and returns true for success or false otherwise. */
boolean set(String key, Object value);
Then simply cast to that interface and try to use that method to set the properties. It sure needs some work in the bean - but avoids reflection.

Categories