Not able to get particular value from java object using yaml method - java

I am using yamlbeans to get data from yaml file. i am getting following response
{x1=[{y1=z1}, {y2=z2}], x2=[{y1 =z1}, {y2=z2]}
Now i want to get data y1 of x1 but i am not able to do this. I am using following code for read operation
package com.mobileapp;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.yamlbeans.YamlReader;
public class ReadDataWithYaml {
public static void main(String[] args) {
try {
YamlReader reader = new YamlReader(new FileReader("C:\\Users\\5521\\Desktop\\test.yml"));
Object object = reader.read();
System.out.println(object);
Map<String, ArrayList<String>> map = (Map<String, ArrayList<String>>) object;
System.out.println(map.get("x1"));
} catch (Exception exception) {
exception.printStackTrace();
}
}
}

Yaml yaml1 = new Yaml();
InputStream inputStream1 = Main.class.getClassLoader().getResourceAsStream("YourYaml.yaml");
Map< String, Object> result = (Map< String, Object>) yaml1.load(inputStream1);
for (Object name : result.keySet()) {
System.out.println(result.get(name).toString());
}
String x= result.get("userInput").toString();
System .out.println(""+x);

Related

Storing values from a Hash Map into a Text File

I have created a class that allows the user to create and store compounds into a Hash Map and now I want to create another class that allows me to take the values stored in that Hash Map and save them into a text file. I'm not sure if this is needed, but here is the code for the first class that I created containing the Hash Map:
package abi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class ChemicalComp {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> data = new HashMap<String, String>();
while(true){
String readinput=br.readLine();
if(readinput.equals(""))
break;
String input = readinput.replaceAll("\"", "");
String array[]=input.split(", ");
String compound=array[0];
String formula="";
for(int i=1;i<array.length;i++){
if(!array[i].equals("1")){
formula+=array[i];
}
}
data.put(compound, formula);
}
if(!data.isEmpty()) {
#SuppressWarnings("rawtypes")
Iterator it = data.entrySet().iterator();
while(it.hasNext()) {
#SuppressWarnings("rawtypes")
Map.Entry obj = (Entry) it.next();
System.out.println(obj.getKey()+":"+obj.getValue());
}
}
}
}
I'm not too familiar with text files, but I have done some research and this is what I've gotten so far. I know its pretty basic and that I will probably need some type of getter method, but I'm not sure where to incorporate it into what I have. Here is what I have for the class containing the text file:
package abi;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class CompoundManager {
private String path;
private boolean append_to_file = false;
public CompoundManager(String file_path) {
path = file_path;
}
public CompoundManager(String file_path, boolean append_value){
path = file_path;
append_to_file = append_value;
}
public void WriteToFile (String textLine) throws IOException{
FileWriter Compounds = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter (Compounds);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
I can't understand what your program does but you can use a buffered writer for it.
Just create a try-catch block and wrap a filewriter in a bufferedwriter like this :
try (BufferedWriter br = new BufferedWriter(new FileWriter(new File("filename.txt"))))
{
for (Map.Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
br.write(key + ": " + value);
br.newLine();
}
} catch (Exception e) {
printStackTrace();
}

Convert url encoded data to json

I expected to get JSON data from a webhook.
I get this form of data below and the content/type was application/x-www-form-urlencoded instead of application/json
results%5B6%5D%5Bid%5D=7&results%5B18%5D%5Bid%5D=19&results%5B0%5D%5Bname%5D=data+autre&results%5B1%5D%5Bname%5D=data2+autre&assessments%5B0%5D%5Bstatus%5D=finish&results%5B10%5D%5Bscore%5D=6&results%5B7%5D%5Bname%5D=data3&results%5B6%5D%5Bname%5D=Accept&results%5B8%5D%5Bname%5D=data4&results%5B2%5D%5Bname%5D=autres&results%5B3%5D%5Bname%5D=data6&results%5B4%5D%5Bname%5D=autre&results%5B5%5D%5Bname%5D=autres3&results%5B9%5D%5Bname%5D=data8&results%5B17%5D%5Bid%5D=18&reports%5B4%5D%5Bid%5D=8&reports%5B4%5D%5Bis_available%5D=0&results%5B7%5D%5Bscore%5D=7&results%5B17%5D%5Bscore%5D=4&reports%5B1%5D%5Bis_available%5D=1&assessments%5B2%5D%5Blink%5D=https%3A%2F%2Ftest%3D123&lastname=aaa&results%5B3%5D%5Bscore%5D=10&reports%5B3%5D%5Bid%5D=15&results%5B16%5D%5Bid%5D=17&register_link=&results%5B7%5D%5Bid%5D=8&results%5B19%5D%5Bid%5D=20&results%5B13%5D%5Bscore%5D=5&assessments%5B1%5D%5Bstatus%5D=todo&results%5B4%5D%5Bid%5D=5&status=accepted&results%5B9%5D%5Bid%5D=10&results%5B15%5D%5Bid%5D=16&results%5B3%5D%5Bid%5D=4&reports%5B4%5D%5Bname%5D=data9&reports%5B3%5D%5Bname%5D=data10&results%5B18%5D%5Bscore%5D=1&email=test#test.com&results%5B9%5D%5Bscore%5D=6&synthesis=
How can I convert this to json ?
Thanks
if you are looking to convert this in java, may be you can try the following code:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class URLEncodeDecode {
public static void main(String[] args) {
String url2 = "results%5B6%5D%5Bid%5D=7&results%5B18%5D%5Bid%5D=19";
String decodeURL = decode(url2);
System.out.println("Decoded URL: " + decodeURL);
System.out.println(Stream.of(decodeURL.split("&")).map(elem -> new String(elem)).collect(Collectors.toList()));
List<String> uriToList = Stream.of(decodeURL.split("&")).map(elem -> new String(elem))
.collect(Collectors.toList());
Map<String, String> uriToListToMap = new HashMap<>();
for (String individualElement : uriToList) {
uriToListToMap.put(individualElement.split("=")[0], individualElement.split("=")[1]);
}
// Use this builder to construct a Gson instance when you need to set
// configuration options other than the default.
GsonBuilder gsonMapBuilder = new GsonBuilder();
Gson gsonObject = gsonMapBuilder.create();
String uriToJSON = gsonObject.toJson(uriToListToMap);
System.out.println(uriToJSON);
}
public static String decode(String url) {
try {
String prevURL = "";
String decodeURL = url;
while (!prevURL.equals(decodeURL)) {
prevURL = decodeURL;
decodeURL = URLDecoder.decode(decodeURL, "UTF-8");
}
return decodeURL;
} catch (UnsupportedEncodingException e) {
return "Issue while decoding" + e.getMessage();
}
}
}

How to add a method to parse a JSON file in Java

I am trying to parse the content of JSON file text.json by using Jackson library.
What I want is to make a java method in the following code to get all keys and values of it, but so far in my code I get only the first key and the first value of the JSON file.
Here is my Java class:
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonStreamExample {
public static void main(String[] args) {
try {
//Create a JsonFactory instance
JsonFactory factory = new JsonFactory();
//Create a JsonParser instance to read from file c:\\text.json
JsonParser jParser = factory.createJsonParser(new File("c:\\text.json"));
/*Create an ObjectMapper instance to provide a pointer
* to root node of the tree after reading the JSON
*/
ObjectMapper mapper = new ObjectMapper(factory);
//Create tree from JSON
JsonNode rootNode = mapper.readTree(jParser);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.getFields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My Eclipse output is the following which creates only 1 pair(key-value):
Key: cells Value:[{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":-80,"y":200},"angle":0,"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24","embeds":"","z":1,"wi_name":"START","wi_displayName":"START","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"START","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":210,"y":200},"angle":0,"id":"d23133e0-e516-4f72-8127-292545d3d479","embeds":"","z":2,"wi_name":"END","wi_displayName":"END","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"END","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":-80,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed","embeds":"","z":3,"wi_name":"ACTIVITY_1","wi_displayName":"ACTIVITY 1","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Activity","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":220,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea","embeds":"","z":4,"wi_name":"ACTIVITY_2","wi_displayName":"ACTIVITY 2","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Workitem","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"link","source":{"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24"},"target":{"id":"d23133e0-e516-4f72-8127-292545d3d479"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"60ee7ff7-3a3b-487d-b581-49027e7bebe4","embeds":"","z":5,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}},{"type":"link","source":{"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed"},"target":{"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"cea0d1c2-2c18-4bd7-ba35-d94918c6fc9b","embeds":"","z":6,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}}]
How will I do it please?
In the above code sample, the nested/Hierarchical Structure is not considered of json value and it directly prints it as field.getValue().
You'll have to check for the type of value using
if(field.getValue().isObject())
{
parse(field.getValue())
}
The Parse Method could be as follows
private void parse(JsonNode jsonNode)
{
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = jsonNode.getFields();
while (fieldsIterator.hasNext())
{
Map.Entry<String, JsonNode> field = fieldsIterator.next();
if (field.getValue().isObject())
{
parse(field.getValue());
}
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
}
Then you have to just call the parse method for the rootNode.
I solved my problem by changing JSON library.
I used json-simple-1.1.1
My final code that worked is the following:
package jsontoxml;
import java.io.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;
public class JacksonStreamExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("text.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray cells = (JSONArray) jsonObject.get("cells");
Iterator<JSONObject> iterator = cells.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

static method returns empty hashmap

I have some code where there are 2 classes, A and and util class with static methods B. The class B has a static method called by A. This static method returns a hashmap (); Although the map is properly built by the static method in clas B, the map is empty when i call this method of B from A. Any thoughts?
the following is the static method from class B which correctly build the map.
package fileutils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.google.common.io.Files;
public class JarFileUtils {
//Returns the sql queries as a MAP
public static Map<String, String> getSQLs(String jarFileFullPath){
Map<String, String> sqlData = new HashMap<String, String>();
try {
JarFile jarFile = new JarFile(jarFileFullPath);
Enumeration enumeration = jarFile.entries();
while (enumeration.hasMoreElements()){
sqlData = getSqlDataHelper(enumeration.nextElement(), jarFile);
}
jarFile.close();
} catch (IOException e) {
e.printStackTrace();
}
return sqlData;
}
//Helper to fetch SQL info
private static Map<String, String> getSqlDataHelper(Object obj, JarFile jarFile)
{ Map<String, String> sqls = new HashMap<String, String>();
JarEntry entry = (JarEntry)obj;
String path = "/"+entry.getName();
if(Files.getFileExtension(path).equalsIgnoreCase("sql")){
InputStream input;
try {
input = jarFile.getInputStream(entry);
sqls.put(Files.getNameWithoutExtension(path), readSqlFile(input));
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sqls.toString());
return sqls;
}
//Reads the given SQL file
private static String readSqlFile(InputStream input) throws IOException {
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
StringBuilder sqlQuery = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sqlQuery.append(line);
sqlQuery.append("\n");
}
reader.close();
return sqlQuery.toString();
}
}
the following is where i call the above static method from class A. the size of this map is zero for some reason.
//Get the list of SQLs in the jar file
Map<String,String> sqlsExtracted = JarFileUtils.getSQLs(currentProjectFullPath);
System.out.println("size = "+currentProjectFullPath+" = "+sqlsExtracted.size());
please advise,
thanks!
Adding my comment as a possible answer, since it might point to the problem.
getSQLs() is going through each entry in the jar file, but only returns the result of the last entry. Perhaps the last entry doesn't contain any sql files?

Accessing JSON property name using java

I'm working on a way to parse JSON files and collect their contents for use elsewhere. I currently have a working example that is as follows:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testJSONParser {
public static void main(String[] args) throws Exception {
List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
try {
String line = br.readLine();
while (line != null) {
JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);
Map<String, String> currentLineMap = new HashMap<String, String>();
currentLineMap.put("country", jsonObject.get("country").toString());
currentLineMap.put("size", jsonObject.get("size").toString());
currentLineMap.put("capital", jsonObject.get("capital").toString());
jsonArray.add(currentLineMap);
line = br.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
};
}
}
}
I'm using the json simple library for parsing the passed in JSON strings.
Here's a sample string from the parsed file.
{"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"}
What my question is about is how to take this code, and have the put method be able to assign to the corresponding Map dynamically. This is what I currently have:
for (int i = 0; i < jsonObject.size(); i++) {
currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}
The ??? part is where I'm stumped. Getting the values of the current JSON line is easy enough. But how to get the property values (highlighted in bold in the JSON string sample) eludes me. Is there a method that I can call on this object that I'm not familiar with? A different and better way to itenerate through this? Or am I doing this completely assbackwards right from the get go?
In the JSON.org reference implementation, you could do:
for (String key : JSONObject.getNames(jsonObject))
{
map.put(key, jsonObject.get(key));
}
In JSON simple, you would do:
for (Object keyObject : jsonObject.keySet())
{
String key = (String)keyObject;
map.put(key, (String)jsonObject.get(key));
}
This should do the trick.

Categories