How to set atributes throught reflexion - java

I have map of <String, Object>:
params={
dateOfBirthTo=23.05.2013,
lastName=bbb, ssn=aa-ccc-ddd,
gender=MALE,
dateOfBirthFrom=03.05.2013,
firstName=aaa
}
Then I have form which contains variable from this map. How I can create new form with this value through reflection?
Something like:
SimpleForm form = new SimpleForm();
Map<String, Object> parameters = request.getParams();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
// fill form
}

You could use Apache Commons BeanUtils
SimpleForm form = new SimpleForm();
Map<String, Object> parameters = request.getParams();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
BeanUtils.setProperty(form, entry.getKey(), entry.getValue());
}

Related

How to iterate List<Map<String, Object>> and add the key and value dynamically in another hash map in java

I'm trying to iterate the List<Map<String, Object>> and want to check if the code is "approved" or not - if code is having value "approved" then I would like to add "id" as Key and "date" as Value in another hashMap.
List<Map<String, Object>> prodIds = ((List<Map<String, Object>>) myIds.get("result"));
This prodIds returns below set of records:
[{id=[14766724], Date=[1999-01-01]}, {id=[49295837], code=[approved], Date=[2003-04-01]}]
[{id=[58761474621], code=[approved], Date=[2017-09-30]}, {id=[3368781], code=[Cancelled], Date=[2014-01-01]}, {id=[48843224], code=[Cancelled], Date=[2009-01-01]}]
I want the output something like this: If code is "approved" - my new hash map should have value like below:
map.put("49295837", "2003-04-01")
map.put("58761474621", "2017-09-30")
Java Code
List<Map<String, Object>> prodIds = ((List<Map<String, Object>>) myIds.get("result"));
System.out.println("prodIds : " +prodIds );
// [{id=[14766724], Date=[1999-01-01]}, {id=[49295837], code=[approved], Date=[2003-04-01]}]
// [{id=[58761474621], code=[approved], Date=[2017-09-30]}, {id=[3368781], code=[Cancelled], Date=[2014-01-01]}, {id=[48843224], code=[Cancelled], Date=[2009-01-01]}]
Map<String, String> newMap = new HashMap<>();
for (Map<String, Object> map : prodIds) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
System.out.println("Key : " +key);
String value = (String) entry.getValue();
System.out.println(" Value : " +value);
}
}
I'm having difficulty how to put the key(id) and value(Date) dynamically if the code value is "approved" into new hash map. It would be really helpful if someone can help me with this.
Appreciated your help in advance!
Thanks
As best as I can determine by your example, this should work. But for each Map<String,Object> I need to know what Object is (e.g. String, List<>, etc).
I am assuming they are lists. If I'm wrong you will get a ClassCastException
public static Map<String, String>
getApproved(List<Map<String, Object>> prodIds) {
Map<String, String> newMap = new HashMap<>();
for (Map<String, Object> map : prodIds) {
if (map.containsKey("code") &&
((List<String>) map.get("code")).get(0)
.equals("approved")) {
newMap.put(((List<String>) map.get("id")).get(0),
(String) ((List<String>) map.get("Date"))
.get(0));
}
}
return newMap;
}
Map<String, String> newMap = getApproved(prodIds);
newMap.entrySet().forEach(System.out::println);
Prints
58761474621=2017-09-30
49295837=2003-04-01
It would help if you could describe all your data structures. Like what is the Object type of map?

concurrent modification exception while iterating list map string object and edit key

I'm putting in a List<Map<String, Object>> the result of a query along with the column names. Sometimes column names are like TableAlias.ColumnName, in that case I want to change it to just ColumnName and remove TableAlias. for that I have below code:
queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
for (Map<String, Object> map : queryResult) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 0) {
Object obj = map.remove(entry.getKey());
map.put(keyData[1], obj);
}
}
}
That is giving me concurrent modification exception so I was trying with an iterator like below:
for (Map<String, Object> map : queryResult) {
for(Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Object> entry = it.next();
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 0) {
it.remove();
}
}
}
But not sure how to add the item back with the new key.
Any suggestions please?
I would iterate over the original map and fill another map with the updated keys.
queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
Map<String, Object> newMap = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 1) {
newMap.put(keyData[1], entry.getValue());
} else {
newMap.put(entry.getKey(), entry.getValue());
}
}

Convert Entry<String, List<String>> to Entry<String, String>

I am trying to store the header name and it's first value as an Entry into a list. I am not sure how to achieve this.
HttpHeaders headerNames = request.getHeaders();
List<Entry<String, String>> reqHeaders = new ArrayList<>();
for (Entry<String, List<String>> entry : headerNames.entrySet()) {
reqHeaders.add(entry.getKey(), entry.getValue().get(0)); //This line is incorrect
}
Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object).
for (Map.Entry<String, List<String>> entry : headerNames.entrySet()) {
reqHeaders.add(Map.entry(entry.getKey(), entry.getValue().get(0)));
}
For before Java 9, you can use AbstractMap.SimpleImmutableEntry or AbstractMap.SimpleEntry
for (Map.Entry<String, List<String>> entry : headerNames.entrySet()) {
reqHeaders.add(new SimpleImmutableEntry<>(entry.getKey(), entry.getValue().get(0))); // immutable
reqHeaders.add(new SimpleEntry<>(entry.getKey(), entry.getValue().get(0))); // mutable version
}
I tried something like this, but #azro answer is simpler.
HttpHeaders headerNames = request.getHeaders();
Map<String, String> headersMap = new HashMap<>();
List<Entry<String, String>> requestHeaders = new ArrayList<>();
for (Entry<String, List<String>> entry : headerNames.entrySet()) {
headersMap.put(entry.getKey(), entry.getValue().get(0));
}
requestHeaders.addAll(headersMap.entrySet());

How to create hierarchical JSON from java.util.Properties object

I'm looking for good way or complete API to create a hierarchical JSON from plain java.util.Properties object.
Exist java.util.Properties object, e.g.:
car.color=blue
car.places=4
car.motor.dimension=2L
car.motor.ps=120
and the target json structur should be:
{
"car":
{"color":"blue",
"places":4,
"motor":
{"dimension":"2L",
"ps":120
}
}
}
public void run() throws IOException {
Properties properties = ...;
Map<String, Object> map = new TreeMap<>();
for (Object key : properties.keySet()) {
List<String> keyList = Arrays.asList(((String) key).split("\\."));
Map<String, Object> valueMap = createTree(keyList, map);
String value = properties.getProperty((String) key);
value = StringEscapeUtils.unescapeHtml(value);
valueMap.put(keyList.get(keyList.size() - 1), value);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(map);
System.out.println("Ready, converts " + properties.size() + " entries.");
}
#SuppressWarnings("unchecked")
private Map<String, Object> createTree(List<String> keys, Map<String, Object> map) {
Map<String, Object> valueMap = (Map<String, Object>) map.get(keys.get(0));
if (valueMap == null) {
valueMap = new HashMap<String, Object>();
}
map.put(keys.get(0), valueMap);
Map<String, Object> out = valueMap;
if (keys.size() > 2) {
out = createTree(keys.subList(1, keys.size()), valueMap);
}
return out;
}
The following project 'Java Properties to JSON' achieves exactly what you seek.
However, it has a restriction on Java 8.
Would be great if someone actually provides changes to make it Java 7 compatible.
You will need to parse your properties to Map<String, Object> where your Object will be either another Map<String, Object> or a String. For this you will have to write your own code. I suppose you will need to take your properties keys and split them over "." using method String.split(). Note that in your code you will need to use "\\." as a parameter as "." is a regular expression. Once you build your Map it is very easy to convert it to JSON using Jackson library or any available JSON library.

How to add a Map to RequestBody instead of adding key value pairs individually when using okhttp?

If I have this:
RequestBody formBody = new FormEncodingBuilder()
.add("email", "Jurassic#Park.com")
.add("tel", "90301171XX")
.build();
But instead of adding key value pairs individually, I just want to add a variable of type map that has a variable size, how do I go about adding it?
How about just iterating over the map yourself and adding each key/value? Example:
private FormEncodingBuilder makeBuilderFromMap(final Map<String, String> map) {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (final Map.Entry<String, String> entrySet : map.entrySet()) {
formBody.add(entrySet.getKey(), entrySet.getValue());
}
return formBody;
}
usage:
RequestBody body = makeBuilderFromMap(map)
.otherBuilderStuff()
.otherBuilderStuff()
.otherBuilderStuff()
.build();
If you do the typing correctly the code provided by nbokmans works well. Here the corrected version:
private RequestBody makeFormBody(final Map<String, String> map) {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (final Map.Entry<String, String> entrySet : map.entrySet()) {
formBody.add(entrySet.getKey(), entrySet.getValue());
}
return formBody.build();
}

Categories