How can I read data and put into model in java? - java

I need to get some specific data from rest to my model.
Data I get from rest :
[{"id":595,"name":"TransXChange20210805113332","prosystem_file_id":null,"dataset":16,"creator":113,"editor":113,"created":"2021-08-05T09:45:21.444949Z","edited":"2021-08-05T09:45:27.542152Z","update_from_url":false,"description":"Rozkłady jazdy komunikacji miejskiej ważne od 08.08.2021","file":"https://otwartedane.erzeszow.pl/media/resources/transxchange20210805113332.xml","link":null,"extension":"XML","data_type":"[]","file_name":"transxchange20210805113332.xml","chart_info":null,"map_info":null,"score":4,"public":true,"licence":"other-open","connection_dict":null,"selection_string":null,"db_type":"POSTGRESQL","type":"file","dbview_cache_minutes":1,"preview_base64":null,"gpkg_display_info":null,"archive_to_csv":false},{"id":538,"name":"TransXChange20210513082611","prosystem_file_id":null,"dataset":16,"creator":113,"editor":113,"created":"2021-05-13T06:28:50.233464Z","edited":"2021-07-28T08:52:06.695966Z","update_from_url":false,"description":"Rozkłady jazdy komunikacji miejskiej ważne od 15.05.2021","file":"https://otwartedane.erzeszow.pl/media/resources/transxchange20210513082611.xml","link":null,"extension":"XML","data_type":"[]","file_name":"transxchange20210513082611.xml","chart_info":null,"map_info":null,"score":4,"public":true,"licence":"other-open","connection_dict":null,"selection_string":null,"db_type":"POSTGRESQL","type":"file","dbview_cache_minutes":1,"preview_base64":null,"gpkg_display_info":null,"archive_to_csv":false},{"id":544,"name":"TransXChange20210526143716","prosystem_file_id":null,"dataset":16,"creator":113,"editor":113,"created":"2021-05-26T12:40:42.587492Z","edited":"2021-07-28T08:52:04.417450Z","update_from_url":false,"description":"Rozkłady jazdy komunikacji miejskiej ważne od 01.06.2021","file":"https://otwartedane.erzeszow.pl/media/resources/transxchange20210526143716.xml","link":null,"extension":"XML","data_type":"[]","file_name":"transxchange20210526143716.xml","chart_info":null,"map_info":null,"score":4,"public":true,"licence":"other-open","connection_dict":null,"selection_string":null,"db_type":"POSTGRESQL","type":"file","dbview_cache_minutes":1,"preview_base64":null,"gpkg_display_info":null,"archive_to_csv":false}]
i got it in single line
my code in java :
RestTemplateBuilder builder = new RestTemplateBuilder();
String soc = builder.build().getForObject("https://otwartedane.erzeszow.pl/v1/datasets/16/resources/", String.class);
assert soc != null;
System.out.println(soc);
And the problem is I need to put them into model
My model:
public class Resource {
private long id;
private String name;
private long prosystem_file_id;
private int dataset;
private int creator;
private int editor;
private LocalDateTime created;
private LocalDateTime edited;
private boolean update_from_url;
private String description;
private String file;
private String link;
private String extension;
private String data_type;
private String file_name;
private String chart_info;
private String map_info;
private int score;
private boolean isPublic;
private String licence;
private String connection_dict;
private String selection_string;
private String db_type;
private String type;
private int dbview_cache_minutes;
private String preview_base64;
private String gpkg_display_info;
private boolean archive_to_csv;
All getters and setters are generated.
How can I put them into model for example List?
The problem is I get data like [{resource},{resource},{resource}].

As it states from the RestTemplate documentation
you can call to the getForObject method passing as an argument the desired deserialization class.
Something like:
RestTemplateBuilder builder = new RestTemplateBuilder();
Resource soc = builder.build().getForObject("https://otwartedane.erzeszow.pl/v1/datasets/16/resources/", Resource.class);
assert soc != null;
System.out.println(soc);

I have found answer to my question.
I need to assign my call to array of model.
Resource[] soc =builder.build().getForObject( URL , Resource[].class );

Related

How to Convert MongoDB Query to Spring Data Query

I'm trying to convert the following Mongo query for use with Spring data.
db.product.aggregate([
{$unwind: '$barcodes'},
{$project: {
_id: 0,
productId: '$_id',
productTitle: '$title',
productVariation: '$variation',
barcode: '$barcodes'
}}])
This is what I've been trying so far. It returns the aggregation, but with null values:
UnwindOperation unwindOperation = Aggregation.unwind("barcodes");
ProjectionOperation projectStage = Aggregation.project().and("productId").as("_id").and("productTitle")
.as("title")
.and("productVariation").as("variation")
.and("barcodeTitle").as("barcodes.title")
.and("barcodeValue").as("barcodes.value")
.and("barcodeType").as("barcodes.type")
.and("codeStandard").as("barcodes.codeStandard")
.and("quantity").as("barcodes.quantity")
.and("status").as("barcodes.status");
SortOperation sortOperation = Aggregation.sort(Sort.by(Sort.Direction.DESC, "title"));
Aggregation agg = Aggregation.newAggregation(unwindOperation, projectStage, sortOperation);
AggregationResults<BarcodeAggregateList> results = mongoTemplate.aggregate(agg, "product", BarcodeAggregateList.class);
What it is returning:
The class I am mapping to (has getters/setters):
public class BarcodeAggregateList {
private String productId;
private String productTitle;
private String productVariation;
private String barcodeTitle;
private String barcodeValue;
private String barcodeType;
private String codeStandard;
private int quantity;
private String status;
}
Product class that the data is coming from:
public class Product implements Serializable {
private static final long serialVersionUID = -998149317494604215L;
private String id;
private String title;
private String description;
private String SKU;
private double cost;
private double retailPrice;
private String status;
private LocalDate launchDate;
private LocalDate discontinueDate;
private String discontinueReason;
private String salesChannel;
private List<Barcode> barcodes;
private ProductVariation variation;
private List<Supplier> supplier;
private Product parentProduct;
private boolean updateChildren;
private Label label;
private int secondaryStockLevel;
private int primaryStockLevel;
private Date createdDate;
private Date modifiedDate;
private List<Dimension> dimensions;
private boolean isDeleted = false;
}
Barcode class
public class Barcode {
private String type;
private String title;
private String value;
private String status;
private String codeStandard;
private int quantity;
}
I appreciate any help with this or resources to help me better understand how to perform these types of conversions.
For anyone trying to solve similar issues, I've found the following resources somewhat helpful:
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.query
https://xpadro.com/2016/04/data-aggregation-with-spring-data-mongodb-and-spring-boot.html
https://www.tutorialspoint.com/get-fields-from-multiple-sub-documents-that-match-a-condition-in-mongodb
BarcodeAggregateList class fields are null because there is a minor issue in ProjectionOperation's and() and as() methods. The correct syntax is
Aggregation.project().and(SOURCE_FIELD).as(TARGET_FIELD)
You have written and("productId").as("_id") , which is wrong
You need to write this as and("_id").as("productId") , because source field is _id
complete code:
UnwindOperation unwindOperation = Aggregation.unwind("barcodes");
ProjectionOperation projectStage = Aggregation.project()
.and("_id").as("productId")
.and("title").as("productTitle")
.and("variation").as("productVariation")
.and("barcodes.title").as("barcodeTitle")
.and("barcodes.value").as("barcodeValue")
.and("barcodes.type").as("barcodeType")
.and("barcodes.codeStandard").as("codeStandard")
.and("barcodes.quantity").as("quantity")
.and("barcodes.status").as("status");
SortOperation sortOperation = Aggregation.sort(Sort.by(Sort.Direction.DESC, "productTitle"));
Aggregation agg = Aggregation.newAggregation(unwindOperation, projectStage, sortOperation);
AggregationResults<BarcodeAggregateList> results = mongoTemplate.aggregate(agg, "product", BarcodeAggregateList.class);

Unmarshal JSON-Array to object while ignoring null values

I get a JSON-Object as an array form an external source which looks like this:
[13823108,"Text1","Text2",null,null,1585730520000,1585753742000,null,null,"COMPLETED",null]
The array will always have null values at those positions, which is why I would like to ignore those.
My Java object is suppose to look like this:
#JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class MyJsonObject {
private final String id;
private final String textField1;
private final String textField2;
private final Date started;
private final Date updated;
private final String status;
#JsonCreator
public MyJsonObject(
#JsonProperty("id") final String id,
#JsonProperty("textField1") final String textField1,
#JsonProperty("textField2") final String textField2,
#JsonProperty("started") final Date started,
#JsonProperty("updated") final Date updated,
#JsonProperty("status") final String status) {
this.id = id;
this.textField1 = textField1;
this.textField2 = textField2;
this.started = started;
this.updated = updated;
this.status = status;
}
[...]
}
When I try to unmarshal the Json the null values are used, which courses the additional values to be ignored:
MyJsonObject{id='13105603', textField1='Text1', textField2='Text2', started=null, updated=null, status='1569348774000'}
Is there a way to tell the ObjectMapper to ignore null values of the array? Can I achieve this without writing a specific Deserializer?
I already tried #JsonInclude(JsonInclude.Include.NON_NULL) with no effect.

How to combine data from two reactive streams in project reactor?

I started using Project Reactor recently and I can't work out how to work with nested streams. I want to update data of outer Mono with some data of inner Mono.
#GetMapping("/search")
public Mono<Github> combineGithubData() {
WebClient client = WebClient.create("https://api.github.com");
Mono<Github> data = client.get().uri(URI.create("https://api.github.com/users/autocorrectoff")).retrieve().bodyToMono(Github.class);
data = data.map(s -> {
client.get().uri(URI.create("https://api.github.com/users/Kukilej")).retrieve().bodyToMono(Github.class).map(m -> {
s.setXXX(m.getName());
return m;
});
return s;
});
return data;
}
The field XXX is always returned as null, although I have set it to a value from inner Mono. I'm pretty sure this would work in RxJs. How do I make this work with Project Reactor?
edit:
the code of the Github class
import lombok.*;
#Getter #Setter
#Builder
#ToString
#NoArgsConstructor
#AllArgsConstructor
public class Github {
private String login;
private int id;
private String node_id;
private String avatar_url;
private String gravatar_id;
private String url;
private String html_url;
private String followers_url;
private String following_url;
private String gists_url;
private String starred_url;
private String subscriptions_url;
private String organizations_url;
private String repos_url;
private String events_url;
private String received_events_url;
private String type;
private boolean site_admin;
private String name;
private String company;
private String blog;
private String location;
private String email;
private String hireable;
private String bio;
private int public_repos;
private int public_gists;
private int followers;
private int following;
private String created_at;
private String updated_at;
private String XXX;
}
Your inner stream is not getting subscribed to. Either us flatMap, or better yet, use zip:
data
.zipWith(client.get().uri(...).retrieve().bodyToMono(Github.class))
.map(tuple2 -> {
//update tuple2.getT1() with m.getName() and return the updated tuple
return tuple2.mapT1(tuple2.getT1().setXXX(tuple2.getT2().getName()));
})
.map(tuple2 -> tuple2.getT1() //updated s);
zipWith() subscribes to the inner stream.

how can i combine 3 List of different object into one new object with Java 8

I have 3 objects List and i would like to combine it base on they unique key into one object List.
Since Loan depend on Account and Account depend on Bank
is there simple way without multiple looping for each object in java 8?
I know its better to do it in single query but wonder if there is something existing with Java 8 using List and combine it into one list.
public class Bank {
private String institution; //pk
private String transit; //pk
private String bankName;
}
public class Account {
private String institution; //pk
private String transit; //pk
private String accountNo; //pk
private String nameAccount;
}
public class Loan {
private String institution;//pk
private String transit;//pk
private String accountNo;//pk
private String serviceNo;//pk
}
// fusion object
public class CombineObject {
private String institution;
private String transit;
private String accountNo;
private String serviceNo;
private String nameAccount;
private String bankName;
}
List<Bank> lstBank = myListBank();
List<Account> lstAccount = myListAccount();
List<Loan> lstLoan = myListLoan();

How can I make this Serializable?

I'm very sorry for i explained like fool...
I mean I can't compile because of error.
public class PictureBean implements Serializable
{
public enum CCLtype implements Serializable
{
BY, ND, CO, NN, SA
}
private String picture_rm;
private String picture_url;
private String picture_16_9_url;
private String author;
private String title;
private String description;
private String p_memo;
private String p_original_rate;
private String move_url;
private int like_count;
private int picture_exp_count;
private List<JsonObject> tagList;
private List<JsonObject> categoryList;
private CCLtype ccl;
private String picture_source;
private boolean isUserLiked;
private boolean isUserAdded;
I use this PictureBean.class for contain image datas in my server.
but when I send list of PictureBean data to activity from activity, like below, Eclipse occurred error line.
How could I send list of PictureBean to activity from activity?
'mItems''s dataType is List of PictureBean.
intent.putExtra(CategoryDetailPagerActivity.EXTRA_DATA_CATEGORY_DETAIL_LIST, mItems);
Update:
Don't put the list it self as an extra. send a class object that contain the list as the only member as follow:
public class SerialObject implements Serializable
{
private static final long serialVersionUID = -3975620301776205681L;
public List<PictureBean> myItems;
}
SerialObject sb = new SerialObject();
sb.myItems = mItems;
intent.putExtra(CategoryDetailPagerActivity.EXTRA_DATA_CATEGORY_DETAIL_LIST, sb);
Original Answer:
This is how your class should be:
public class PictureBean implements Serializable
{
private static final long serialVersionUID = 6969933524911660214L;
public enum CCLtype
{
BY, ND, CO, NN, SA
}
private String picture_rm;
private String picture_url;
private String picture_16_9_url;
private String author;
private String title;
private String description;
private String p_memo;
private String p_original_rate;
private String move_url;
private int like_count;
private int picture_exp_count;
private List<JsonObject> tagList;
private List<JsonObject> categoryList;
private CCLtype ccl;
private String picture_source;
private boolean isUserLiked;
private boolean isUserAdded;
}
Same thing for the JsonObject class.
I believe that you don't have to serialise CCLtype
Can you share the error with us? That would be most helpful. Without that information it'd be hard to tell, but my guess is maybe that some of the class types you are trying to make serializable are not types that you can serialize in Android (at least not using the pre-made "Serializable" implementation.
Try commenting out all the types and one at a time uncommenting to find out which type is breaking your serialization. You might be able to write a special serialization method for those types (or switch it to a different type).
Just a guess because you've not yet posted the error, but as the Android docs say "if the local serialVersionUID differs from the serialVersionUID in the serialized data, deserialization will fail with an InvalidClassException." You can work around this, as I had to in my app, by declaring an explicit ID. Put this in your class, to do so, with any Long value you like:
private static final long serialVersionUID = 0L;

Categories

Resources