I have the following mapping: mapTechnicaltoM. My leader asked me to use orika mappping in mapTechnicaltoM, can someone please help me with this?
List<P> pList = new ArrayList<>();
Iterator<Map.Entry<String, Map<String, Technical>>> pIterator = asset.getP().entrySet().iterator();
while (pIterator.hasNext()) {
Map.Entry<String, Map<String, Technical>> pPair = Iterator.next();
Iterator<Map.Entry<String, Technical>> pTIterator = (pPair.getValue()).entrySet().iterator();
while (pTIterator.hasNext()) {
Map.Entry pTRsPair = pTIterator.next();
P eP = new P();
eP.setCode(pPair.getKey());
eP.setTypeCode(String.valueOf(pTRsPair.getKey()).toUpperCase());
mapPerilTechnicalRatesToNaturalPerils((Technical) pTRsPair.getValue(), eP);
pList.add(eP);
}
}
private void mapTechnicaltoM(Technical technical, P pp){
pp.setStatusCode(technical.getStatusDetails().getStatusCode());
pp.setPremium(technical.getPremiumDetails().getRetainedPremium());
}
Related
Hi I'm trying to create yaml file using java and snakeyaml but i did basic coding on it and wanted to improvise on the creation of hash maps and array list with class objects anyone can help in refactoring this code as I'm new to java.I want help in specifically creating classes for the redundant objects created in createmap function
Sample Code
package com.yaml.writer;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JavaToYamlWithOptions {
public static void main(String[] args) {
Map<String,Object> map = createMap();
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(options);
String output = yaml.dump(map);
System.out.println(output);
}
private static Map<String,Object> createMap() {
Map<String,Object> env = new HashMap<>();
Map<String,String> rpath = new HashMap<>();
Map<String,String> rtab = new HashMap<>();
List<Map<String,String>> rlist = new ArrayList<>();
rpath.put("path","hdfs");
rtab.put("tabname","tbl");
rlist.add(rpath);
rlist.add(rtab);
Map<String,List<Map<String,String>>> parq = new HashMap<>();
parq.put("parquet",rlist);
List<Map<String,List<Map<String,String>>>> readlst = new ArrayList<>();
readlst.add(parq);
Map<String,List<Map<String,List<Map<String,String>>>>> readmap = new HashMap<>();
readmap.put("read", readlst);
Map<String,String> coltrans = new HashMap<>();
Map<String,String> colsec = new HashMap<>();
List<Map<String,String>> collist = new ArrayList<>();
coltrans.put("coltrans","colxx");
colsec.put("coal","false");
collist.add(coltrans);
collist.add(colsec);
Map<String,List<Map<String,String>>> trans = new HashMap<>();
trans.put("transform",collist);
List<Map<String,List<Map<String,String>>>> trlist = new ArrayList<>();
trlist.add(trans);
Map<String,List<Map<String,List<Map<String,String>>>>> trmap = new HashMap<>();
trmap.put("transform", trlist);
env.put("environment" ,"kubernetes");
Map<String,String> wpath = new HashMap<>();
List<Map<String,String>> wlist = new ArrayList<>();
wpath.put("path","whdfs");
wlist.add(wpath);
Map<String,List<Map<String,String>>> wparq = new HashMap<>();
wparq.put("parquet",wlist);
List<Map<String,List<Map<String,String>>>> wrlst = new ArrayList<>();
wrlst.add(wparq);
Map<String,List<Map<String,List<Map<String,String>>>>> wmap = new HashMap<>();
wmap.put("write", wrlst);
Map<String,Object> action = new HashMap<>();
trmap.putAll(wmap);
readmap.putAll(trmap);
action.put("action1",readmap);
Map<String,Object> actions = new HashMap<>();
actions.put("action",action);
env.putAll(actions);
return env;
}
}
expected output
environment: "kubernetes"
action:
action1:
transform:
- transform:
- colTrans: colxx
- coal: false
read:
- parquet:
- path: "hdfs"
- tabname: "tbl"
write:
- parquet:
- path: "whdfs"
First of all let me describe the scenario.
Step 1. I have to read from a file, line by line. The file is a .json and each line has the following format:
{
"schema":{Several keys that are to be deleted},
"payload":{"key1":20001,"key2":"aaaa","key3":"bbbb","key4":"USD","key5":"100"}
}
Step 2. Delete schema object and end up with (added more examples for the sake of the next steps):
{"key1":20001,"key2":"aaaa","key3":"bbbb","key4":"USD","key5":"100"}
{"key1":20001,"key2":"aaaa","key3":"bbbb","key4":"US","key5":"90"}
{"key1":2002,"key2":"cccc","key3":"hhhh","key4":"CN","key5":"80"}
Step 3. Split these values into key and value by making them json in memory and use the strings as keys and values with map
{"key1":20001,"key2":"aaaa","key3":"bbbb"} = {"key4":"USD","key5":"100"}
{"key1":20001,"key2":"aaaa","key3":"bbbb"} = {"key4":"US","key5":"90"}
{"key1":2002,"key2":"cccc","key3":"hhhh"} = {"key4":"CN","key5":"80"}
Step 4, and the one I can't work out due to my lack of knowledge in Pcollections. I need to grab all the lines read and do a GroupByKey so that it would end up like:
{"key1":20001,"key2":"aaaa","key3":"bbbb"} = [
{"key4":"USD","key5":"100"},
{"key4":"US","key5":"90"} ]
{"key1":2002,"key2":"cccc","key3":"hhhh"} = {"key4":"CN","key5":"80"}
Righ now my code looks like this:
static void runSimplePipeline(PipelineOptionsCustom options) {
Pipeline p = Pipeline.create(options);
p.apply("ReadLines", TextIO.read().from(options.getInputFile()))
.apply("TransformData", ParDo.of(new DoFn<String, String>() {
#ProcessElement
public void processElement(ProcessContext c) {
Gson gson = new GsonBuilder().create();
ObjectMapper oMapper = new ObjectMapper();
JSONObject obj_key = new JSONObject();
JSONObject obj_value = new JSONObject();
List<String> listMainKeys = Arrays.asList(new String[]{"Key1", "Key2", "Key3"});
HashMap<String, Object> parsedMap = gson.fromJson(c.element().toString(), HashMap.class);
parsedMap.remove("schema");
Map<String, String> map = oMapper.convertValue(parsedMap.get("payload"), Map.class);
for (Map.Entry<String,String> entry : map.entrySet()) {
if (listMainKeys.contains(entry.getKey())) {
obj_key.put(entry.getKey(),entry.getValue());
} else {
obj_value.put(entry.getKey(),entry.getValue());
}
}
KV objectKV = KV.of(obj_key.toJSONString(), obj_value.toJSONString());
System.out.print(obj_key.toString() + " : " + obj_value.toString() +"\n");
}
})); <------- RIGHT HERE
p.run().waitUntilFinish();
}
Now the obvious part is that on where it says "RIGHT HERE" I should have another apply with CountByKey however that requires a full PCollection and that's what I do not really understand.
Here's the code, thanks to Guillem Xercavins's linked Github:
static void runSimplePipeline(PipelineOptionsCustom options) {
Pipeline p = Pipeline.create(options);
PCollection<Void> results = p.apply("ReadLines", TextIO.read().from(options.getInputFile()))
.apply("TransformData", ParDo.of(new DoFn<String, KV<String, String>>() {
#ProcessElement
public void processElement(ProcessContext c) {
Gson gson = new GsonBuilder().create();
ObjectMapper oMapper = new ObjectMapper();
JSONObject obj_key = new JSONObject();
JSONObject obj_value = new JSONObject();
List<String> listMainKeys = Arrays
.asList(new String[] { "EBELN", "AEDAT", "BATXT", "EKOTX", "Land1", "WAERS" });
HashMap<String, Object> parsedMap = gson.fromJson(c.element().toString(), HashMap.class);
parsedMap.remove("schema");
Map<String, String> map = oMapper.convertValue(parsedMap.get("payload"), Map.class);
for (Map.Entry<String, String> entry : map.entrySet()) {
if (listMainKeys.contains(entry.getKey())) {
obj_key.put(entry.getKey(), entry.getValue());
} else {
obj_value.put(entry.getKey(), entry.getValue());
}
}
KV objectKV = KV.of(obj_key.toJSONString(), obj_value.toJSONString());
c.output(objectKV);
}
})).apply("Group By Key", GroupByKey.<String, String>create())
.apply("Continue Processing", ParDo.of(new DoFn<KV<String, Iterable<String>>, Void>() {
#ProcessElement
public void processElement(ProcessContext c) {
System.out.print(c.element());
}
}));
p.run().waitUntilFinish();
}
I'm trying to parse this JSON using gson:
{"hvs1":{"16191":[["TestFile3","C",["A"]],["TestFile3","-",["1G","1A"]]],"16193":[["TestFile3","C",["G"]]]},"hvs2":{"25":[["TestFile3","-",["1A"]]]},"outros":{"16423":[["TestFile3","A",["T"]]]}}
Into this object
public class Results {
private String regiaoAfetada;
private String posicaoReferencia;
private String nomeDoArquivo;
private String baseAlteradaReferencia;
private List<String> mutacaoEncontrada;
//get and set
}
And my test class to try to achive this, but I'm getting a error.
public class JsonTeste {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
Type type = new TypeToken<TreeMap<String, TreeMap>>() {
}.getType();
TreeMap<String, TreeMap<String, List<List<List<String>>>>> map = gson.fromJson(reader, type);
List<Results> listaMutacoes = new ArrayList<Results>();
for (Entry<String, TreeMap<String, List<List<List<String>>>>> regioesMap : map.entrySet()) {
TreeMap<String, List<List<List<String>>>> regiaoUm = regioesMap.getValue();
for (Entry<String, List<List<List<String>>>> regiaoUmResult : regiaoUm.entrySet()) {
List<List<List<String>>> resultados = regiaoUmResult.getValue();
for (List<List<String>> list : resultados) {
Results resultado = new Results();
resultado.setRegiaoAfetada(regioesMap.getKey());
resultado.setPosicaoReferencia(regiaoUmResult.getKey());
resultado.setNomeDoArquivo(list.get(0).toString());
resultado.setBaseAlteradaReferencia(list.get(1).toString());
resultado.setMutacaoEncontrada(list.get(2));
listaMutacoes.add(resultado);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem is when I try to parse this part
[
"TestFile3",
"-",
[
"1G",
"1A"
]
]
Because I have two Strings and a Array inside, so the problem Is when I try to place "TestFile3" into setNomeDoArquivo, but even if I comment this line, i get the same error in the second line.
resultado.setNomeDoArquivo(list.get(0).toString());
resultado.setBaseAlteradaReferencia(list.get(1).toString());
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List
Can you guys help me?
The List resultados is of List<string> or List<List<String>>.When you get the item of resultados it can be one of them. So to generalized declare it as List<List<Object>>
Try The below Code :
Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
Type type = new TypeToken<TreeMap<String, TreeMap>>() {
}.getType();
TreeMap<String, TreeMap<String, List<List<Object>>>> map = gson.fromJson(reader, type);
List<Results> listaMutacoes = new ArrayList<>();
for (Map.Entry<String, TreeMap<String, List<List<Object>>>> regioesMap : map.entrySet()) {
TreeMap<String, List<List<Object>>> regiaoUm = regioesMap.getValue();
for (Map.Entry<String, List<List<Object>>> regiaoUmResult : regiaoUm.entrySet()) {
List<List<Object>> resultados = regiaoUmResult.getValue();
for (List<Object> list : resultados) {
System.out.println(list);
Results resultado = new Results();
resultado.setRegiaoAfetada(regioesMap.getKey());
resultado.setPosicaoReferencia(regiaoUmResult.getKey());
resultado.setNomeDoArquivo((String) list.get(0));
resultado.setBaseAlteradaReferencia((String) list.get(1));
resultado.setMutacaoEncontrada((List<String>) list.get(2));
listaMutacoes.add(resultado);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
I want to get a list of objects from database
i'm 100% that i retreive the data but the list so my php code seems to be good
public ArrayList<Categorie> getListCategorie() {
ArrayList<Categorie> listcategories = new ArrayList<>();
ConnectionRequest con2 = new ConnectionRequest();
con2.setUrl("http://localhost/pidev2017/selectcategorie.php");
con2.addResponseListener(new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent evt) {
try {
JSONParser j = new JSONParser();
Map<String, Object> catefories = j.parseJSON(new CharArrayReader(new String(con2.getResponseData()).toCharArray()));
List<Map<String, Object>> list = (List<Map<String, Object>>) catefories.get("Categorie");
for (Map<String, Object> obj : list) {
Categorie categorie = new Categorie();
categorie.setId(Integer.parseInt(obj.get("id").toString()));
categorie.setNomCategorie(obj.get("nomCategorie").toString());
listcategories.add(categorie);
}
} catch (IOException ex) {
}
}
});
NetworkManager.getInstance().addToQueue(con2);
return listcategories;
}
when i want to fetch my result "listcategories" i found that is empty
Change
NetworkManager.getInstance().addToQueue(con2);
to
NetworkManager.getInstance().addToQueueAndWait(con2);
It's possible that you try to get the result before the data has been fetched.
HashMap<String, HashMap<String, String>> hm = new HashMap<String, HashMap<String, String>>();
hm.put("Title1","Key1");
for(int i=0;i<2;i++) {
HashMap<String, String> hm1 = new HashMap<String, String>();
hm1.put("Key1","Value1");
}
if i have call Title1 that time they call another hashmap. i want
this type of output
hm<key,value(object hm1)>
hm<key,value)
first hashmap object call second hashmap key
If I correct undestand what you want, use following code
HashMap<String, HashMap<String, String>> hm = new HashMap<>();
HashMap<String, String> hm1 = new HashMap<>();
for(int i=0;i<2;i++) {
hm1.put("Key1","Value1");
}
hm.put("Title1", hm1); // save hm
...
HashMap<String, String> hm2 = hm.get("Title1");
String s = hm2.get("Key1"); // s = "Value1"
OR you can create new class
class HashKey {
private String title;
private String key;
...
// getters, setters, constructor, hashcode and equals
}
and just use HashMap < HashKey, String > hm, for example:
hm.put(new HashKey("Title1", "Key 1"), "Value");
...
String s = hm.get(new HashKey("Title1", "Key 1")); // Value
you can do something likewise,
HashMap<String,HashMap<String,String>> hm = new HashMap<String,HashMap<String,String>>();
HashMap<String,String> hm1 = new HashMap<String,String>();
hm1.put("subkey1","subvalue");
hm.put("Title1",hm1);
HashMap<String,String> newhm = hm.get("Title1");
import java.util.HashMap;
import java.util.Map;
public class MapInMap {
Map<String, Map<String, String>> standards =
new HashMap<String, Map<String, String>>();
void addValues() {
Map<String, String> studentA = new HashMap<String, String>();
studentA.put("A1", "49");
studentA.put("A2", "45");
studentA.put("A3", "43");
studentA.put("A4", "39");
standards.put("A", studentA);
Map<String, String> studentB = new HashMap<String, String>();
studentB.put("B1", "29");
studentB.put("B2", "25");
studentB.put("B3", "33");
studentB.put("B4", "29");
standards.put("B", studentB);
}
void disp() {
for (Map.Entry<String, Map<String, String>> entryL1 : standards
.entrySet()) {
System.out.println("Standard :" + entryL1.getKey());
for (Map.Entry<String, String> entryL2 : entryL1.getValue()
.entrySet()) {
System.out.println(entryL2.getKey() + "/" + entryL2.getValue());
}
}
}
public static void main(String args[]) {
MapInMap inMap = new MapInMap();
inMap.addValues();
inMap.disp();
}
}