I am working on a Spring project wherein I have a POJO class
public class Owner extends Person {
private String address;
private String city;
private String telephone;
Getters and Setters
#Override
public String toString() {
return new ToStringCreator(this)
.append("id", this.getId())
.append("new", this.isNew())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
}
}
I have two doubts why a toString() method is being used here? What is its use?
What is ToStringCreator method doing?
As per official docs
ToStringCreator is a Utility class that builds pretty-printing toString() methods with pluggable styling conventions. By default, ToStringCreator adheres to Spring's toString() styling conventions.
It is a helper class for customizing toString() presentation.
Related
I'm working on a rest api project with spring boot and hibernate, and I'm wondering on json serialization of RestController using Jackson.
Here is the problem: I use external hibernate entities class defined in a library I cannot edit. This classes are very complex and define lot of field I'm not interested in when I return the object with the rest api.
Actually, I've solved the problem wrapping the original class with a wrapper class that exposes only the values I want to return from the controller.
Eg:
original class
class AccountEntity {
///...
public String getName() {
return this.name;
}
/// ... Lot of code here
}
Wrapper class:
class AccountWrapper {
AccountEntity original;
public AccountWrapper(AccountEntity original) {
this.original = original;
}
public String getName() {
return this.original.getName();
}
}
and the use the Wrapper as following
#RestController("/api/user")
public class UsersController {
#GetMapping("/")
public AccountWrapper getUser() {
AccountEntity account = //get account in some way
AccountWrapper accountWrapper = new AccountWrapper(account);
return accountWrapper;
}
}
The method works well, but it's not very clean and makes stuff more complex (e.g., when I have to return lists), because I always have to wrap the original class.
I didn't found a method to make me able to specify which fields I want to serialize without modify (and I cannot) the original class.
Any help?
Instead of using a wrapper class, create a DTO object for the rest API that will be leaner than the DB entity and a trasformer to create DTO from entity (and vice a verce)
The difference from using a wrapper here is that the DB entity is not part of the DTO, and thus does not need to be serialized on the response.
The big advantage here is that you separate the DB layer from the API layer, which makes it more flexible and easy to manage.
you can read more about this pattern here
Apparently, you can use Jackson Mixins to annotate a class with Jackson annotations.
See this answer for example.
The idea is to create an class with the annotations you want and to use objectMapper.getSerializationConfig().addMixInAnnotations() to register the MixIn with your class.
For example:
//Class you don't controll
public class User {
private String name;
private String password; //attribute we want to omit
//... getters and setters
}
public abstract class UserMixIn {
#JsonIgnore String getPassword();
}
objectMapper.addMixInAnnotations(User.class, UserMixIn.class);
Hope it helps,
I have a class (Account) that represents the user's system. Account contains a field role. It is the enum that contains three cases.
Account class
public class Account extends Model {
#Id
#Email
public String email;
#Required
#NotNull
public String password;
#Required
#NotNull
public String firstName;
#Required
#NotNull
public String lastName;
#Required
public String phone;
public MyRole role;
MyRole
public enum MyRole {
ADMIN,
TEACHER,
USER
}
How can I implement an authorization?
I think you could use Deadbolt-2 library, listed in the Play Framework plugins.
In the same idea of not reinvent the wheel, did you take a look at the Play-Authenticate plugin ? An another advantage of this last one is that it is compatible with Deadbolt-2.
Deadbolt-2 library is a solution. However, if you want to build your very own one, firstly, you need to read https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition.
Actually, it is not that difficult and you can implement almost unlimited, very flexiable solution.
The basic idea is to define a UserAuthAction, like:
#Singleton
class UserAuthAction #Inject() (principalService: PrincipalService) extends ActionBuilder[Request] with ActionFilter[Request] {
override protected def filter[A](request: Request[A]) = Future.successful {
request.session.get(principalService.accessTokenCacheKey).map { accessToken =>
if (principalService.authenticate(accessToken))
None
else
Some(Results.Redirect(routes.PrincipalController.login()))
} getOrElse {
Some(Results.Redirect(routes.PrincipalController.login()))
}
}
}
And then compose it with the actions the do the actually job. For example:
#Singleton
class Application #Inject() (userAuthAction: UserAuthAction) extends Controller {
def index = (userAuthAction andThen anyAction) { request =>
Ok(views.html.index())
}
}
Along the way, if you are using ActionRefiner, you can even extract additional user information and provide it to the latter actions, such as anyAction above.
Is there any way to use JAXB annotations on default methods inherited from Java 8 interfaces?
I created a sample maven project at https://github.com/ruckc/jaxb-java8-javafx highlighting the shims required for what I would like to do.
In dealing with JavaFX properties, i've found that I can use the default methods on interfaces to remove the annoying getters/setters from the data object.
public interface Named {
#XmlAttribute(name="name")
default String getName() {
return nameProperty().get();
}
default void setName(String name) {
nameProperty().set(name);
}
StringProperty nameProperty();
}
This removes alot of redundant code inside the implementations. My issue is that now, when trying to marshall the objects using JAXB, I still have to implement the methods (annotated with #Shim) in the implementations, so that the annotations are picked up.
#XmlRootElement(name="business")
public class Business implements Named {
private final StringProperty nameProperty = new SimpleStringProperty();
#Shim
#Override
public void setName(String name) {
Named.super.setName(name);
}
#Shim
#XmlAttribute(name="name")
#Override
public String getName() {
return Named.super.getName();
}
#Override
public StringProperty nameProperty() {
return nameProperty;
}
}
In short, if I remove the #Shim the printed out xml from the main method doesn't contain the name attribute, and the printed out name attribute from the unmarshalled string is null. I'd really like avoiding spurious/duplicate code.
I'm looking for an eclipse plugin that can generate fluent API methods in my beans.
For instance, given this bean:
public class MyBean {
private String name;
private int age;
//Setters and getters
}
Is there any eclipse plugin that generates these methods for me?
public class MyBean {
private String name;
private int age;
public MyBean withName(String name) {
setName(name);
return this;
}
public MyBean withAge(int age) {
setAge(age);
return this;
}
//Setters and getters
}
I've found a google plugin that generates Builder objects, but I prefer fluent API inside each Bean class.
While can't find anything, you can do like me.
Generate the setters, then "Find" (checking "regular expressions") for:
\tpublic void set(.+)\((.+)\) \{\R\t\tthis\.(.+) = (.+);\R\t\}
 and replace with:
\tpublic [PUT_TYPE_HERE] with$1\($2\) \{\R\t\tthis\.$3 = $4;\R\t\treturn this;\R\t\}
Probably there's a simpler expression, but this works ;)
[UPDATE] # 07-MAR-2018
I'm now using lombok which generates getters, setters and builders throught simple annotations. (#Getter, #Setter and #Builder respectively)
It can generate with methods using the #Wither annotation too, but unfortunately its an experimental feature so it should be avoided.
In playframework, it uses javassist library to let the public fields of a class can be used as property.
See the example:
public class User {
public String name;
}
User user = new User();
user.name = "Freewind"
System.out.println(user.name);
In compilation time, play enhanced the bytecode with javassist, the final code is similar to:
public class User {
private String name;
public String getName() { return this.name; };
public void setName() { this.name = name; };
}
User user = new User();
user.setName("Freewind");
System.out.println(user.getName());
You can see not only the field name has getter and setter, but also the invocations of it changed to getters and setters.
I wonder if there is any other way to do the same (use other things than javassist)?
I found Annotation Processing Tool, but I'm not sure it can do it.
Or aspectj? Or something else?
You can look at Project Lombok, which does something similar, but with annotations. With project lombok you do need to use the getters and setters in your own code.
Not without other tools.
Unlike C#, Java does not support properties.