Tuesday, March 27, 2018

Could not write content: Infinite recursion (StackOverflowError) (through reference chain: org.hibernate.collection.internal.PersistentBag[0]

The problem., I was getting a wrong JSON response while using a many-to-many relationship, that caused my application to enter in an infinite loop giving as output an infinite recursion Stackoverflow error.
Here is part of what I found in my Eclipse console:
Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain: [here is the loop]) with root cause
java.lang.StackOverflowError
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:567)
 at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:143)
 at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:118)
 at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:24)
 at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:180)
 at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:544)
 at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:551)
 ...

and so on.
As the docs state (see references), bi-directional references for ORM-managed beans (iBatis, Hibernate) would cause serialization to failure since they are cyclic dependencies. Since Jackson 1.6, this problem has been solved by the introduction of two new annotations: @JsonManagedReference and @JsonBackReference(and see the end of this post to give a look at the @JsonIdentityInfo annotation).
How does serialization work? (The solution in theory)
In computer science, in the context of data storage and transmission, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and resurrected later in the same or another computer environment. 
For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the annoying infinite recursive loop that causes our stackoverflow error.
So, Jackson takes the forward part of the reference, for example an attribute of a java class (i.e. List<Role> roles in User class), and converts it in a json-like storage format; this is the so-called marshalling process. 
Then, Jackson looks for the back part of the reference (i.e. List<User> users in Role class) and leaves it as it is, not serializing it. This part of the relationship will be re-constructed during the deserialization (unmarshalling) of the forward reference.
The solution in practice.
It's very simple. Assuming that your database query already works without JSON, all you have to do is this:
  1. Add the @JsonManagedReference In the forward part of the relationship (i.e. User.java class):
    @Entity
    public class User implements java.io.Serializable{
     
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private long id;
     
     @Column(name="name")
     private String name;
    
     @ManyToMany
     @JoinTable(name="users_roles",joinColumns=@JoinColumn(name = "user_fk"),
     inverseJoinColumns=@JoinColumn(name = "role_fk"))
     @JsonManagedReference
     private Set<Role> roles = new HashSet<Role>();
    
    ...
    
  2. Add the @JsonBackReference In the back part of the relationship (i.e. Role.java class): 
    @Entity
    public class Role implements java.io.Serializable {
    
     @Id 
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;
    
     @ManyToMany(mappedBy="roles")
     @JsonBackReference
     private Set<User> users = new HashSet<User>();
    
    ...
    
The work is done. If you take a look at your firebug logs, you'll notice that the infinite recursive loop has disappeared.

Resource Link:  

How To Solve JSON infinite recursion Stackoverflow (with Spring and Jackson annotations)


Monday, March 12, 2018

New git tips and tricks

Viewing New and Recent Connections and Contacts in Linkedin

You can view a list of your 1st-degree Connections on the Connections page. You can sort your connections by name or by most recently added.
To sort your connections list to show the most recently added at the top:
  1. Click the  My Network icon at the top of your LinkedIn homepage.
  2. Click See all below Your connections on the left rail.
  3. Click the Sort by  dropdown above your connection list and select Recently added (which is usually selected by default).
You can view a list of your synced and imported contacts from the Contacts page.
To view and sort your contacts list to show the most recently added at the top:
  1. Click the  My Network icon at the top of your LinkedIn homepage.
  2. Click See all below Your connections on the left rail.
  3. Click  Manage synced and imported contacts on the right rail.
  4. Click the Sort by  dropdown above your connection list and select Recently added (which is usually selected by default).
Note: You can only sort by Recently added for synced contacts.

SSO Login Demo

Wednesday, March 7, 2018

Java 8 at a glance

runAsync() method:
=================
If you want to run some background task asynchronously and don’t want to return anything from the task, then you can use CompletableFuture.runAsync() method.

supplyAsync() method:
=====================
Run a task asynchronously and return the result using supplyAsync()

get() method:
=============
The CompletableFuture.get() method is blocking. It waits until the Future is completed and returns the result after its completion.

Example: String result = completableFuture.get()

CompletableFuture.complete() method:
===================================
CompletableFuture.complete() method is used to manually complete a Future.

Example: completableFuture.complete("Future's Result")

All the clients waiting for this Future will get the specified result. And, Subsequent calls to completableFuture.complete() will be ignored.

thenApply() method: [Will return]
===================
done sequentially after completion one by one. First one is completed first, then second one will start taking the first one's output.

thenApply() method is used to process and transform the result of a CompletableFuture when it arrives.

You can also write a sequence of transformations on the CompletableFuture by attaching a series of thenApply() callback methods. The result of one thenApply() method is passed to the next in the series


thenAccept() method: [Wouldn't return]
===================
thenRun() method:
=================

If you don’t want to return anything from your callback function and just want to run some piece of code after the completion of the Future, then you can use thenAccept() and thenRun() methods. These methods are consumers and are often used as the last callback in the callback chain.

CompletableFuture.thenAccept() takes a Consumer<T> and returns CompletableFuture<Void>

thenCompose() method:
=====================

thenCombine() method:
=====================

thenApplyAsync() method:
========================

CompletableFuture.allOf() method:
=================================

CompletableFuture.anyOf() method:
=================================


Difference between thenAccept() and thenRun():
==============================================
CompletableFuture.thenAccept() takes a Consumer<T> and returns CompletableFuture<Void>. It has access to the result of the CompletableFuture on which it is attached.

// thenAccept() example
CompletableFuture.supplyAsync(() -> {
return ProductService.getProductDetail(productId);
}).thenAccept(product -> {
System.out.println("Got product detail from remote service " + product.getName())
});
While thenAccept() has access to the result of the CompletableFuture on which it is attached, thenRun() doesn’t even have access to the Future’s result. It takes a Runnable and returns CompletableFuture<Void> -

// thenRun() example
CompletableFuture.supplyAsync(() -> {
    // Run some computation 
}).thenRun(() -> {
    // Computation Finished.
});

Resource Link: https://www.callicoder.com/java-8-completablefuture-tutorial/


AWS S3 Image Upload + Swagger + Spring Boot + User Login and Registration Example

https://o7planning.org/en/11679/spring-boot-file-upload-example
http://zetcode.com/springboot/uploadfile/
http://javasampleapproach.com/java-integration/upload-multipartfile-spring-boot
http://javasampleapproach.com/frontend/angular/angular-4-uploadget-multipartfile-tofrom-spring-boot-server
https://github.com/swagger-api/swagger-codegen/blob/master/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java
https://github.com/brant-hwang/spring-cloud-aws-example/blob/master/src/main/java/com/axisj/spring/cloud/aws/controllers/UploadController.java
https://github.com/hellokoding/uploadingfiles-springboot/blob/master/src/main/java/com/hellokoding/uploadingfiles/UploadingController.java
http://javasampleapproach.com/spring-framework/spring-boot/multipartfile-create-spring-angularjs-multipartfile-application-downloadupload-files-springboot-angularjs-bootstrap
http://www.javainuse.com/spring/bootupload




VVI:
===
https://github.com/vatri/spring-rest-ecommerce/blob/master/src/main/java/net/vatri/ecommerce/controllers/ProductController.java
https://github.com/springfox/springfox/issues/1072
http://javasampleapproach.com/spring-framework/spring-cloud/amazon-s3-uploaddownload-files-springboot-amazon-s3-application
https://medium.com/oril/uploading-files-to-aws-s3-bucket-using-spring-boot-483fcb6f8646
https://hellokoding.com/uploading-multiple-files-example-with-spring-boot/


Friday, March 2, 2018

How to create a wrapper in gradle?

Make sure that the build.gradle has the "wrapper" task as below:

task wrapper(type: Wrapper) {
     gradleVersion = '4.6'
}
Run the "gradle wrapper" from the command line, it would create the gradle wrappers.

After that you can push those files to source control so that,no manual steps is required later.


Commands are given below:

$ gradle wrapper
$ git add gradlew gradlew.bat gradle
$ git commit -m "Adding gradle wrapper to git repo"
$ git push

So all the future builds can be using gradlew

$ ./gradlew build
:framework:compileJava
:framework:processResources
:framework:classes
:framework:jar
:compileJava
:processResources
:classes
:findMainClass
:jar
:bootRepackage
:assemble
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
:check
:build
:framework:findMainClass
:framework:bootRepackage
:framework:assemble
:framework:compileTestJava
:framework:processTestResources UP-TO-DATE
:framework:testClasses
:framework:test
:framework:check
:framework:build
BUILD SUCCESSFUL
Total time: 42.712 secs

Resource Link:
==============
https://stackoverflow.com/questions/42675234/spring-boot-1-3-3-is-not-building-with-gradle-3-0