StorageHelper.Converter Maven / Gradle / Ivy
package StorageHelper;
import DataTools.Utils;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
/**
Copyright 2016 Alianza Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Converter {
private HashMap storage;
public Converter(HashMap data) {
storage = data;
}
/**
* take the string and make an xml node
* @param xml string in xml format
* @return xml Node object, org.w3c.dom.Node
*/
public static Element xmlStringToElement(String xml) {
String xmlWithRoot = "" + xml + " ";
Document doc = null;
ByteArrayInputStream stream = null;
try {
SAXReader reader = new SAXReader();
stream = new ByteArrayInputStream(xmlWithRoot.getBytes("UTF-8"));
doc = reader.read(stream);
} catch (UnsupportedEncodingException | DocumentException e) {
e.printStackTrace();
}
return doc.getRootElement();
}
/**
* use the Hashmap in the class and convert the data to be a jsonObject
* @return same data as the storage hashmap but in json Object format
*/
public JSONObject convertToJson() {
//gson setup
Gson converter = new Gson();
Type hashmapType = new TypeToken>() {}.getType();
try {
String jsonConverted = converter.toJson(storage, hashmapType);
JSONObject scrubbed = (JSONObject)scrubJson(jsonConverted);
return scrubbed;
} catch (JSONException e) {
Utils.debug("unable to convert to json", "error");
e.printStackTrace();
}
return new JSONObject();
}
/**
* use the Hashmap in the class and convert the data to be a jsonArray
* @return same data as the storage hashmap but in json Array format
*/
public JSONArray convertToJsonArray() {
Gson converter = new Gson();
Type hashmapType = new TypeToken>() {}.getType();
JSONArray json = new JSONArray();
for(int i = 0; storage.containsKey(String.valueOf(i)); ++i) {
try {
Object result = storage.get(String.valueOf(i));
if (result.getClass().getTypeName().contains("HashMap") || result.getClass().getTypeName().contains("LinkedTreeMap"))
json.put(i, new JSONObject(converter.toJson(result, hashmapType)));
else
json.put(i, result);
} catch (JSONException e) {
e.printStackTrace();
}
}
return json;
}
/**
* using the storage hashmap, converts the data to an xml string
* @return string formatted as xml
*/
public String convertToXml() {
String xml = null;
try {
xml = convertToXml(convertToJson());
} catch (JSONException e) {
e.printStackTrace();
}
return xml;
}
private String convertToXml(JSONObject json) throws JSONException {
StringBuilder xmlString = new StringBuilder();
Iterator keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String append = xmlFormatting(key, convertToXml(json.get(key)));
xmlString.append(append);
}
return xmlString.toString();
}
private String convertToXml(JSONArray json) throws JSONException {
StringBuilder xmlString = new StringBuilder();
for (int i = 0; i < json.length(); ++i) {
String append = xmlFormatting(convertToXml(json.get(i)));
xmlString.append(append);
}
return xmlString.toString();
}
private String convertToXml(Object value) throws JSONException {
if (value instanceof JSONObject)
return convertToXml((JSONObject) value);
else if (value instanceof JSONArray) {
//setArray
return convertToXml((JSONArray) value);
}
return value.toString();
}
private String xmlFormatting(String key, String value) {
String formattedKey = key.replace(" ", "_");
return "<" + formattedKey + ">" + value + "" + formattedKey + ">";
}
private String xmlFormatting(String value) {
return "- " + value + "
";
}
/**
* before the json is returned needs to be cleaned up,
* @param jsonString string that is formatted as json
* @return JSONObject that has the junk removed
* @throws JSONException
*/
private Object scrubJson(String jsonString) throws JSONException {
String[] removeKeys = {"myMap", "myArrayList", "map", "storage"};
String pendingRemove = "";
//if null just return an empty JSON
if (jsonString.equals("null"))
return new JSONObject();
JSONObject converted = new JSONObject(jsonString);
// Object reference = converted;
//recursively search the whole object for these things and get them out
Iterator keys = converted.keys();
//get the keys for the json object
while (keys.hasNext()) {
String key = keys.next();
//see if the value is a json type
if (converted.get(key).getClass().getTypeName().contains("JSON")) {
//track if anything is replaced
for (String remove : removeKeys) {
//see if anything we want removed is in that json
if (converted.get(key).getClass().getTypeName().contains("JSONObject") && (converted.getJSONObject(key)).has(remove)) {
//found something that needs to be removed, move it up a layer by overwriting
converted.put(key, converted.getJSONObject(key).get(remove));
}
//the key is what we want to remove
else if (converted.get(key).getClass().getTypeName().contains("JSON") && key.equals(remove)) {
//found something that needs to be removed, move it up a layer by overwriting
pendingRemove = key;
}
}
//handle both objects and arrays
//nothing replaced iterate down to see if there is anything else in there
//because of special case of when remove is the key, the key might not be there
if (converted.has(key) && converted.get(key).getClass().getTypeName().contains("JSONArray"))
for (int i = 0; i < (converted.getJSONArray(key)).length(); ++i) {
Object item = (converted.getJSONArray(key)).get(i);
//not every item in the array, only if they are json objects
if (item.getClass().getTypeName().contains("JSONObject"))
converted.getJSONArray(key).put(i, scrubJson(item.toString()));
}
else if (converted.has(key) && converted.get(key).getClass().getTypeName().contains("JSON"))
converted.put(key, scrubJson(converted.getString(key)));
}
}
//final removings
return pendingRemove.isEmpty() ? converted : converted.get(pendingRemove);
}
}