I have two Pojo classes, one for hibernate mapping and one for jaxb.
So I get a List<CarA> using Criteria.list() and I would like to transform it into a List<CarB> in order to send it back to my client as a SOAP message.
Would you have any idea how to do the conversion from CarA to CarB?
My list contains more than 100 elements and the construction gets expensive very fast.
I wish I didn't have to build a list from A to Z.
Thanks for your help
You can use model mapper library : https://www.baeldung.com/java-modelmapper
Example of what you can do:
List<Carb> lb = new ArrayList();
for (Cara a : la )
lb.add(mapper.map(a, Carb.class))
Related
I am calling a service that returns data from a DB in the form of a LinkedList. I need to update the LinkedList with a new field called "status" which is determined off of endDate.
endDate > current date => status=deactivated
endDate <= current date => status=active
Mule Payload Class: java.util.LinkedList
Mule Payload: [{serialNumber=, maintenanceId=12345, customerID=09890, startDate=2017-10-10 23:34:17, endDate=2018-10-10 23:34:17},{serialNumber=, maintenanceId=09091, customerID=74743, startDate=2014-8-16 23:34:17, endDate=2019-8-16 23:34:17}]
The issue I am having in mule is that I am unable to navigate into the linked list to retrieve the value as well as add a new value to the list. Hoping someone could give me some advice on the best way to move forward. I am trying to use a groovy transformer to update the payload, but it's not going so well, so I don't have any code to show.
Thanks taking the time!
I had a similar requirement (the payload was a JSON but it should work as well) and this is what I did using Dataweave (I added your data so it can be easier to understand).
%dw 1.0
%output application/java
---
flowVars.input2 map {
serialNumber : $.serialNumber,
maintenanceId: $.maintenanceId,
customerID: $.customerID,
startDate: $.startDate,
endDate: $.endDate,
status: "deactivated" when $.endDate as :date {format:"yyyy-M-dd HH:mm:ss"} > (now as :date {format:"yyyy-M-dd HH:mm:ss"}) otherwise "activated"
}
With this transformation you iterate the list and add the status value based on your requirement.
Input example:
[{"serialNumber":"test1", "maintenanceId":"12345", "customerID":"09890", "startDate":"2017-10-10 23:34:17", "endDate":"2018-10-10 23:34:17"},{"serialNumber":"test2", "maintenanceId":"09091", "customerID":"74743", "startDate":"2014-8-15 23:34:17", "endDate":"2018-8-15 23:34:17"}]
Output example
[{"serialNumber":"test1","maintenanceId":"12345","customerID":"09890","startDate":"2017-10-10 23:34:17","endDate":"2018-10-10 23:34:17","status":"deactivated"},{"serialNumber":"test2","maintenanceId":"09091","customerID":"74743","startDate":"2014-8-15 23:34:17","endDate":"2018-8-15 23:34:17","status":"activated"}]
Hope this helps you
I'm trying to convert a large Map> to some JavaBean. The key of map corresponds to some property of JavaBean, and the value somehow is decoded to property value. So I decided to use some util for that, but don't know what will work. There are some requirements I have to this util (or framework):
all configuration must be in separate files
should be a possibility to map dynamic quantity of keys:
there is a map:
key | value
quan | n
key_1| value_1
key_2| value_2
........ | .............
key_n| value_n
where n - is any number
and the JavaBean has a List of some beans. They have a property. value_1, value_2, ... must be mapped in this property, and in the end there must be so much beans in list, as these keys and values in map.
3.. should be a possibility to set up custom decoder for property mapping, because in most cases the value in map is a List with 1 value, so I need to get the first item of list (if it's not empty).
4.. should be a possibility run some script to execute extraordinary mappings, for example:
there is a map, that is described in 2d point.
and the JavaBean has a property of type HashMap, where value_1 is mapped to Bean1 and some analogous value from input map is mapped to Bean2.
I've tried to use smooks, but when I've started, all these requirements were not clear yet and the smooks was something new, I haven't worked with it until now. So the smooks config doesn't contain the whole business-logic (because of second req.) and looks ugly, I don't like that. I can show the most ugliest fragment for 2d point:
<jb:bean beanId="javaBean" class="com.example.JavaBean" createOnElement="map">
<jb:wiring property="someBeans" beanIdRef="someBeanItems"/>
</jb:bean>
<jb:bean beanId="someBeanItems" class="java.util.ArrayList" createOnElement="map/entry">
<jb:wiring beanIdRef="someBeanItem"/>
</jb:bean>
<jb:bean beanId="someBeanItem" class="com.example.someBeanItem" createOnElement="map/entry">
<condition>map.quan[0]>0</condition>
<jb:expression property="property1">
index = map.quan[0]-1;
value = additionalProperties.property1_List[index];
map.quan[0] = map.quan[0] - 1;
return value;
</jb:expression>
</jb:bean>
Here "property1_List" is builded before executing smooks.
Now I look for something more nice and need your help: maybe you know how to make that better using smooks? Or what another frameworks for mapping can you recommend for my issue?
Update: I should have mentioned this right off the bat: I first considered a Java/JSON mapping framework, but my manager does not want me adding any more dependencies to the project, so that is out as an option. The JSON-Java jar is already on our classpath, so I could use that, but still not seeing the forest through the trees on how it could be used.
My Java program is being handed JSON of the following form (althought the values will change all the time):
{"order":{"booze":"1","handled":"0","credits":"0.6",
"execute":0,"available":["299258"],"approved":[],
"blizzard":"143030","reviewable":["930932","283982","782821"],
"units":"6","pending":["298233","329449"],"hobbit":"blasphemy"}}
I'm looking for the easiest, efficient, surefire way of cherry-picking specific values out of this JSON string and aggregating them into a List<Long>.
Specifically, I'm looking to extract-and-aggregate all of the "ids", that is, all the numeric values that you see for the available, approved, reviewable and pending fields. Each of these fields is an array of 0+ "ids". So, in the example above, we see the following breakdown of ids:
available: has 1 id (299258)
approved: has 0 ids
reviewable: has 3 ids (930932, 283982, 782821)
pending: has 2 ids (298233, 329449)
I need some Java code to run and produce a List<Long> with all 6 of these extracted ids, in no particular order. The ids just need to make it into the list.
This feels like an incredibly complex, convoluded regex, and I'm not even sure where too begin. Any help at all is enormously appreciated. Thanks in advance.
The easiest way IMO is use a json library such as gson, jackson, json.org, etc, parse de JSON into an object and create a new List<Long> with the values of the properties you need.
Pseudocode with gson:
class Order {
long[] available;
long[] approved;
...
}
Order order = gson.fromJson("{ your json goes here }", Order.class);
List<Long> result = new ArrayList<Long>();
result.add(order.getAvailable());
result.add(order.getApproved());
...
Pseudocode with json.org/java:
JSONObject myobject = new JSONObject("{ your json goes here"});
JSONObject order = myobject.getJSONObject("order");
List<Long> result = new ArrayList<Long>();
for (int i=0; i<order.getJSONArray("approved").length(); i++) {
Long value = order.getJSONArray("approved").getLong(i);
result.add(value);
}
...
I'm trying to hit a REST end-point that returns a multi-line, multi-column response, such as:
A1 B1 C1
A2 B2 C2
A3 B3 C3
...
...
I'm currently using jersey-client to hit this endpoint and trying to look for the neatest way to parse this response. Here, each line would represent a bean, say MyBean and each column on that would represent a property in that bean. The order of values in the response is always fixed.
I can get the response back as a long String, split it at line-feeds and tabs to get individual values.
However, I would like to know if there is a way where I can get the results as a List<String>, where each element in the List would represent a line of the response. I can then split it on \t to get individual values.
Here's what I've tried:
WebResource resource = client.resource(NETSPEAK_URL)
.type(MediaType.TEXT_PLAIN)
.get(new GenericType<List<String>>(){});
But this leads to the following exception:
A message body reader for Java class java.util.List,
and Java type java.util.List<java.lang.String>,
and MIME media type text/plain; charset=UTF-8 was not found
If I be even greedier, I would like to know if I can get the individual column values mapped to the properties of my bean, MyBean. I've considered creating a wrapper around MyBean, to have a list of MyBeans, but then how would I annotate it to assist parsing? That would have made sense for an xml/json response. But this is plain text.
Is it possible to somehow tell jersey-client about the parsing of this text/plain response? If this is achievable through Apache HTTP client, I'm ready to move.
Thanks
You may want to implement a class representing your list of beans, say class BeanList extends List<Bean>, and implement a MessageBodyReader<BeanList> (see http://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/ext/MessageBodyReader.html) to teach jersey how to read a string as a BeanList.
Then you can use BeanList.class instead of List<String> as argument to the get call.
I have a XML file with many copies of table node structure as below:
<databasetable TblID=”123” TblName=”Department1_mailbox”>
<SelectColumns>
<Slno>dept1_slno</Slno>
<To>dept1_to</To>
<From>dept1_from</From>
<Subject>dept1_sub</Subject>
<Body>dept1_body</Body>
<BCC>dept1_BCC</BCC>
<CC>dept1_CC</CC>
</SelectColumns>
<WhereCondition>MailSentStatus=’New’</WhereCondition>
<UpdateSuccess>
<MailSentStatus>’Yes’</MailSentStatus>
<MailSentFailedReason>’Mail Sent Successfully’</MailSentFailedReason>
</UpdateSuccess>
<UpdateFailure>
<MailSentStatus>’No’</MailSentStatus>
<MailSentFailedReason>’Mail Sending Failed ’</MailSentFailedReason>
</ UpdateFailure>
</databasetable>
As it is not an efficient manner to traverse the file for each time to fetch the details of each node for the queries in the program, I used the nested hashmap concept to store the details while traversing the XML file for the first time. The structure I used is as below:
MapMaster
Key Value
123 MapDetails
Key Value
TblName Department1_mailbox
SelectColumns mapSelect
Key Value
Slno dept1_slno
To dept1_to
From dept1_from
Subject dept1_sub
Body dept1_body
BCC dept1_BCC
CC dept1_CC
WhereCondition MailSentStatus=’New’
UpdateSuccess mapUS
MailSentStatus ’Yes’
MailSentFailedReason ’Mail Sent Successfully’
UpdateFailure mapUF
MailSentStatus ’No’
MailSentFailedReason ’Mail Sending Failed’
But the problem I’m facing now is regarding retrieving the Value part using the nested Keys. For example,
If I need the value of Slno Key, I have to specify TblID, SelectColumns, Slno in nested form like:
Stirng Slno = ((HashMap)((HashMap)mapMaster.get(“123”))mapDetails.get(“SelectColumns”))mapSelect.get(“Slno”);
This is unconvinent to use in a program. Please suggest a solution but don’t tell that iterators are available. As I’ve to fetch the individual value from the map according to the need of my program.
EDIT:my program has to fetch the IDs of the department for which there is privilege to send mails and then these IDs are compared with the IDs in XML file. Only information of those IDs are fetched from XML which returned true in comparison. This is all my program. Please help.
Thanks in advance,
Vishu
Never cast to specific Map implementation. Better use casting to Map interface, i.e.
((Map)one.get("foo")).get("bar")
Do not use casting in your case. You can define collection using generics, so compiler will do work for you:
Map<String, Map> one = new HashMap<String, Map>();
Map<String, Integer> two = new HashMap<String, Integer>();
Now your can say:
int n = one.get("foo").get("bar");
No casting, no problems.
But the better solution is not to use nested tables at all. Create your custom classes like SelectColumns, WhereCondition etc. Each class should have appropriate private fields, getters and setters. Now parse your XML creating instance of these classes. And then use getters to traverse the data structure.
BTW if you wish to use JAXB you do not have to do almost anything! Something like the following:
Unmarshaller u = JAXBContext.newInstance(SelectColumns.class, WhereCondition.class).createUnmarshaller();
SelectColumns[] columns = (SelectColumns[])u.unmarshal(in);
One approach to take would be to generate fully qualified keys that contain the XML path to the element or attribute. These keys would be unique, stored in a single hashmap and get you to the element quickly.
Your code would simply have to generate a unique textual representation of the path and store and retrieve the xml element based on the key.