Problems implementing Interface in graphql - java

I am trying to implement an interface in graphql and stuck in a loop.
I am getting the following error
Object type 'FeaturedCourseDto' implements a known interface, but no class could be found for that type name. Please pass a class for type 'FeaturedCourseDto' in the parser's dictionary.
So I add Featured Element Dto to the dictionary, but then get
value already present: class x.x.x.FeaturedCourseDto
My dictionary code below has some commented out fields because I've been flipping around trying all sorts of combinations to no avail...
Any help would be appreciated.
Here is my graphql code
interface Featurable {
guid: ID
entityGuid: ID
friendly: String
description: String
institutionName: String
institutionFriendly: String
primaryImageUrlBase: String
primaryImageUrlPath: String
}
type FeaturedElementDto implements Featurable{
guid: ID
type: String
entityGuid: ID
friendly: String
description: String
institutionName: String
institutionFriendly: String
primaryImageUrlBase: String
primaryImageUrlPath: String
orderNumber: Int
}
type FeaturedCourseDto implements Featurable{
guid: ID
type: String
entityGuid: ID
friendly: String
description: String
institutionName: String
institutionFriendly: String
primaryImageUrlBase: String
primaryImageUrlPath: String
orderNumber: Int
author: String
syllabus: String
trailer: String
}
type FeaturedListDto {
guid: ID
friendly: String
description: String
elements: [Featurable]
}
My Java code
#Getter
#Setter
#NoArgsConstructor
public class FeaturedElementDto {
private UUID guid;
private String type;
private UUID entityGuid;
private String friendly;
private String description;
private String institutionName;
private String institutionFriendly;
private String primaryImageUrlBase;
private String primaryImageUrlPath;
private Integer orderNumber;
}
#Getter
#Setter
#NoArgsConstructor
public class FeaturedCourseDto extends FeaturedElementDto {
private String author;
private String syllabus;
private String trailer;
}
#Bean
public SchemaParserDictionary schemaParserDictionary() {
return new SchemaParserDictionary()
// .add("Featurable", Featurable.class);
.add("FeaturedElementDto", FeaturedElementDto.class);
// .add("FeaturedCourseDto", FeaturedCourseDto.class);
}

Related

Lombok #delegate annotation not passing values to innerDTO

inside my test class
String json="{\n" +
"\t\"masterName\": \"test1\",\n" +
"\t\"masterSubjectName\": \"testsubject\",\n" +
"\t\"masterRoll\": \"534\",\n" +
"\t\"firstName\": \"studentFirstName\",\n" +
"\t\"rollNumber\": \"23\"\n" +
"}";
Student studentDTO=new Gson().fromJson(json, Student.class);
System.out.println(studentDTO);
Student.java
#Data
public class Student {
#Delegate(types = Master.class)
private Master master=new Master();
private String firstName;
private String lastName;
private int rollNumber;
}
Master.java
#Data
public class Master {
private String masterName;
private String masterSubjectName;
private int masterRoll;
}
This gives Response:
Student(master=Master(masterName=null, masterSubjectName=null, masterRoll=0), firstName=studentFirstName, lastName=null, rollNumber=23)
When I parse the json string "json" to the Student class,
Why values not getting passed to "Master.java" inner dto?
I need something like Student(masterName=test1, masterSubjectName=testsubject, masterRoll=534, firstName=studentFirstName,rollNumber=23)
Your 'types' value in #Delegate should be Interface with getter methods for example getMasterName() , getMasterSubjectName... and so on
documentation:
https://projectlombok.org/features/experimental/Delegate

Serializing Enum to JSON in Java

I have a Java enum where I store different statuses:
public enum BusinessCustomersStatus {
A("active", "Active"),
O("onboarding", "Onboarding"),
NV("not_verified", "Not Verified"),
V("verified", "Verified"),
S("suspended", "Suspended"),
I("inactive", "Inactive");
#Getter
private String shortName;
#JsonValue
#Getter
private String fullName;
BusinessCustomersStatus(String shortName, String fullName) {
this.shortName = shortName;
this.fullName = fullName;
}
// Use the fromStatus method as #JsonCreator
#JsonCreator
public static BusinessCustomersStatus fromStatus(String statusText) {
for (BusinessCustomersStatus status : values()) {
if (status.getShortName().equalsIgnoreCase(statusText)) {
return status;
}
}
throw new UnsupportedOperationException(String.format("Unknown status: '%s'", statusText));
}
}
Full code: https://github.com/rcbandit111/Search_specification_POC/blob/main/src/main/java/org/merchant/database/service/businesscustomers/BusinessCustomersStatus.java
The code works well when I want to get the list of items into pages for the value fullName because I use #JsonValue annotation.
I have a case where I need to get the shortValue for this code:
return businessCustomersService.findById(id).map( businessCustomers -> businessCustomersMapper.toFullDTO(businessCustomers));
Source: https://github.com/rcbandit111/Search_specification_POC/blob/316c97aa5dc34488771ee11fb0dcf6dc1e4303da/src/main/java/org/merchant/service/businesscustomers/BusinessCustomersRestServiceImpl.java#L77
But I get fullValue. Do you know for a single row how I can map the shortValue?
I'd recommend serializing it as an object. This can be done via the #JsonFormat annotation at the class level:
#JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum BusinessCustomersStatus {
A("active", "Active"),
O("onboarding", "Onboarding"),
//...
#Getter
private String shortName;
#Getter
private String fullName;
//...
This will lead to the following result when serializing this enum for BusinessCustomersStatus.A:
{"shortName":"active","fullName":"Active"}
Alternatively, you could define status field as String:
public class BusinessCustomersFullDTO {
private long id;
private String name;
private String businessType;
private String status;
}
and map its value like this:
businessCustomersFullDTO.status(businessCustomers.getStatus().getShortName());

Field error in object 'titulo' on field 'status': rejected value [Pendente];

I am trying to learn Spring Framework on the go. During runtime I get following stacktrace:
Validation failed for object='title'. Error count: 1
org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'title' on field 'status': rejected value
[Received];
I noticed that the problem is in the status, which is formatted by enum, but I can't any error.
My class Controller:
#Controller
#RequestMapping("/titles")
public class registerTitleController {
#RequestMapping("/title")
public String new() {
return "RegisterTitle";
}
#Autowired
private Titles titles;
#RequestMapping(method=RequestMethod.POST)
public String saveIn(Title title) {
titles.save(title);
return "RegisterTitle";
}
}
My class entity
#Entity
public class Title {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cod;
private String description;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Temporal(TemporalType.DATE)
private Date dateV;
private BigDecimal val;
#Enumerated(value = EnumType.STRING)
private StatusTitle status;
//other accessor methods
My class enum
public enum StatusTitle {
PENDING("Pending"),
RECEIVED("Received");
private String description;
private StatusTitulo(String descricao){
this.description = description;
}
public String getDescription() {
return description;
}
}
My system work without the status of the attribute.
Can someone point out what is wrong? Your help will be much appreciated.
You probably are sending "Received", but you need to send "RECEIVED" string to properly convert to the ENUM by default.

Java object not populated from json request for inner class

Have searched in different sites but couldn't find correct answer, hence posting this request though it could possible duplicates.sorry for that.
I am sending the below json request to my back-end service and converting to java object for processing. I can see the request body passed to my service but when i convert from json to java object , values are not populating
{
"data":{
"username":"martin",
"customerId":1234567890,
"firstName":"john",
"lastName":"smith",
"password":"p#ssrr0rd##12",
"email":"john.smith#gmail.com",
"contactNumber":"0342323443",
"department":"sports",
"location":"texas",
"status":"unlocked",
"OrderConfigs":[
{
"vpnId":"N4234554R",
"serviceId":"connectNow",
"serviceType":"WRLIP",
"ipAddress":"10.101.10.3",
"fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
"timeout":1800,
"mapId":"test_map"
}
]
}
}
My Parser class have something like,
JSONObject requestJSON = new JSONObject(requestBody).getJSONObject("data");
ObjectMapper mapper = new ObjectMapper();
final String jsonData = requestJSON.toString();
OrderDTO mappedObject= mapper.readValue(jsonData , OrderDTO .class);
// I can see value coming from front-end but not populating in the mappedObject
My OrderDTO.java
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true,value = {"hibernateLazyInitializer", "handler", "created"})
public class OrderDTO {
private String username;
private long customerId;
private String source;
private String firstName;
private String lastName;
private String email;
private String contactNumber;
private String password;
private String department;
private String location;
private String status;
private List<OrderConfig> OrderConfigs;
#JsonInclude(value = Include.NON_NULL)
public class OrderConfig {
private String vpnId;
private String serviceId;
private String serviceType;
private String ipAddress;
private String mapId;
private String[] fRoutes;
private Map<String, Object> attributes;
private SubConfig subConfig;
private String routeFlag;
getter/setters
.....
}
all setter/getter
}
Not sure what I'm missing here. Is this right way to do?
If your are trying to use inner class, correct way to use is to declare it static for Jackson to work with inner classes.
For reference check this
code changes made are
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
static class OrderConfig {
Make sure that your json tag names match with variable names of java object
Ex : "fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
private String[] fRoutes;
OrderConfigs fields will not be initialized, just modify your bean as
#JsonProperty("OrderConfigs")
private List<OrderConfig> orderConfigs;
// setter and getter as setOrderConfigs / getOrderConfigs
See my answer here. (same issue)

DynamoDB Pojo to attribute value

I have a POJO defined for a dynamodb Table like this:
public class DynamoDBTablePojo {
#NonNull
private String requestId;
#NonNull
private String responseId;
private String responseBlob;
#DynamoDBHashKey(attributeName = "RequestId")
public String getRequestId(){return this.requestId;};
#DynamoDBAttribute(attributeName = "ResponseId")
public String getResponseId(){return this.responseId;};
#DynamoDBAttribute(attributeName = "ResponseBlob")
public String getResponseBlob() {return responseBlob;}
}
I want to write a function in java which will take attribute name and DynamoDBTablePojo object and returns the value of that attribute. e.g.,
String func(String attributeName, DynamoDBTablePojo dynamoDBTablePojoObj){
// returns value associated with this attribute.
}

Categories