How to post to a URL with hash + range key Spring Data DynamoDB - spring

As in spring-data-dynamoDB demo, I have created my application with hash and range keys, but am unable to post any data into my Table using POST because the following exception,
{cause: {cause: {cause: null,message: null}, message: "N/A (through reference chain: pkg.Test["id"])"}, message: "Could not read JSON: N/A (through reference chain: pkg.Test["id"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: N/A (through reference chain: pkg["id"])"
}
My Domain Class,
#DynamoDBTable(tableName = "test")
public class Test implements Serializable{
private static final long serialVersionUID = 1L;
#Id private TestId testId;
private String description;
private String testing;
#DynamoDBHashKey(attributeName="id")
public String getId() {
return testId != null ? testId.getId() : null;
}
public void setId(String id) {
if(testId == null){
testId = new TestId();
}
this.setId(id);
}
#DynamoDBRangeKey(attributeName="name")
public String getName() {
return testId != null ? testId.getName() : null;
}
public void setName(String name) {
if(testId == null){
testId = new TestId();
}
this.setName(name);
}
#DynamoDBAttribute(attributeName="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#DynamoDBAttribute(attributeName="testing")
public String getTesting() {
return testing;
}
public void setTesting(String testing) {
this.testing = testing;
}
public TestId getTestId() {
return testId;
}
public void setTestId(TestId testId) {
this.testId = testId;
}
}
and my TestId Class,
public class TestId implements Serializable{
private String id;
private String name;
#DynamoDBHashKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBRangeKey
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I think I have created Domain class correctly but What is the correct procedure to Post data into it. I have tried,
URL:
http://localhost:8080/tests
Request Body:
{"testId": {"id": "test", "name": "z"}, "description": "Awesome Guy", "testing": "x"}
and
{"id": "test", "name": "z", "description": "Awesome Guy", "testing": "x"}
But all shows the exception as I mentioned above but I have given id attribute in requestbody correctly.
What is the correct procedure to POST the data into my table? and Is there anything problem with spring-data-rest parsing? as mentioned here

The setId() method seems to be self-calling. You may want to call testId.setId() instead of this.setId().

Related

Graphql - Query returns null

I am using the graphql-java-annotations library for java to retrieve data from my spring backend.
<dependency>
<groupId>io.github.graphql-java</groupId>
<artifactId>graphql-java-annotations</artifactId>
<version>7.1</version>
</dependency>
When I call the query it always return null.
This is my Provider class:
GraphQLAnnotations graphqlAnnotations = new GraphQLAnnotations();
GraphQLSchema graphQLSchema = newSchema()
.query(graphqlAnnotations.object(QueryTest.class))
.build();
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
This is the query:
#GraphQLName("queryTest")
public class QueryTest {
#GraphQLField
public static Test byId(final DataFetchingEnvironment env, #GraphQLName("id") Long id) {
return new Test();
}
}
And finally the Test.class
#GraphQLName("Test")
public class Test {
private String id;
private String name;
public Test() {
this("0");
}
public Test(String id) {
this.setName("Name" + id);
this.setId(id);
}
#GraphQLField
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#GraphQLField
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
This is my call:
{
"query" : "query queryTest { byId(id: 2) { getId } }",
"operationName" : "queryTest"
}
And this is the result i get:
{
"data": {
"byId": null
}
}
I debugged into the graphql execution and found out that schema contains TestClass and Test. So type and query are known. With this configuration I don't have a fetcher or a resolver.
Found the solution:
I had to change my Provider class in order to create the schema correctly via the AnnotationsSchemaCreator Builder:
GraphQLSchema graphQLSchema = AnnotationsSchemaCreator.newAnnotationsSchema()
.query(QueryTest.class)
.typeFunction(new ZonedDateTimeFunction())
.build();
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();

how to convert integer to string using typeconverters in room android?

I am developing a chat app but I am getting the following error: Cannot find getter for the field.
that's why I want to convert Integer to String using type converters in Room but I did not find any sample below my User.java model class
#Entity public class User implements IChatUser {
#PrimaryKey(autoGenerate = true)
private Integer id;
#ColumnInfo(name = "name")
private String name;
#Ignore
Bitmap icon;
public User() {
}
#Ignore
public User(String name, Bitmap icon) {
this.name = name;
this.icon = icon;
}
#Override
public Integer getId() {
return this.id;
}
#Override
public String getName() {
return this.name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
#Override
public Bitmap getIcon() {
return this.icon;
}
#Override
public void setIcon(Bitmap icon) {
this.icon = icon;
} }
below IchatUser.kt
interface IChatUser {
fun getId(): String
fun getName(): String?
fun getIcon(): Bitmap?
fun setIcon(bmp: Bitmap)
}
To create a #TypeConverter create a java class and call it IntConverter
public class IntConverter {
#TypeConverter
public static String toString(int number) {
return number == null ? null : Integer.toString(number);
}
#TypeConverter
public static int toInt(String str) {
return str == null ? null : Integer.parseInt(str);
}
}
Now you need the database to know about this TypeConverter so declare this:
#TypeConverters(IntConverter.class)
Just below the #Database annotation in the Database class

How to create a custom json object to columns value returned from my custom #Query

I have a query to My SQL database and I use Spring Boot to return it to Json format.
My problem is it only return value without key like:
[
[
"kermit",
6
]
]
I want it return like:
[
[
"name":"kermit",
"count" :6
]
]
I tried add Jackson Annotation jar file to project and use #JsonProperty in my entity model class:
#Entity
#Table(name = "act_id_membership", schema = "activiti", catalog = "")
#IdClass(ActIdMembershipEntityPK.class)
public class ActIdMembershipEntity {
#JsonProperty("name")
private String userId;
#JsonProperty("group")
private String groupId;
#Id
#Column(name = "USER_ID_")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Id
#Column(name = "GROUP_ID_")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActIdMembershipEntity that = (ActIdMembershipEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
But it still return without key. What I should do now? Please help me!
Thank you very much!
First, I'm agree with guy who commented that is not valid JSON format. You can see examples here https://json.org/example.html
Second, You need to create an object JSON which has fields needed for example:
public class UserStat es implements Serializable {
private String name;
private long count;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
And in your custom query. Based your return looks like on this way:
#Query("SELECT u.name, count(u) FROM User u")
public List<UserStat> findUserStat() ;

Error Spring React REST Controller Using Custom Class Response (WebFlux)

I'm trying to build a Spring WebFlux project and realize the follow business logic:
1 - Call an external REST Api using WebClient and parse the Json results using the Models below. It is working OK
2 - To show the Mono results Mono<DeviceList> devices, I'm using the ResponseApi class and returning it, but it is NOT working
I'm getting the follow error:
Response status 406 with reason "Could not find acceptable representation"
Thanks
# Json Result
{
"data": [
{
"id": "5bc3c0efe833d93f401bafa8",
"name": "XXXXX",
"group": "5b8fd1fa0499f54cfa7febb8",
"description": "Geolocalizacao gps",
"payloadType": "None",
"contract": "5bc08be5e833d93f40e1f936",
"keepAlive": 0
}
]
}
# Controller
public class DeviceController{
...
...
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
Mono<DeviceList> devices = deviceService.findDeviceTypes();
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
}
}
# Repository
public Mono<DeviceList> findDeviceTypes() {
return webClient.get()
.uri(DEVICE_TYPES_URL)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(DeviceList.class);
}
# Model
public class DeviceList{
#JsonProperty("data")
private List<Device> data;
public List<Device> getData() {
return data;
}
public void setData(List<Device> data) {
this.data = data;
}
}
public class Device{
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("group")
private String group;
#JsonProperty("description")
private String description;
#JsonProperty("keepAlive")
private Integer keepAlive;
#JsonProperty("payloadType")
private String payloadType;
#JsonProperty("contract")
private String contract;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Integer keepAlive) {
this.keepAlive = keepAlive;
}
public String getPayloadType() {
return payloadType;
}
public void setPayloadType(String payloadType) {
this.payloadType = payloadType;
}
public String getContract() {
return contract;
}
public void setContract(String contract) {
this.contract = contract;
}
}
#JsonRootName("data")
public class ResponseApi{
#JsonProperty("status")
private Integer status;
#JsonProperty("code")
private String code;
#JsonProperty("message")
private String message;
#JsonProperty("data")
private Object data;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
You can get devices, then in non blocking way, map them to the ResponseApi like that:
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
return deviceService.findDeviceTypes()
.flatMap(devices -> {
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
});
}

springboot - Json object return invalid

Currently, I am using rest template to get data from external api in getter method. While printing in console log, valid json format is coming. But, through postman output, invalid json output is coming (with \"). Pls suggest.
public class Product {
#Id
public Integer id;
private String name;
public Product() {
}
public Product(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
final String uri = "http://example.com/";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri + this.getId(), String.class);
System.out.println(result);
return result;
}
public void setName(String name) {
this.name = name;
}
}
//console.log (example)
{"product":{"rating_and_review_reviews":{"hasErrors":false,"offset":0,
"totalResults":0,"locale":"en_US","limit":10,"duration":1,"result":
[]},"question_answer_statistics"
// POSTMAN - HTTP GET (coming with \)
{
"id": 1,
"name": "{\"product\":{\"rating\":{\"hasErrors\":false,\"offset\":0,
\"totalResults\":0,\"locale\":\"en_US\",\"limit\":10,
\"duration\":1,\"result\":[]}

Resources