Converting Request scoped bean to JSON string - spring

I was facing an issue while converting a bean with request scope to JSON using object mapper. It thows an exception like below. Not sure what am missing. I couldn't find any relatable resource on the web. Can someone explain what should be the way to do this.
Thanks in advance.
Line of code :
planInfo -> Bean with request scope
String json = new ObjectMapper().writeValueAsString(planInfo);
Exception :
"timestampSeconds":1630567890,"timestampNanos":683000000,"severity":"ERROR","thread":"qtp133294616-216","logger":"com.signup.api.service.SignupService","message":"exception \ncom.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: jdk.internal.loader.ClassLoaders$PlatformClassLoader[\"unnamedModule\"]-\u003ejava.lang.Module[\"classLoader\"]-....
PlanInfo
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
#Data
#Component
#RequestScope
public class PlanInfo {
String additionalPlanDetails;
String additionalServiceCost;
String listOfAdditionalServiceIds;
String planMinutes;
String planPrice;
String totalamt;
String setUpFee;
String selectedPlanId;
String canadaProvince;
String vatAmount;
String vatPercentage;
String netTotalAmt;
String selectedIvrPlanId;
String selectedIvrPlanMinutes;
String selectedIvrPlanPrice;
String totalPlanPrice;
String totalAmtAfterDiscount;
boolean waiveSetupFee;
String planCategory;
}

Related

How to parse by Spring a name of a variable (key, but not value) from yaml when its name is changing?

I have a yaml file with a structure
section:
subsections:
subsectionName1:
param1: value1
param2: value2
subsectionName2:
param1: value1
param2: value2
I need to parse these properties as List<CustomClass>
#ConfigurationProperties(prefix = "section.subsections")
#Configuration
public class CustomClass {
private final String subsectionName; //the problem is there
private String param1;
private String param2;
//Constructors, getters, setters
How can I do this in Spring?
I see that this works in Micronaut this way:
import io.micronaut.context.annotation.Context;
import io.micronaut.context.annotation.EachProperty;
import io.micronaut.context.annotation.Parameter;
import lombok.EqualsAndHashCode;
#Context
#EachProperty("section.subsections")
#EqualsAndHashCode
public class CustomClass {
private final String subsectionName;
private String param1;
private String param2;
public CustomClass(#Parameter String subsectionName) {
this.subsectionName = subsectionName;
}
//getters, setters...
But I didn't manage to find something similar to io.micronaut.context.annotation.Parameter in Spring.
I need this to use the shared util class which accepts List as a parameter.
Are there any ideas on how to do this?
I really appreciate any help you can provide.
Maybe you can try something like that :
section:
subsections:
subsectionName1: value1,value2
And in your code you need to parse this using #Value annotation and split function of Strings
#Value("#{'${section.subsections:}'.split(',')}")
Set<String> subsections
In that case I use set, but you cant use list if you allow repeated values.

Could not extract response: no suitable HttpMessageConverter found for response type and content type [binary/octet-stream]

So i am consuming JSON response from this URL through RestTemplate
Link:
"https://s3-ap-southeast-1.amazonaws.com/he-public-data/productdf38641.json"
My Product POJO:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
#Data
#NoArgsConstructor
#AllArgsConstructor
public class ProductModel {
private String uniq_id;
private String product_name;
private int retail_price;
private int discounted_price;
private List<String> image;
private String description;
private String product_rating;
private String overall_rating;
private String brand;
}
Now when i use restTemplate to store this Array of Json object in ProductModel[].
ProductModel[] books = restTemplate.getForObject(URL, ProductModel[].class);
I am getting this error
Caused by: org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.schema.testing.domain.ProductModel] and content type [binary/octet-stream]
when i pass the same JSON object though postman to REST endpoint via POST request.
it is able to process that request.
IS this all game related to content-type.
Please help , what do i have to do next. i am not sure .
Any help is appreciated
I guess there is a solution for this exception. Try out and let me know the result.
Not any message converter can read your HTTP response, so it fails with an exception.
The main problem here is a content-type, In order to overcome this, you can introduce a custom message converter. and register it for all kinds of responses (i.e. ignore the response content-type header). Just like this
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
// We are making this converter to process any kind of response, not only application/*json, which is the default behaviour
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);

Add Two Conditions in JpaRepository

i am trying to do a POC - using JpaRepository filter out the data by adding two conditions.
I have written a code like below
public interface TemplateRepository extends JpaRepository<Template, Long> {
List<Template> findByTemplateNameContains(String templateName);//This is Working Fine
List<Template> findByTemplateNameAndActiveFlagContains(String templateName, String activeFlag);// My POC
}
templateName column is a VARCHAR2 and activeFlag is a Char in the Oracle Database. I am trying to filter the data with both templatename
and activeFlag.
I pass the input object in SoapUI app (POST) request.
{
"netting":"karu_test",
"activeFlag": "Y"
}
but I get the below error
"Parameter value [%Y%] did not match expected type [java.lang.Character (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [%Y%] did not match expected type [java.lang.Character (n/a)]"
I understand this error like, the ACTIVE_FLAG column is CHAR(1) so type mismatch happend. But how to achieve the same functionality ?
More over .. how to use multiple table joins and condition in JpaRepository
I changed the type of activeFlag to Char still i get the same error.
Template class
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Entity
#Table(name="TEMPLATE_DEF")
#Getter
#Setter
public class Template {
#Column(name="TEMPLATE_ID")
#Id
private String nettingTemplateId;
#Column(name="TEMPLATE_NAME")
private String templateName;
#Column(name="LAST_UPDATE")
private Date lastUpdate;
#Column(name="UPDATE_USER_ID")
private Integer updUsrId;
#Column(name="ACTIVE_FLAG")
private char activeFlag;
#Column(name="VERSION")
private Integer Version;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="CREATE_USER_ID")
private Integer createUsrId;
}
Please try the below JPA Query
List<Template> findByTemplateNameContainingAndActiveFlagContaining(String templateName, Character activeFlag);
Your Active flag is a char so no point in putting containing for activeFlag rather do a exact match, change method signature to
List<Template> findByTemplateNameContainsAndActiveFlag(String templateName, char activeFlag);// My POC
I have tested it it will match name with like and activeFlag based on value of it

Spring WebClient setting some fields to null when they are not null in the response body

I have domain class
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Data
#Document
public class Bar {
#Id
private String id;
private List<String> owners;
private List<String> cFeatures;
private Integer age;
private String color;
}
I am using below code to invoke API to get data in Bar object:
import org.springframework.web.reactive.function.client.WebClient;
Mono<Bar> prop = webClient.get()
.uri("/bars/"+id)
.header("Authorization", "Bearer " + access_token)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Bar.class).log("find by id")
The problem is that I get cFeatures as null even though original JSON response
has:
"cFeatures":["custom feature one", ""]
but owners list gets correct value even though owners also has empty string value in the list (not sure if thats the source of this bug)
so Bar object has:
cFeatures: null
Is this a bug in Webclient or am I missing something ? I spent whole day on this but no fix yet.
The problem was with lombok. Lombok was generating setter method:
setCFeatures
but jackson expects setter:
setcFeatures which it does not find and hence null value for cFeatures.
It can be helpful if you make sure your POJO has the correct annotation style. For example, use jsonscheme2pojo.org and choose "Json" as your source type and "Jackson 2.x" as your annotation style. That should make the problem disappear. I was stuck at first by the same problem because I used a Gson-annotated POJO.

Gson Custom deserializer

I want to deserialize json string to java object. My class structure is this
public class Category {
String name;
int id;
ArrayList<Catalog> catalogs;
}
and catalog class structure is this
public class catalog {
private int catalogId = 0;
private String catalogName;
}
Following code i used to deserialize
Gson gson = new Gson();
ArrayList<Category> categories = gson.fromJson(jsonString, Category.class);
I got exception when it try to deserialize ArrayList catalogs;
If i remove ArrayList then it parse successfully
Thanks
Pawan
I solved this problem. The problem is that the string which i am parsing contain boolean value instead of Array . So There is exception while parsing.
The reason is that datatype is not match in json string which is parsed.
Thanks

Resources