How do I suppress CheckStyle StrictDuplicate warning? - checkstyle

I am trying to suppress CheckStyle StrictDuplicateCode warning, and it does not work.
In my Eclipse project, I have two classes with similar fields:
public class MyClass {
// CHECKSTYLE:OFF
private String field1;
private String field2;
private String field3;
private String field4;
private String field5;
private String field6;
private String field7;
private String field8;
}
public class MyDuplicateClass {
// CHECKSTYLE:OFF
private String field1;
private String field2;
private String field3;
private String field4;
private String field5;
private String field6;
private String field7;
private String field8;
}
Putting "CHECKSTYLE:OFF" comment in one or both classes does not suppress the warning.
Am I missing something?

Make sure you configured the SuppressionCommentFilter correctly, for example:
<module name="Checker">
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE\:OFF ([\w\|]+)"/>
<property name="onCommentFormat" value="CHECKSTYLE\:ON ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
<module name="TreeWalker">
...

Related

JSON parse error: Cannot deserialize value of type `java.time.LocalDate`

Im trying to send a post to my api using postman:
But its returning an error:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.time.LocalDate from String "10/11/2022": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '10/11/2022' could not be parsed at index 0;
I tried to correct do the mapping with json mapping annotation in the dto class:
#Data
#Builder
public class OfertaEspecialDTO {
private String nome;
private final double desconto_percentual;
private String descricao;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate dataValidade;
}
But its still returning me the error.
How is the correct way to map my dateTime instance variable?
There is no issue with LocalDate instance variable mapping. Issue is with annotations used on top of class. Please refactor DTO class like this and try again.
#Setter
#Getter
public class OfertaEspecialDTO {
private String nome;
private double desconto_percentual;
private String descricao;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate dataValidade;
}
or like this
#Data
public class OfertaEspecialDTO {
private String nome;
private double desconto_percentual;
private String descricao;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate dataValidade;
}

Json Spring Boot Jackson How do I deserialise Json that has a child entity that has a namespace prefix?

I'm attempting to deserialize this json in my Spring Boot server application (which uses Jackson). Its throws an com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field. The prefix seems to be an issue and I can tell Jackson to ignore the user_metadata field and it works fine, however I do need to access that value. I've had a look through the various Spring #Json annotations and none seem to deal with the prefix.
{
"sub":"",
"nickname":"",
"name":"",
"picture":"",
"updated_at":"2020-05-01T11:23:01.110Z",
"email":"",
"email_verified":false,
"https://somedomain:eu:auth0:com/user_metadata":{
"tennant":"value"
}
}
And the model classes in Java
public class UserMetaData {
private String tennant;
public String getTennant() {
return tennant;
}
public void setTennant(String tennant) {
this.tennant = tennant;
}
}
public class UserInfo {
private String email;
private String sub;
private String picture;
private String nickname;
private Date updated_at;
private boolean email_verified;
private UserMetaData user_metadata;
private String name;
}
Getters and setters removed for brevity
Stack trace below:-
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "https://raptorsoftware:eu:auth0:com/user_metadata" (class uk.co.raptorsoftware.domain.UserInfo), not marked as ignorable (8 known properties: "sub", "user_metadata", "updated_at", "name", "email", "picture", "email_verified", "nickname"])
at [Source: (String)"{"sub":"","nickname":"darren.roberts","name":"","picture":"https://s.gravatar.com/avatar/c496e319edc303163f2e87e5ca91507d?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fda.png","updated_at":"2020-05-01T16:39:11.271Z","email":"darren.roberts#","email_verified":false,"https://raptorsoftware:eu:auth0:com/user_metadata":{"tennant":"some value"}}"; line: 1, column: 411] (through reference chain: uk.co.raptorsoftware.domain.UserInfo["https://raptorsoftware:eu:auth0:com/user_metadata"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61) at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:840)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1206)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1592)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1570)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3205)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3173)
at uk.co.raptorsoftware.web.BaseController.getUserInfo(BaseController.java:49)
at uk.co.raptorsoftware.web.MemberController.listMembers(MemberController.java:49)'''
The problem is the url as key of the UserMetaData. Try to use #JsonProperty
public class UserInfo {
private String email;
private String sub;
private String picture;
private String nickname;
private Date updated_at;
private boolean email_verified;
#JsonProperty(name="https://somedomain:eu:auth0:com/user_metadata")
private UserMetaData user_metadata;
private String name;
}

convert json String to array java object by Gson

I never understand that how can I use gson.
this is my json string that is fetched from my web service:
{
"GetHistoricalNotificationsInTopicByFilterResult":[
{
"BusinessCode":"10-1-75-16-1-3-0",
"CreationDateTime":"\/Date(1502550561602)\/",
"DeviceId":"8998432005",
"Distributions":null,
"EventData":[ ],
"EventId":"com.test.revisit.events",
"EventTitle":"sending",
"Id":"69dbc367-09ws-bf3c-9re8-5c6b35ecbrtg",
"ProcessId":"4ebb6271-bf3c-9re8-a148-5c6b35ec458",
"SystemId":"com.safarayaneh.revisit",
"SystemTitle":"seeing",
"UserFullName":"jack",
"UserId":"69dbc367-32f3-4e94-bf3c-5c6b35ec3456",
"WKT":"POLYGON ((59.0 36.0, 59.01 36.01, ...))",
"WorkItemId":2354365
},{
....
}
and this is my contract class:
public class SaveNotify implements Parcelable {
private long id;
private String NotificationID;
private String MessageID;
private String CreationDateTime;
private String DeviceId;
private String UserId;
private String UserFullName;
private String SystemId;
private String SystemTitle;
private String EventId;
private String EventTitle;
private String EventData;
private String BusinessCode;
private String ProcessId;
private String WorkItemId;
private String WKT;
private String Distributions;
private String Address;
private String SaveDate;
private String Status;
private String DistributionId;
private String SchedulerCreationDateTime;
private String ExpirationDateTime;
how can I convert json string that i receive from my webservice to pojo class as array list? I want to put this list to my recycler view adapter for showing this info as a list.
What you need to create is an object that gets the field GetHistoricalNotificationsInTopicByFilterResult
public class MainObject implements Parceable{
List<SaveNotify > GetHistoricalNotificationsInTopicByFilterResult;
}
And then, with Gson parce you JSON to The MainObject
Gson gson = new Gson();
MainObject mainObject = gson.fromJson(jsonString, MainObject.class);

Modifying objects list fileds saved as LONGBLOB in MySQL

I have a table "Project" in my MySQL Databse that contains an ArrayList saved as LONGBLOB (FiledDetailsData).
public class ProjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String projectName;
private String city;
private int nbFields;
private List<FiledDetailsData> FiledDetails;...
I already have alot of data saved and would like to keep it. The problem is that I had to change to structure of FiledDetailsData to add new fields
I've changed it from
#Embeddable
#XmlRootEllement
public class FiledDetailsData implements Serializable`{
private String id;
private String lot;
private String number;
private String street;
private String size;
private String status;
to
#Embeddable
#XmlRootEllement
public class FiledDetailsData implements Serializable`{
private String id;
private String lot;
private String number;
private String street;
private String size;
private String status;
private BigDecimal extraField;
private BigDecimal extraParking;
When I try to run the application with the previous data, I get this error
Could not deserialize object from byte array. Internal Exception: local class incompatible
I can fin it by deleting the LONGBLOB in my DAtaBase and recreating it, but then I lose all my data.
here are my save/edit methods
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
Thank you.

Resteasy JAXB output Json field order

My code is something like:
#XmlRootElement
#XmlType(propOrder = {"id", "name", "content", "disclaimer", "buttons"})
public class Product {
private String id;
private String name;
private String content;
private String disclaimer;
private List<ProductButton> buttons = new ArrayList<ProductButton>();}
Service code is:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/GetProduct")
public Response getProduct() {
try {
Product product = generateProductById(productId);
return Response.ok().entity(product).build();
}
catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
return Response.serverError().build();
}
}
However the output json string is not in order.
My expected order is same as my object, however the result is: "name", "id", "content"...
Anyone got idea how i can achieve that?
--------------------------------------Updated--------------------------------
#JsonPropertyOrder({"id", "name", "content", "disclaimer", "buttons"})
public class Product {
private String id;
private String name;
private String content;
private String disclaimer;
private List<ProductButton> buttons = new ArrayList<ProductButton>();}
Use the resteasy-jackson-provider and then annotate your class with the #JsonPropertyOrder annotation.
Here is the Maven dependency for the provider. If you are not using Maven just add this jar to your classpath.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
Example:
#JsonPropertyOrder({
"user_id",
"user_name",
"email"
})
public class User
{
#JsonProperty("user_id")
private Long userId;
#JsonProperty("user_name")
private String username;
private String email;
//Getters and Setters Removed for Brevity
}