How to get specific class and attribute using java 8 - java

I've defined the following set of data
Response response = new Response();
List<ObjectTest> objList = new ArrayList<ObjectTest>();
objList.add(new ObjectTest(new Attributes(new FirstName("ab","1"),new LastName("hernandez","2"))));
objList.add(new ObjectTest(new Attributes(new FirstName("jose","1"),new LastName("perez","2"))));
objList.add(new ObjectTest(new Attributes(new FirstName("paco","2"),new LastName("jackson","2"))));
objList.add(new ObjectTest(new Attributes(new FirstName("pedro","1"),new LastName("herrera","2"))));
objList.add(new ObjectTest(new Attributes(new FirstName("juan","2"),new LastName("flores","2"))));
response.setObjectList(objList);
So based on what the user selects I need to be able to get the specific class and the attribute, for example:
if the user selects [Attributes - FirstName - value] the output would be :
ab
jose
paco
pedro
juan
if the user selects [Attributes - LastName- status] the output would be:
2
2
2
2
2
The problem here is that I dont know how to get the specific class in runtime. Also the main object could have any number of classes inside of it like MainClass.ClassA.ClasstB.ClassX.classAttributeValue. The only thing that I know is that the last value is going to be the one that I have to take in that case I have to print classAttributeValue . Any ideas how to solve this using java 8 ?

Assuming your class structure looks something like this:
public static abstract class Attribute {
public final String value;
public final String status;
public Attribute(String value, String status) {
this.value = value;
this.status = status;
}
}
public static class FirstName extends Attribute {
public FirstName(String value, String status) {
super(value, status);
}
}
public static class LastName extends Attribute {
public LastName(String value, String status) {
super(value, status);
}
}
public static class Attributes {
public final FirstName firstName;
public final LastName lastName;
public Attributes(FirstName firstName, LastName lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
public static class ObjectTest {
public final Attributes attributes;
public ObjectTest(Attributes attributes) {
this.attributes = attributes;
}
}
You can define java.util.function.Function accessors for each stage:
Function<ObjectTest, Attributes> attributes = t -> t.attributes;
Function<Attributes, FirstName> firstName = t -> t.firstName;
Function<Attributes, LastName> lastName = t -> t.lastName;
Function<Attribute, String> value = t -> t.value;
Function<Attribute, String> status = t -> t.status;
And combine them like so:
Function<ObjectTest, String> attributeFirstNameValue =
attributes.andThen(firstName).andThen(value);
Function<ObjectTest, String> attributeLastNameStatus =
attributes.andThen(lastName).andThen(status);
Then apply the combined accessor to the list:
objList.stream().map(attributeFirstNameValue).forEach(System.out::println);
objList.stream().map(attributeLastNameStatus).forEach(System.out::println);

Is it critical to use this class structure?
In your example using a associative container is more suitable.
For example you can create class with structure like this:
Firstly you shoud something for itterate by Tree:
class DynamicObjectNode {
private HashMap<String, DynamicObjectNode> childs = new HashMap<>();
public HashMap<String, DynamicObjectNode> getChilds() {
return childs;
}
}
All values should be in leafs:
class DynamicObjectNodeValue<T> extends DynamicObjectNode {
public DynamicObjectNodeValue(T value) {
this.value = value;
}
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
#Override
public HashMap<String, DynamicObjectNode> getChilds() {
return null; //Tree leafs should not has childs
}
}
If you need to work with this as objects. You can use wrapped class like this:
class FirstNameAttribute extends DynamicObjectNode{
private static final String NameValueProperty = "NameValue";
private static final String StatusProperty = "Status";
private DynamicObjectNodeValue<String> nameValue = new DynamicObjectNodeValue<String>("Default name");
private DynamicObjectNodeValue<Integer> status = new DynamicObjectNodeValue<Integer>(1);
public FirstNameAttribute() {
getChilds().put(NameValueProperty, nameValue);
getChilds().put(StatusProperty, status);
}
public String getName() {
return nameValue.getValue();
}
public Integer getStatus() {
return status.getValue();
}
public void setName(String val) {
nameValue.setValue(val);
}
public void setStatus(Integer val) {
status.setValue(val);
}
}
So, with this code you can iterate it as a Tree and get values Dynamic.
And you can use this as objects to call some methods.

Thank you for your responses, what I finally did was to use JsonNode and based on the attribute I wanted to get I was iterating the same object and assign the result to se same object for example:
Json Response:
Object.Person1.firstName.value
I created an array of that and split it by "." then I created a for and I used this
jsonNode = jsonNode.get(inputArray[x]);
at the end the last element of the array is the one that I need so I added some logic to get it.

Related

Spring Enum list empty in #RequestBody

I have the below enum with two values, and i have a search api with many fields, One of these fields is a list of StatusEnum. So i created a dto that contains this field.
The problem when i send the data the list status is always empty
json exp: {"status":["En activité"],"startDate":null,"endDate":null}
public enum StatusEnum {
INACTIVITY, ENDACTIVITY;
private static Map<String, StatusEnum > namesMap = new HashMap<>(2);
static {
namesMap.put("En activité", INACTIVITY);
namesMap.put("En fin d'activité", ENDACTIVITY);
}
#JsonCreator
public static StatusEnum forValue(String value) {
return namesMap.get(StringUtils.lowerCase(value));
}
#JsonValue
public String toValue() {
for (Entry<String, StatusEnum > entry : namesMap.entrySet()) {
if (entry.getValue() == this)
return entry.getKey();
}
return null;
}
}
#PostMapping
public ResponseEntity<List<Object>> search(#RequestBody SearchDTO search) { }
public class SearchDTO {
private Date startDate;
private Date endDate
private List<StatusEnum> status;
//getter and setter
}
#JsonCreator
public static StatusEnum forValue(String value) {
return namesMap.get(StringUtils.lowerCase(value));
}
Problem is the usage of #lowerCase in forValue!
Your keys in your map aren't lower-cased. That's why namesMap.get can't find anything.

How to override the #AdminPresentation for existing attributes [Broadleaf Commerce]

I am trying to override the #AdminPresentation of the following attribute defined in ProductImpl:
#Column(name = "DISPLAY_TEMPLATE")
#AdminPresentation(friendlyName = "ProductImpl_Product_Display_Template",
group = GroupName.Advanced)
protected String displayTemplate;
Currently, it is displayed as a text field by default as there is no fieldType attribute provided. But I want to display a dropdown select menu with predefined values such as Product and Plan. Here is what I've tried so far:
I've created a class DisplayTemplateType that implements BroadleafEnumerationType and defined PLAN and PRODUCT enums. Here is the code of that class:
public class DisplayTemplateType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 7761108654549553693L;
private static final Map<String, DisplayTemplateType> TYPES = new LinkedHashMap<String, DisplayTemplateType>();
public static final DisplayTemplateType PLAN = new DisplayTemplateType("PLAN", "PLAN");
public static final DisplayTemplateType PRODUCT = new DisplayTemplateType("PRODUCT", "PRODUCT");
public static DisplayTemplateType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public DisplayTemplateType() {
//do nothing
}
public DisplayTemplateType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
#Override
public String getType() {
return type;
}
#Override
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
// equals() and hashCode() implementation is removed for readability
}
Then in applicationContext-admin.xml file, I have added the following override properties:
<mo:override id="blMetadataOverrides">
<mo:overrideItem ceilingEntity="org.broadleafcommerce.core.catalog.domain.Product">
<mo:field name="displayTemplate">
<mo:property name="explicitFieldType" value="BROADLEAF_ENUMERATION"/>
<mo:property name="broadleafEnumeration" value="com.community.core.domain.DisplayTemplateType"/>
</mo:field>
</mo:overrideItem>
</mo:override>
But it didn't change anything. Am I missing something here?
Finally, after trying many things, I came up with a workaround. Instead of going with the XML based approach, I had to extend the ProductImpl class to override #AdminPresentation of its attributes. But for extending I needed to define an #Entity and as a result, I needed to create a useless table to bind to that entity. I know this is not the perfect approach but I couldn't find any better solution for this. Here is my code, so that someone might get help from it in the future:
#Entity
#Immutable
#AdminPresentationMergeOverrides({
#AdminPresentationMergeOverride(name = "displayTemplate", mergeEntries = {
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.FIELDTYPE, overrideValue = "BROADLEAF_ENUMERATION"),
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.BROADLEAFENUMERATION, overrideValue = "com.community.core.domain.DisplayTemplateType"),
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE, overrideValue = "REQUIRED"),
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.DEFAULTVALUE, overrideValue = "PLAN")
})
})
public class CustomProduct extends ProductImpl {
private static final long serialVersionUID = -5745207984235258075L;
}
This is how it is displayed now:

What is the best way to get the result through Java8 function?

I need to filter elements and then sort based on certain column. Post that I would need to find the unique entries based on combination of columns. Since it is file processing, pipe(|) is used as delimiter to denote the column value.
String s1= "12|Thor|Asgaurd|1000000|Avenger|Active"
String s2= "234|Iron man|New York|9999999|Avenger|Active"
String s3= "420|Loki|Asgaurd|||Inactive"
String s4= "12|Thor|Asgaurd Bank|1000000|Avenger HQ|Active"
Data first needs to be filtered based on the Active/Inactive status. Then it needs to be sorted based on 4th column. Lastly, the uniqueness needs to be maintained by combining column 1,2,3.
Expected Output =
"234|Iron man|New York|9999999|Avenger|Active"
"12|Thor|Asgaurd|1000000|Avenger|Active"
Creating a model class and parsing the string is the way to go, but if for some reaseon you don't want to do that you can do it this way:
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
List<String> result = Stream.of(s1, s2, s3, s4)
.filter(s -> s.split("\\|")[5].equals("Active"))
.sorted(Comparator.comparing(e -> e.split("\\|")[4]))
.collect(Collectors.toList());
First of all you should create an Object which represents your String data. Something like this:
public class MyObject {
private int id;
private String name;
private String location;
private Integer value;
private String category;
private String state;
public MyObject(String entry) {
String[] parts = entry.split("\\|");
if (parts.length != 6) {
throw new IllegalArgumentException("entry has not 6 parts");
}
id = Integer.parseInt(parts[0]);
name = parts[1];
location = parts[2];
try {
value = Integer.parseInt(parts[3]);
} catch (NumberFormatException ignored) {
}
category = parts[4];
state = parts[5];
}
// getters
#Override
public String toString() {
return String.join("|", String.valueOf(id), name, location, String.valueOf(value), category, state);
}
}
With this you can create a Stream of objects from your Strings and to the filter, sort and distinct operations afterwards:
Collection<MyObject> result = Stream.of(s1, s2, s3, s4)
.map(MyObject::new)
.filter(o -> "Active".equals(o.getState()))
.sorted(Comparator.comparing(MyObject::getValue).reversed())
.collect(Collectors.toMap(o -> Arrays.asList(o.getId(), o.getName()),
Function.identity(), (o1, o2) -> o1, LinkedHashMap::new))
.values();
result.forEach(System.out::println);
After the map operation you filter the values by state and sort them by column 4 (value in my case). At the end you collect all the values in a map for the distinct operation. Add all values you need distinction for to the Arrays.asList(). As values the map takes all the original values (Function.identity()). For duplicates we keep the first value ((o1, o2) -> o1) and we are using a LinkedHashMap to keep the order of the items. At the end wee use only the values of the map.
If you need a List instead of a Collection use new ArrayList(result).
The result will be this:
234|Iron man|New York|9999999|Avenger|Active
12|Thor|Asgaurd|1000000|Avenger|Active
It seems like you're unable to filter while everything is string only.
Try this,
create a new model class which can hold your columns.
Ex:
class MyData{
private String name;
private String city;
private String distance;
private String organization;
private String status;
//And create Getter Setter method for all above fields.
}
Now came to your main class where you can play with your code stuff.
Map<MyData> map = new HashMap<MyData>();
MyData myData = new MyData();
myData.setName("Thor");
myData.setCity("Asgaurd");
myData.setDistance("1000000");
myData.setOrganization("Avenger");
myData.setStatus("Active");
map.put(12, myData);
//Same thing for all other data (note: use the loop for data insertion in map)
Map<String, MyData> sorted = map.entrySet().stream().sorted(comparingByValue()).collect(toMap(e -> e.getKey(), e -> e.getValue().getName(), (e1, e2) -> e2,LinkedHashMap::new));
System.out.println("map after sorting by values: " + sorted);
You can solve your task this way:
Firstly, just create POJO(Plain Old Java Object) and override the toString() method.
class MarvelPerson {
private Integer id;
private String name;
private String origin;
private Integer point = null;
private String faction;
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public Integer getPoint() {
return point;
}
public void setPoint(Integer point) {
this.point = point;
}
public String getFaction() {
return faction;
}
public void setFaction(String faction) {
this.faction = faction;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(id);
builder.append("|");
builder.append(name);
builder.append("|");
builder.append(origin);
builder.append("|");
if(point != null) {
builder.append(point);
}
builder.append("|");
if(faction != null) {
builder.append(faction);
}
builder.append("|");
builder.append(status);
return builder.toString();
}
}
Then, you should write the parser from string to MarvelPerson. Side note: Carefully, my implementation is pretty basic, and I suppose it should be modified because I may not have foreseen some corner cases.
class PersonParser {
static MarvelPerson parse(String data) {
MarvelPerson person = new MarvelPerson();
String[] array = data.split("\\|", -1);
person.setId(Integer.parseInt(array[0]));
person.setName(array[1]);
person.setOrigin(array[2]);
if(!array[3].isEmpty()) {
person.setPoint(Integer.parseInt(array[3]));
}
if(!array[4].isEmpty()) {
person.setFaction(array[4]);
}
person.setStatus(array[5]);
return person;
}
}
And then your solution:
public class Test {
public static void main(String[] args) {
List<MarvelPerson> list = new ArrayList<>();
list.add(PersonParser.parse("12|Thor|Asgaurd|1000000|Avenger|Active"));
list.add(PersonParser.parse("234|Iron man|New York|9999999|Avenger|Active"));
list.add(PersonParser.parse("420|Loki|Asgaurd|||Inactive"));
list.add(PersonParser.parse("12|Thor|Asgaurd Bank|1000000|Avenger HQ|Actie"));
list.stream()
.filter(marvelPerson -> marvelPerson.getStatus().equals("Active"))
.sorted((o1, o2) -> o1.getPoint() <= o2.getPoint() ? 1 : -1)
.forEach(marvelPerson -> {
System.out.println(marvelPerson.toString());
});
}
}
The output to be printed:
234|Iron man|New York|9999999|Avenger|Active
12|Thor|Asgaurd|1000000|Avenger|Active

Java - set the field value to the correct type from string(reflection)

I have class like this:
public enum Type {
ONE, TWO
}
#Data
public class Car {
private String name;
private int year;
private Type type;
}
I have new object:
Car car = new Car();
And I have this data:
Map<String, String> data....
name - BMW
year - 2018
type - TWO
key and value - String
And I need set this values to object(except for reflection, I see no ways)
Field year = car.getClass().getDeclaredField("year");
year.setAccessible(true);
year.set(car, data.get("year"));//2018 as string
I get exception(differently and could not be I know):
Caused by: java.lang.IllegalArgumentException: Can not set int field com.example.mapper.Car.year to java.lang.String
Therefore, the question is - how do I correctly cast the value to the desired type to set in the field?
This is a simple example, because the real task is very long explained. If in short - I get a list of values (they are always a string) and the names of the fields in which they change (also a string) and must update the fields of the object with new values
A valid solution with minimum effort would be using a JSON library as a workaround, since they have already implemented value instantiation from strings for the most common types.
For example, using ObjectMapper:
Map<String,String> data = new HashMap<>();
data.put("year","2018");
data.put("name", "BMW");
data.put("type", "TWO");
ObjectMapper mapper = new ObjectMapper();
Car car = mapper.readValue(mapper.writeValueAsString(data), Car.class);
Reflection is indeed the way to go. You can get the type using field.getType() and then check for concrete classes using Class.isAssignableFrom():
final Class<?> type = field.getType();
if (int.class.isAssignableFrom(type)) {
typedValue = Integer.parseInt(value);
} else if (type.isEnum()) {
typedValue = Enum.valueOf((Class<Enum>) type, value);
} else {
// Assume String
typedValue = value;
}
Of course this can become almost arbitrarily complex, but here's a fully working sample for your provided values. That should give you a gist on how to proceed:
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
class CarFiller {
public static void main(String[] args) throws Exception {
Map<String, String> data = new HashMap<>();
data.put("name", "BMW");
data.put("year", "2018");
data.put("type", "TWO");
Car car = new Car();
fillField(car, "name", data);
fillField(car, "year", data);
fillField(car, "type", data);
System.out.println(car);
}
private static void fillField(Object instance, String fieldName, Map<String, String> data) throws Exception {
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
String value = data.get(fieldName);
Object typedValue = null;
final Class<?> type = field.getType();
if (int.class.isAssignableFrom(type)) {
typedValue = Integer.parseInt(value);
} else if (type.isEnum()) {
typedValue = Enum.valueOf((Class<Enum>) type, value);
} else {
// Assume String
typedValue = value;
}
field.set(instance, typedValue);
}
enum Type {
ONE, TWO
}
static class Car {
private String name;
private int year;
private Type type;
public void setName(String name) {
this.name = name;
}
public void setYear(int year) {
this.year = year;
}
public void setType(Type type) {
this.type = type;
}
#Override
public String toString() {
return "Car [name=" + name + ", year=" + year + ", type=" + type + "]";
}
}
}
(See also on ideone)
I'd recommend not to use reflection everywhere it's possible. Like in your exact example.
You can create an enum class wich contains BiConsumers for each of your fields in Car class:
import java.util.Map;
import java.util.function.BiConsumer;
#Data
public class Car {
private String name;
private int year;
private Ttc.Type type;
static enum CarEnum {
name((car, value) -> car.setName(value)),
year((car, value) -> car.setYear(Integer.parseInt(value))),
type((car, value) -> car.setType(Ttc.Type.valueOf(value)));
private BiConsumer<Car, String> setValueConsumer;
CarEnum(BiConsumer<Car, String> setValueConsumer) {
this.setValueConsumer = setValueConsumer;
}
static Car createCar(Map<String, String> data) {
Car car = new Car();
data.forEach((key, value) -> valueOf(key).setValueConsumer.accept(car, value));
return car;
}
}
}
And then use it in the next way:
Map<String, String> data = new HashMap<>();
data.put("name", "BMW");
data.put("year", "2018");
data.put("type", "TWO");
Car.CarEnum.createCar(data);
Java is statically typed. Therefore you need to provide the correct type yourself. Integer.valueOf takes a String and returns an Integer.
int year = Integer.valueOf("2018");
Converting a String to an Enum works the same.
Type type = Type.valueOf("ONE");
Enum.valueOf is called in the background.
Of course you also need to add some error checking.
I'd recommand avoiding the use of reflection in such a case. You could use a different approach, e.g.
class Car
{
private final Type type;
private final String name;
private final int year;
private Car(Builder builder)
{
this.type = builder.type;
this.name = builder.name;
this.year = builder.year;
}
static class Builder
{
private Type type;
private String name;
private int year;
public Builder setType(String type)
{
this.type = Type.valueOf(type);
return this;
}
public Builder setName(String name)
{
this.name = name;
return this;
}
public Builder setYear(String year)
{
this.year = Integer.valueOf(year);
return this;
}
public Car build()
{
return new Car(this);
}
}
}
You could also add a setData method to the builder
public Builder setData(Map<String, String> data)
{
this.year = Integer.valueOf(data.get("year"));
this.type = Type.valueOf(data.get("type"));
// etc.
return this;
}
Then create a car with Car c = new Car.Builder().setData(data).build();.

Json to Object using Gson

I have a class DocumentBO which has the following attributes -
public class DocumentBO implements IStorageBO {
private String aId;
private String studyId;
private Map<AlgorithmsEnum, JobIOStatus> status;
private String text;
private Collection<Sentence> sentences;
public String getaId() {
return aId;
}
public void setaId(String aId) {
this.aId = aId;
}
public String getStudyId() {
return studyId;
}
public void setStudyId(String studyId) {
this.studyId = studyId;
}
public Map<AlgorithmsEnum, JobIOStatus> getStatus() {
return status;
}
public void setStatus(Map<AlgorithmsEnum, JobIOStatus> status) {
this.status = status;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Collection<Sentence> getSentences() {
return sentences;
}
public void setSentences(Collection<Sentence> sentences) {
this.sentences = sentences;
}
}
The AlgorithmsEnum is as follows -
public enum AlgorithmsEnum {
SENTIMENT("sentiment"),
INTENTION("intention"),
TOPIC("topic"),
NER("ner"),
UIMA("uima");
private final String value;
private AlgorithmsEnum(String value) {
this.value = value;
}
public String value() {
return value;
}
#Override
public String toString() {
return value;
}
public static AlgorithmsEnum fromValue(String value) {
if (value != null) {
for (AlgorithmsEnum aEnum : AlgorithmsEnum.values()) {
if (aEnum.value().equals(value)) {
return aEnum;
}
}
}
return null;
}
}
The JobIOStatus is also similar.
I am successfully able to create a JSON string of Collection using GSON using the following TypeToken
Type type = new TypeToken<Collection<DocumentBO>>() {}.getType();
But, when I try to recreate the Collection object using the JSON string returned by Gson and the same TypeToken, the key of the status hashmap is always returned as NULL whereas the value is successfully created. What do you think can be the issue?
The problem is that you have overridden toString() in your enum.
If you look at the JSON being produced, the keys to your Map<AlgorithmsEnum, JobIOStatus> are the lowercase names you're creating. That won't work. Gson has no idea how to recreate the enum from those when you attempt to deserialize the JSON.
If you remove your toString() method it will work just fine.
Alternatively you can use the .enableComplexMapKeySerialization() method in GsonBuilder when serializing which will ignore your toString() method and produce JSON using the default representations of your enum values which is what is required.
There are "well" known :) issues of Gson to serialize Map when the key is derived from object and its not a "native" data type.
Please use this
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().create();
Collection<DocumentBO> obj = gson.fromJson(str, type);

Categories