How to convert List<Entity> to a string? - java

Here is the code :
I have a entity named ClassA which consists of following attribute
#JsonProperty("rowDeleted")
private Boolean rowDeleted;
#JsonProperty("start")
private List<Start> start = null;
#JsonProperty("end")
private List<End> end = null;
#JsonProperty("rows")
private List<Row> rows = null;
And Row is another entity which consists of attributes:
#JsonProperty("cells")
private List<Cell> cells = null;
#JsonProperty("clusteringKey")
private String clusteringKey;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
And Cell is another entity:
#JsonProperty("deleted")
private Boolean deleted;
#JsonProperty("name")
private String name;
#JsonProperty("value")
private String value;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
I am getting an object of ClassA and want to convert it into another entity which is ClassB contains fields:
private String end;
private String key;
private String keyspacename;
private String partitiondeleted;
private String rowdeleted;
private String rows;
private String start;
private String tablename;
private String triggerdate;
private String triggertime;
So basically i want to convert List rows of ClassA to String rows of ClassB.
Can anyone please suggest a way to do this.
Thanks in advance

suppose you have a list of class A.
List<A> list= . . . ;
List<B> newList=list
.stream()
.map(obj-> new B()
.setKey(obj.getKey())
.setKeyspacename(//set which field of class A will be saved)
.setPartitiondeleted()
// set more fields
)
.collect(Collecters.toList());
and then serialize this newlist into String by using jakson.

I wanted a string which could represent json format so modified my toString() as per my requirement and it solved my purpose.

Related

spring Boot MongoDB Query

I have the following scenario:-
Use Device_Type telemetry for searching.
Should pull any Device that has a telemetry key that start with "processor".
Database used : Mongo DB
Device_Type.Class (Field of Device_Type collection)
#NotBlank
private String applicationId;
private AcnDeviceCategory deviceCategory;
private boolean editable = CoreConstant.DEFAULT_EDITABLE;
private List<DeviceTelemetry> telemetries = new ArrayList<>();
private Map<String, DeviceStateValueMetadata> stateMetadata = new HashMap<>();
private List<DeviceAction> actions = new ArrayList<>();
DeviceTelemetry.Class
private String name;
private String description;
#NotNull
private TelemetryItemType type;
private String telemetryUnitId;
private Map<String, String> variables = new HashMap<>();
Device.class
#NotBlank
private String uid;
#NotBlank
private String name;
enter code here
My code query is something like this
public static List<Device> getFilteredTelemetries(DeviceType deviceType) {
List<DeviceTelemetry> telemetriesToAdd = new ArrayList<>();
deviceType.getTelemetries().stream()
.filter(f -> f.getName().startsWith("System_Processor"))
.forEach(f -> {
telemetriesToAdd.add(f);
});
deviceType.getTelemetries().addAll(telemetriesToAdd);
return null;
}
can anyone please help me, how I return the device list here? Thank you for your help.
You can remove if !f.getName().startsWith("System_Processor") from the list
deviceType.getTelemetries().stream()
.removeIf(f -> !f.getName().startsWith("System_Processor"))

Convert Complex Entity to DTO With ModelMapper

i'm working in a rest API using Spring boot.
when i wanted to return my entity from an End Point i realized that the Properties are different from what i need on my response so i tried to use Model Mapper to return a DTO.
My entity is like this:
public class RuleEntity {
private String ruleId;
private String bankDecision;
private String aggregatorFunctionType;
private String limitOperatorType;
private double limitRule;
private Integer windowMinutes;
private Integer layer;
private String expressionRule;
private String status;
private List<GroupingKeyName> groupingKeyNames;
private List<RuleFilter> ruleFilters;
}
And the DTO that i need Must Be Like this:
public class RuleDTO {
private String ruleId;
private String bankDecision;
private String aggregatorFunctionType;
private String limitOperatorType;
private double limitRule;
private Integer windowMinutes;
private Integer layer;
private String expressionRule;
private String status;
private List<String> groupingKeyNames;
private List<String> ruleFilters;
}
The only change is that the last two lists are of String instead of The Object
The Objects groupingKeyNames and ruleFilters have a Name and an ID, and i only need the name on the list of DTO so it is a List of Strings
I tried using Model Mapper like this:
ModelMapper modelMapper = new ModelMapper();
RuleSetModel ruleSetModel = modelMapper.map(ruleSetEntity, RuleSetModel.class);
it works, with all the properties but in the Lists it is returning something like:
groupingKeyNames=[GroupingKeyName(groupingKeyId=1, name=cardHash)], ruleFilters=[RuleFilter(ruleFilterId=1, name=status)]
What could i do so i get a result like this:
groupingKeyNames=[cardHash], ruleFilters=[status]
Thanks in advance!
Create a method into your RuleEntity to do it
public RuleDTO dto() {
// config to skip
PropertyMap<RuleEntity, RuleDTO> propertyMap = new PropertyMap<RuleEntity, RuleDTO>() {
#Override
protected void configure() {
skip(destination.getGroupingKeyNames());
skip(destination.getRuleFilters());
}
};
RuleDTO ruleDTO = new RuleDTO();
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.addMappings(propertyMap);
modelMapper.map(this,ruleDTO);
if (!this.groupingKeyNames.isEmpty()) {
ruleDTO.getGroupingKeyNames().clear();
List<String> tmpGroupingKeyNames = new ArrayList<>();
this.getGroupingKeyNames().forEach(itemDTO -> {
tmpGroupingKeyNames.add(itemDTO.name);
});
ruleDTO.getGroupingKeyNames().addAll(tmpGroupingKeyNames);
}
if (!this.ruleFilters.isEmpty()) {
ruleDTO.getRuleFilters().clear();
List<String> tmpRuleFilters = new ArrayList<>();
this.getRuleFilters().forEach(itemDTO -> {
tmpRuleFilters.add(itemDTO.name);
});
ruleDTO.getRuleFilters().addAll(tmpRuleFilters);
}
return ruleDTO;
}

Map nested beans list : "org.mapstruct.Mapping"

I want to map the Abc class to AbcDTO using "org.mapstruct.Mapping"
class Abc {
private List<Xyz> xyz = null;
private String uvw;
private String cde;
}
class AbcDTO{
private List<XyzDTO> xyz = null;
private String uvw;
private String cde;
}
class Xyz{
private String type;
private String value;
private String docId;
}
class XyzDTO{
private String type;
private String value;
private DocDTO document;
}
I tried to map the classes by using the annotation:
#Mappings({
#Mapping(source = "xyz.docId", target = "xyz.doc")
})
abcDTO abcToabcDTO(abc abc)
Can someone please help with how do i iterate through the nested beans and map the docId to doc?
If the names are same they map automatically but I want to map from docId to doc.
when you want map list you can define it :
#Mapping(source="docId", target="doc")
XyzDTO xyzToXyzDTO(XyZ xyz);
#Mapping(source="xyz", target="xyz") //useless if two lists got same name, but good for comprehention
AbcDTO abcToAbcDTA(Abc abc);
It should be as below (
you can give it a try):
#Mappings({
#Mapping(target="doc", source="abc.docId")
})
AbcDTO abcToabcDTO(Abc abc);```

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)

How to Query MongoDB With HashMaps value Using Morphia?

This is a part of my code :
#Entity("messages")
public class Message implements Serializable {
#Id
private ObjectId id;
private long time;
#Reference(lazy = true)
private Payload payload;
private String serviceName;
private Map<String, String> headerMap;
private MessageStatus messageStatus = MessageStatus.ESB;
private MessageType messageType;
i need to find a document which
its headerMap contains "requestID".
the value of headerMap.get("requestID") equals "DUMDUMID".
Thank you
ds.find(Message.class).field("headerMap.requestID").equal("DUMDUMID").get();

Categories