All Downloads are FREE. Search and download functionalities are using the official Maven repository.

StorageHelper.Converter Maven / Gradle / Ivy

There is a newer version: 1.14
Show newest version
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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 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 static final String nsReplacer = "NSDataSeperator";
    public static final String attributesId = "_Attributes";

    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) throws DocumentException {
        xml = cleanXml(xml);
        String xmlWithRoot = "" + xml + "";

        Document doc = null;
        ByteArrayInputStream stream;
        try {
            SAXReader reader = new SAXReader();
            stream = new ByteArrayInputStream(xmlWithRoot.getBytes("UTF-8"));
            doc = reader.read(stream);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return doc.getRootElement();
    }

    /**
     * take an xml string and clean out non xml data like in html has !DOCTYPE html
     * @param xmlData the full xml string
     * @return the full xml string minus the extra data
     */
    public static String cleanXml(String xmlData) {
        //clean up any stupid header data
        String cleanxml = cleanXmlHeader(xmlData);

        String regex = "<[\\w|\\/]*?(:).*?>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(cleanxml);
        while (matcher.find()) {
            String key = matcher.group();
            String changedKey = key.replace(":", nsReplacer);
            cleanxml = cleanxml.replace(key, changedKey);
        }
        return cleanxml;
    }

    /**
     * clean the header data out of an xml string
     * @param xmlData the xml string
     * @return xmlData with now header info on top
     */
    public static String cleanXmlHeader(String xmlData) {
        String htmlRegexReplace = "<[\\?|!].+?>";
        return xmlData.replaceAll(htmlRegexReplace, "");
    }

    /**
     * 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();

            //handle if there are attributes
            String attributes = "";
            if (json.has(key + attributesId)) {
                StringBuilder attributeString = new StringBuilder();
                JSONObject attrs = json.getJSONObject(key + attributesId);
                Iterator attKeys = attrs.keys();

                //add all set attributes
                while (attKeys.hasNext()) {
                    String attKey = attKeys.next();
                    attributeString.append(xmlAttributeFormatting(attKey, attrs.getString(attKey)));
                }
                attributes += attributeString.toString();
            }

            if (!key.endsWith(attributesId)) {
                String append = xmlFormatting(key, convertToXml(json.get(key)), attributes);
                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) {
            return convertToXml((JSONArray) value);
        }

        return value.toString();
    }

    private String xmlFormatting(String key, String value, String attributes) {
        String formattedKey = key.replace(" ", "_");
        return "<" + formattedKey + attributes +">" + value + "";
    }

    private String xmlAttributeFormatting(String attrKey, String attrValue) {
        return " " + attrKey + "=\"" + attrValue + "\"";
    }

    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);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy