I'm trying to parse recursively unknown json input structure in java like the format below and trying to rewrite the same structure in another json.
Meanwhile I need to validate each & every json key/values while parsing.
{"Verbs":[{
"aaaa":"30d", "type":"ed", "rel":1.0, "id":"80", "spoken":"en", "ct":"on", "sps":null
},{
"aaaa":"31", "type":"cc", "rel":3.0, "id":"10", "spoken":"en", "ct":"off", "sps":null
},{
"aaaa":"81", "type":"nn", "rel":3.0, "id":"60", "spoken":"en", "ct":"on", "sps":null
}]}
Please advice which json parser I can use for reading and writing unknown json content.
This way you can recursively parse JSON object:
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
public class JsonQuestion {
public static void main(String[] args) {
String input = "{\"Verbs\":[{\n" +
" \"aaaa\":\"30d\", \"type\":\"ed\", \"rel\":1.0, \"id\":\"80\", \"spoken\":\"en\", \"ct\":\"on\", \"sps\":null\n" +
"},{\n" +
" \"aaaa\":\"31\", \"type\":\"cc\", \"rel\":3.0, \"id\":\"10\", \"spoken\":\"en\", \"ct\":\"off\", \"sps\":null\n" +
"},{\n" +
" \"aaaa\":\"81\", \"type\":\"nn\", \"rel\":3.0, \"id\":\"60\", \"spoken\":\"en\", \"ct\":\"on\", \"sps\":null\n" +
"}]}";
JsonObject jsonObject = JsonObject.readFrom(input);
handleObject(jsonObject);
}
private static void handleValue(JsonObject.Member member, JsonValue value) {
if (value.isArray()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println("array value ");
recurseArray(value.asArray());
} else if (value.isBoolean()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", boolean value = " + value.asBoolean());
} else if (value.isNull()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", null value");
} else if (value.isNumber()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", number value = " + value.asDouble());
} else if (value.isObject()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", object value ");
handleObject(value.asObject());
} else if (value.isString()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", string value = " + value.asString());
}
}
private static void handleObject(JsonObject object) {
for (JsonObject.Member next : object) {
JsonValue value = next.getValue();
handleValue(next, value);
}
}
private static void recurseArray(JsonArray array) {
for (JsonValue value : array) {
handleValue(null, value);
}
}
}
Using gson library
https://sites.google.com/site/gson/gson-user-guide
public void parseJson() {
String jsonStr = "";//input json String.
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(jsonStr);
processJsonElement(jsonElement);
}
private void processJsonElement(JsonElement e) {
if (e.isJsonArray()) {
processJsonArray(e.getAsJsonArray());
} else if (e.isJsonNull()) {
processJsonNull(e.getAsJsonNull());
} else if (e.isJsonObject()) {
processJsonObject(e.getAsJsonObject());
} else if (e.isJsonPrimitive()) {
processJsonPrimitive(e.getAsJsonPrimitive());
}
}
private void processJsonArray(JsonArray a) {
for (JsonElement e : a) {
processJsonElement(e);
}
}
private void processJsonNull(JsonNull n) {
System.out.println("null || : " + n);
}
private void processJsonObject(JsonObject o) {
Set<Map.Entry<String, JsonElement>> members= o.entrySet();
for (Map.Entry<String, JsonElement> e : members) {
System.out.println("Processing object member: " + e.getKey());
processJsonElement(e.getValue());
}
}
private void processJsonPrimitive(JsonPrimitive p) {
System.out.println("Primitive || :" + p);
}
Or Jackson
public void processJson() {
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode node = objectMapper.readTree(jsonStr);
System.out.println(node);
processNode(node);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void processNode(JsonNode n) {
if (n.isContainerNode()) {
processJsonContainer(n.iterator());
} else if (n.isNull()) {
System.out.println("Null || :" + n);
} else if (n.isNumber()) {
System.out.println("Number || :" + n.asDouble());
} else if (n.isBoolean()) {
System.out.println("Boolean || :" + n.asBoolean());
} else if (n.isTextual()) {
System.out.println("Text || :" + n.asText());
}
}
private void processJsonContainer(Iterator<JsonNode> iterator) {
while (iterator.hasNext()) {
processNode(iterator.next());
}
}
Related
I am not too familiar with polymorphism, and was wondering if I have it used in my code?
If this doesn't contain a polymorphic reference, could you lead me in a direction of where I would need to go? The files that the program is using are not included, as I am mainly curious about whether or not any polymorphic references are used.
java file 1 - this file runs the program
import java.util.Scanner;
public class ADTDemo {
ADTDictionary dictionary;
public static void menu() {
System.out.println("Welcome the Faculty Directory Program");
System.out.println(" Use commands:");
System.out.println(" list all");
System.out.println(" list DEPT_NAME");
System.out.println(" add DEPT_NAME, FIRST LAST");
System.out.println(" remove DEPT_NAME, FIRST LAST");
System.out.println(" exit");
}
public static void main(String[] args) {
menu();
String command;
ADTDemo dictObj = new ADTDemo();
dictObj.dictionary = new ADTDictionary();
dictObj.dictionary.read();
Scanner scanner = new Scanner(System.in);
do {
System.out.println("");
System.out.print(">>");
command = scanner.nextLine().trim();
if (!command.equals("exit")) {
dictObj.action(command);
} else {
dictObj.dictionary.saveEntries();
System.out.println("Goodbye! Have a nice day!");
}
} while (!command.equalsIgnoreCase("exit"));
}
public void action(String command) {
if (command.equalsIgnoreCase("LIST ALL")) {
dictionary.listAll();
return;
}
else if (command.toUpperCase().contains("LIST")) {
if (command.length() == 4){
System.out.println("Command needed.");
return;
}
command = command.substring(5, command.length());
dictionary.listDeptName(command);
return;
}
else if (command.toUpperCase().contains("ADD")) {
command = command.substring(4, command.length());
dictionary.add(command);
return;
}
else if (command.toUpperCase().contains("REMOVE")) {
command = command.substring(6, command.length());
dictionary.remove(command);
}
}
}
java file 2
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ADTDictionary {
Map<String, List<String>> adtDictionary;
public void read() {
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
Scanner departmentScanner = new Scanner(departmentFile);
Scanner facultyScanner = new Scanner(facultyFile);
adtDictionary = new HashMap<String, List<String>>();
while (departmentScanner.hasNextLine()) {
String department = departmentScanner.nextLine().trim();
adtDictionary.put(department, new ArrayList<String>());
}
while (facultyScanner.hasNextLine()) {
String faculty = facultyScanner.nextLine();
String[] values = faculty.split(",");
adtDictionary.get(values[1].trim()).add(values[0]);
}
} catch (FileNotFoundException ex) {
System.out.println("ERROR: File not found.");
}
}
public void listAll() {
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
System.out.println(value + ", " + key);
}
}
}
public void listDeptName(String department) {
if (null != adtDictionary.get(department)) {
for (String name : adtDictionary.get(department)) {
System.out.println(name);
}
}
else{
System.out.println("Unknown entry made.");
}
}
public void add(String value) {
if(!value.contains(",")){
System.out.println("Incorrect entry.");
return;
}
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
String[] facName = faculty.split(" ");
if (!(facName.length == 2)){
System.out.println("Please only enter First and Last name of faculty member.");
return;
}
if (!(null != adtDictionary.get(dept))) {
if(adtDictionary.containsKey(dept.toUpperCase())){
System.out.println("Incorrect departtment entry.");
return;
}
else if (dept == dept.toUpperCase()){
adtDictionary.put(dept, new ArrayList<String>());
}
else{
System.out.println("Incorrect department entry.");
return;
}
}
for (String name : adtDictionary.get(dept)) {
if (name.equalsIgnoreCase(faculty)) {
System.out.println("Cannot add " + name + " to " + dept + " because they already exist there.");
return;
}
}
adtDictionary.get(dept).add(faculty);
System.out.println("OK, added " + faculty);
}
public void remove(String value) {
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
adtDictionary.get(dept).remove(faculty);
System.out.println("OK, removed " + faculty + " from " + dept);
}
public void saveEntries(){
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
PrintWriter facWriter = new PrintWriter(facultyFile);
PrintWriter deptWriter = new PrintWriter(departmentFile);
for (Object s : adtDictionary.keySet()) {
deptWriter.println(s);
}
deptWriter.close();
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
facWriter.println(value + ", " + key);
}
}
facWriter.close();
}
catch (IOException ex){
System.out.println("ERROR saving file.");
}
}
}
I want to use java to find node by id and return that node, but now I'm only able to print out that node the return value is null. What's the reason and how to do it?
This is the json:
{
id: '1',
label: 'first',
children: [
{
id: '2',
label: 'second'
}
]
}
This is the code I'm using now. The traverse json method using JSONObject is mostly taken from https://www.baeldung.com/jsonobject-iteration
package cn.velosoft.demo1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class GetTreeNode {
public static void main(String[] args) {
String json1 = "{\r\n" +
" id: '1',\r\n" +
" label: 'first',\r\n" +
" children: [\r\n" +
" {\r\n" +
" id: '2',\r\n" +
" label: 'second'\r\n" +
" }\r\n" +
" ]\r\n" +
"}";
JSONObject jObject1 = new JSONObject(json1);
String id = "2";
JSONObject returnNode = findNodeById(jObject1, id);
// I want the node to return to here
System.out.println(returnNode);
}
private static JSONObject findNodeById(JSONObject jObject1, String id) {
Iterator iterator = jObject1.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if (key.equals("id")) {
String value = jObject1.getString(key);
if (((String) value).equals(id)) {
JSONObject returnNode = new JSONObject(jObject1.toString());
System.out.println(returnNode);
return returnNode; //return value here doesn't work ...
}
} else {
Object value = jObject1.get(key);
handleValue(value, id);
}
}
return null;
}
private static void handleValue(Object value, String id) {
if (value instanceof JSONObject) {
findNodeById((JSONObject) value, id);
} else if (value instanceof JSONArray) {
handleJSONArray((JSONArray) value, id);
} else {
}
}
private static void handleJSONArray(JSONArray jsonArray, String id) {
jsonArray.iterator().forEachRemaining(element -> {
handleValue(element, id);
});
}
}
The output is:
{"id":"2","label":"second"}
null
The first {"id":"2","label":"second"} is the System.out.println() in the middle, the second null is the print in the main function. Why it is null? How to do it?
As #LHCHIN commented why are you not returning the JSONObject object from your method findNodeById() . When you find the key that match , the value must be returned . In your code you are always returning null.
private static JSONObject findNodeById(JSONObject jObject1, String id) {
Iterator iterator = jObject1.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if (key.equals("id")) {
String value = jObject1.getString(key);
if (((String) value).equals(id)) {
JSONObject returnNode = new JSONObject(jObject1.toString());
System.out.println(returnNode);
return returnNode //return value here
}
} else {
Object value = jObject1.get(key);
handleValue(value, id);
}
}
return null;
}
I am trying to use openstreetmap osmosis to read a pbf file of an airport and extract features like gates and runways.
I am using code similar to: http://www.javaoptimum.com/how-to-read-osm-pbf-files-programmatically-java/
When the code encounters a Node instance, it returns reasonable values from getLatitude and getLongitude...
However when the code encounters a Way instance the coordinates appear to be zero. Here is the code that I am using:
Sink sinkImplementation = new Sink() {
public void process(EntityContainer entityContainer) {
Entity entity = entityContainer.getEntity();
entity.getTags().forEach((tag) -> {
if ("aeroway".equals(tag.getKey())) {
if (entity instanceof Node) {
if ("holding_position".equals(tag.getValue())) {
installPointHook(airportIcaoCode, entity, tag);
} else if ("gate".equals(tag.getValue())) {
installPointHook(airportIcaoCode, entity, tag);
} else {
LOGGER.info("Ignoring unrecognized tag value " + tag.getValue());
}
} else if (entity instanceof Way) {
Way way = (Way)entity;
if ("runway".equals(tag.getValue())) {
way.getWayNodes().forEach((it) -> System.out.println(it + " : " + it.getLatitude()+","+it.getLongitude()));
} else if ("taxiway".equals(tag.getValue())) {
way.getWayNodes().forEach((it) -> System.out.println(it + " : " + it.getLatitude()+","+it.getLongitude()));
} else if ("apron".equals(tag.getValue())) {
way.getWayNodes().forEach((it) -> System.out.println(it + " : " + it.getLatitude()+","+it.getLongitude()));
} else if ("hangar".equals(tag.getValue())) {
way.getWayNodes().forEach((it) -> System.out.println(it + " : " + it.getLatitude()+","+it.getLongitude()));
} else {
LOGGER.info("Ignoring unrecognized tag value " + tag.getValue());
}
} else if (entity instanceof Relation) {
LOGGER.info("Ignoring unrecognized tag value " + tag.getValue());
}
}
});
}
public void initialize(Map<String, Object> arg0) {
}
public void complete() {
}
#Override
public void close() {
}
};
Is there some other processing I need to do in order to get the coordinates for Ways?
Turns out that ways don't have coordinates themselves, instead they have lists of WayNodes that have coordinates:
public void process(EntityContainer entityContainer) {
Entity entity = entityContainer.getEntity();
entity.getTags().forEach((tag) -> {
if (tag.getKey().equals("aeroway") && tag.getValue().equals("runway")
&& entity instanceof Way) {
final List<WayNode> wayNodes = ((Way) entity).getWayNodes();
Runway runway = new Runway(entity.getId(), nodes.get(wayNodes.get(0).getNodeId()),
nodes.get(wayNodes.get(wayNodes.size() - 1).getNodeId()));
runways.add(runway);
}
});
}
You could enhance the WayNodes with coordinates using the following snippets:
private static class MySink implements Sink {
public void process(EntityContainer entityContainer) {
if (entityContainer.getEntity() instanceof Node) {
Node node = (Node) entityContainer.getEntity();
nodes.put(node.getId(), node);
}
...
}
...
}
for (int i = 0; i < way.getWayNodes().size(); i++) {
WayNode wayNode = way.getWayNodes().get(i);
Node node = sink.nodes.get(wayNode.getNodeId());
way.getWayNodes().set(i, new WayNode(wayNode.getNodeId(), node.getLatitude(), node.getLongitude()));
}
I am trying to build a post URL for Volley custom request to post some data to server using post method with normal param and array param. But I get some exception when build the post url for request. I am getting exception before make a request with volley custom request.
Map<String, String> params = new HashMap<>();
params.put(API.Parameter.ANDROID_DEVICE_ID, appManager.getDeviceId());
params.put(API.Parameter.ANDROID_APP_VERSION, appManager.getAppVersion());
params.put("trip_no", MainActivity.temp_trip_id);
Map<String, List<String>> arrayParams = new HashMap<>();
arrayParams.put("ticket_id",ticket_id);
arrayParams.put("ticket_name",ticket_name);
arrayParams.put("ticket_price_each",ticket_price_each);
PostUrlBuilder urlBuilder = new PostUrlBuilder(API.BOOK_TRIP_API_URL, params, arrayParams);
String Url = urlBuilder.getQueryUrl();
ObjectRequest<OnlineUserData> onlineUserDataObjectRequest = new ObjectRequest<OnlineUserData>(Request.Method.POST, Url, null,
new Response.Listener<OnlineUserData>() {
#Override
public void onResponse(OnlineUserData response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}, OnlineUserData.class);
AppController.getInstance().addToRequestQueue(onlineUserDataObjectRequest);
My PostUrlBuilder.java class is:
public class PostUrlBuilder {
private static final String TAG = PostUrlBuilder.class.getSimpleName();
private String url;
private Map<String, String> parameters;
private Map<String, List<String>> arrayParameters;
private String queryUrl;
public PostUrlBuilder() {
}
public PostUrlBuilder(String url, Map<String, String> parameters, Map<String, List<String>> arrayParameters) {
this.url = url;
this.parameters = parameters;
this.arrayParameters = arrayParameters;
buildQueryUrl();
}
public PostUrlBuilder(Map<String, String> parameters, String url) {
this.parameters = parameters;
this.url = url;
}
private void buildQueryUrl() {
StringBuilder urlBuilder = new StringBuilder(url);
if (parameters != null && parameters.size() != 0) {
urlBuilder.append("?");
int i = 0;
for (String key : parameters.keySet()) {
String value = parameters.get(key);
Log.d(TAG, "key= " + key + " & " + "value=" + value);
try {
urlBuilder.append(String.format("%s=%s", key, URLEncoder.encode(value, "UTf-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
if (i != parameters.size()) {
urlBuilder.append("&");
}
}
}
if (arrayParameters != null && arrayParameters.size() != 0) {
if (parameters != null && parameters.size() != 0) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
}
int i = 0;
for (String key : arrayParameters.keySet()) {
List<String> values = arrayParameters.get(key);
int j = 0;
for (String value : values) {
Log.d(TAG, "size = " + values.size() + " j = " + j + " key= " + key + " & " + "value=" + value);
try {
urlBuilder.append(String.format("%s[]=%s", key, URLEncoder.encode(value, "UTf-8")));
j++;
if (j != values.size()) {
urlBuilder.append("&");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
i++;
if (i != arrayParameters.size()) {
urlBuilder.append("&");
}
}
}
queryUrl = urlBuilder.toString();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public String getQueryUrl() {
return queryUrl;
}
public void setQueryUrl(String queryUrl) {
this.queryUrl = queryUrl;
}
public Map<String, List<String>> getArrayParameters() {
return arrayParameters;
}
public void setArrayParameters(Map<String, List<String>> arrayParameters) {
this.arrayParameters = arrayParameters;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PostUrlBuilder)) return false;
PostUrlBuilder that = (PostUrlBuilder) o;
return this.getUrl().equals(that.getUrl())
&& this.getParameters().equals(that.getParameters())
&& this.getArrayParameters().equals(that.getArrayParameters())
&& this.getQueryUrl().equals(that.getQueryUrl());
}
#Override
public int hashCode() {
int result = getUrl().hashCode();
result = 31 * result + getParameters().hashCode();
result = 31 * result + getArrayParameters().hashCode();
result = 31 * result + getQueryUrl().hashCode();
return result;
}
#Override
public String toString() {
return "GetUrlBuilder{" +
"url='" + url + '\'' +
", parameters=" + parameters +
", queryUrl='" + queryUrl + '\'' +
'}';
}
}
I am getting exception in line below:
urlBuilder.append(String.format("%s[]=%s", key, URLEncoder.encode(value, "UTf-8")));
Error Log-cat shows errors below :
FATAL EXCEPTION: main
Process: com.shohoz.launch.cabin, PID: 12230
java.lang.NullPointerException
at libcore.net.UriCodec.encode(UriCodec.java:132)
at java.net.URLEncoder.encode(URLEncoder.java:57)
at com.shohoz.launch.cabin.toolbox.PostUrlBuilder.buildQueryUrl(PostUrlBuilder.java:70)
at com.shohoz.launch.cabin.toolbox.PostUrlBuilder.<init>(PostUrlBuilder.java:29)
at com.shohoz.launch.cabin.fragment.RightFullSeatLayoutFragment.onlineCreateAndInsertIntoConfirm(RightFullSeatLayoutFragment.java:1105)
at com.shohoz.launch.cabin.fragment.RightFullSeatLayoutFragment$15.onClick(RightFullSeatLayoutFragment.java:857)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5398)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:680)
at dalvik.system.NativeStart.main(Native Method)
Thanks in advance.
I've Figured out arrayParams.put("ticket_price_each",ticket_price_each); sending null value. That's why app was crashed.
I have a multiple-multi-dimensional HashMap() instances, I am using them to store hierarchical data from a database;
HashMap<String, HashMap<String, ArrayList<String>>>
I add to them with 3 primary methods that we'll refer to as addTop(), addMid() and addLow(). The methods all accept parameters that match their data group and a string, each method returns the next dimension of the HashMap();
public static HashMap<String, ArrayList<String>> addTop(HashMap<String, HashMap<String, ArrayList<String>>> data, String val) { ... };
public static ArrayList<String> addMid(HashMap<String, ArrayList<String>> data, String val) { ... };
public static String addLow(ArrayList<String> data, String val) { ... };
I call these, usually, in sequence in between a few checks and perform additional checks inside the methods. Essentially all these methods do is add val to data then return an empty HashMap();
out = new HashMap();
data.put(val, out);
return out;
When I check at the end of the loop/data-population all of the data from addMid() & addLow() is missing. Why is this?
I thought Java worked by reference when dealing with complex objects, such as HashMap().
What can I do to ensure that addMid() and addLow() update the master HashMap()?
EDIT: Included code. It compiles and runs but there are other problems, I have stripped out as much as I can to demonstrate whats happening, except the SQL stuff, that won't compile, sorry. the method that is run at start is sqlToArray();
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
public class Av2 {
protected class AvailLookup {
private Integer key;
private String value;
public AvailLookup(Integer inKey, String inValue) {
key = inKey;
value = inValue;
}
public void updateName(String name) {
value = name;
}
public Integer getKey() {
return key;
}
public String getValue() {
return value;
}
public String toString() {
return value;
}
}
private static HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> data = new HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>>();
private static Sql sql = new Sql("PlantAvail");
public static HashMap<AvailLookup, ArrayList<AvailLookup>> getChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer channel) {
HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
if (inArray != null ) {
for (AvailLookup lookup : inArray.keySet()) {
if (lookup.getKey() == channel) {
out = inArray.get(lookup);
System.out.println("Channel: " + channel + " found");
break;
}
}
if (out == null) {
System.out.println("Channel: " + channel + " not found");
}
}
return out;
}
public static HashMap<AvailLookup, ArrayList<AvailLookup>> getChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, String channel) {
HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
if (inArray != null ) {
for (AvailLookup lookup : inArray.keySet()) {
if (lookup.getValue() != null) {
if (lookup.getValue().equalsIgnoreCase(channel)) {
out = inArray.get(lookup);
System.out.println("Channel: " + channel + " found");
break;
}
}
}
if (out == null) {
System.out.println("Channel: " + channel + " not found");
}
}
return out;
}
public static HashMap<AvailLookup, ArrayList<AvailLookup>> addChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer id, String name) {
HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
if (inArray != null ) {
if (getChannel(inArray, id) == null) {
out = new HashMap<AvailLookup, ArrayList<AvailLookup>>();
inArray.put(new AvailLookup(id, name), new HashMap<AvailLookup, ArrayList<AvailLookup>>());
System.out.println("Channel: added " + id);
} else {
System.out.println("Channel: " + id + " already exists");
}
} else {
System.out.println("Channel: " + id + " already exists");
}
return out;
}
public static void removeChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer channel) {
boolean pass = false;
HashMap<AvailLookup, ArrayList<AvailLookup>> channelLookup = getChannel(inArray, channel);
for (AvailLookup lookup : channelLookup.keySet()) {
if (lookup.getKey() == channel) {
inArray.remove(channel);
System.out.println("Channel: " + channel + " removed");
pass = true;
break;
}
}
if (!pass) {
System.out.println("Channel: " + channel + " cannot be removed");
}
}
public static ArrayList<AvailLookup> getDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer device) {
ArrayList<AvailLookup> out = null;
for(AvailLookup lookup : channel.keySet()) {
if (lookup.getKey() == device) {
out = channel.get(device);
System.out.println("Device: " + device + " found");
break;
}
}
if (out == null) {
System.out.println("Device: " + device + " not found");
}
return out;
}
public static ArrayList<AvailLookup> getDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, String device) {
ArrayList<AvailLookup> out = null;
for(AvailLookup lookup : channel.keySet()) {
if (lookup.getValue() == device) {
out = channel.get(device);
System.out.println("Device: " + device + " found");
break;
}
}
if (out == null) {
System.out.println("Device: " + device + " not found");
}
return out;
}
public static ArrayList<AvailLookup> addDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer id, String value) {
ArrayList<AvailLookup> out = null;
if (getDevice(channel, id) == null) {
out = new ArrayList<AvailLookup>();
channel.put(new AvailLookup(id, value), new ArrayList<AvailLookup>());
System.out.println("Device: added " + id);
} else {
System.out.println("Device: " + id + " already exists");
}
return out;
}
public static void removeDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer device) {
boolean pass = false;
ArrayList<AvailLookup> deviceLookup = getDevice(channel,device);
for (AvailLookup lookup : deviceLookup) {
if (lookup.getKey() == device) {
channel.remove(device);
System.out.println("Device: " + device + " removed");
pass = true;
break;
}
}
if (!pass) {
System.out.println("Device: " + device + " cannot be removed");
}
}
public static AvailLookup getHost(ArrayList<AvailLookup> hosts, Integer host) {
AvailLookup out = null;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getKey() == host) {
out = hostLookup;
System.out.println("Host: " + host + " found");
}
}
if (hosts.contains(host)) {
} else {
System.out.println("Host: " + host + " not found");
}
return out;
}
public static AvailLookup getHost(ArrayList<AvailLookup> hosts, String host) {
AvailLookup out = null;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getValue() == host) {
out = hostLookup;
System.out.println("Host: " + host + " found");
}
}
if (hosts.contains(host)) {
} else {
System.out.println("Host: " + host + " not found");
}
return out;
}
public static AvailLookup addHost(ArrayList<AvailLookup> hosts, Integer id, String value) {
AvailLookup out = null;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getKey() == id) {
out = hosts.set(id, new AvailLookup(id, value));
System.out.println("Host: " + id + " found");
break;
}
}
if (out == null) {
System.out.println("Host: " + id + " not found");
}
return out;
}
public static void removeHost(ArrayList<AvailLookup> hosts, Integer host) {
boolean pass = false;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getKey() == host) {
hosts.remove(hostLookup);
System.out.println("Host: " + host + " removed");
pass = true;
}
}
if (!pass) {
System.out.println("Host: " + host + " cannot be removed");
}
}
public static ArrayList<AvailLookup> otherHosts(ArrayList<AvailLookup> hosts, Integer key, String value) {
ArrayList<AvailLookup> out = null;
for (AvailLookup host : hosts) {
if (host.getKey() != key) {
if (out == null) {
out = new ArrayList<AvailLookup>();
}
out.add(new AvailLookup(key, value));
}
}
if (out != null) {
if (out.size() > 1) {
System.out.println("Host: generated other hosts");
}
}
return out;
}
public static AvailLookup nextHost(ArrayList<AvailLookup> otherHosts) {
AvailLookup out = null;
if (otherHosts != null) {
out = otherHosts.get(0);
System.out.println("Host: getting next host");
} else {
System.out.println("Host: no other host");
}
return out;
}
public static void sqlToArray() {
HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> tempData = new HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>>();
Integer iHost = null;
Integer iDevice = null;
Integer iChannel = null;
String sHost = null;
String sDevice = null;
String sChannel = null;
HashMap<AvailLookup, ArrayList<AvailLookup>> channel = null;
ArrayList<AvailLookup> device = null;
Sql obj = new Sql("plantavail");
obj.query("select j_channel.id as channelid, j_channel.name as channelname, j_device.id as deviceid, j_device.name as devicename, j_io.id as hostid, j_io.host as hostname, alias"
+ " from j_io"
+ " left join j_channel on j_io.id = j_channel.iofk"
+ " left join j_device on j_channel.iofk = j_device.id");
try {
while(obj.getResult().next()) {
sChannel = obj.getResult().getString("channelname");
sDevice = obj.getResult().getString("devicename");
sHost = obj.getResult().getString("hostname");
iChannel = obj.getResult().getInt("channelid");
iDevice = obj.getResult().getInt("deviceid");
iHost = obj.getResult().getInt("hostid");
channel = addChannel(tempData, iChannel, sChannel);
if (channel != null) {
device = addDevice(channel, iDevice, sDevice);
if (device != null) {
addHost(device, iHost, sHost);
}
}
}
} catch (SQLException e1) {
e1.printStackTrace();
}
data = tempData;
}
}
Be careful with accidentally overriding your existing map values. If you use java 8 you can use:
map.computeIfAbsent("entry", s -> new ArrayList<>());
Before Java 8 you need to check if the value is null:
List<String> list = map.get("entry");
if(list == null){
list = map.put("entry", new ArrayList<String>());
}
Also you need to make sure that you update your map correctly:
A little example:
Map<String, String> map = new HashMap<>();
String a = "a";
String b = "b";
map.put(a, b);
System.out.println(map.get(a));
b = "c";
System.out.println(map.get(a));
System.out.println(b);
The output is:
b
b
c
So you see if you update b the map does not get updated. Now the same thing with a map in a map:
final String a = "a";
final String b = "b";
Map<String, Map<String, String>> topMap = new HashMap<>();
Map<String, String> middleMap = topMap.getOrDefault(a, new HashMap<>());
middleMap.put(b, "c");
topMap.put("a", middleMap);
System.out.println(topMap.get(a).get(b));
middleMap.replace(b, "d");
System.out.println(topMap.get(a).get(b));
topMap.put("a", middleMap);
System.out.println(topMap.get(a).get(b));
The output is:
c
d
d
But why? Shouldn't it be 'c c d'? NO! Because a String in Java is immutable, but a Map is not. If you consider this you should be able to solve your problem.
You need to check if there is already a map for this key:
Map<...> result = data.get(val);
if(null == result) {
result = new HashMap();
data.put(val, result);
}
return out;
Without this, the second attempt to add values to the same key will overwrite the existing map instead of appending to it.