alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Glassfish example source code file (MarshallingUtils.java)

This example Glassfish source code file (MarshallingUtils.java) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Glassfish tags/keywords

arraylist, file, io, jsonarray, jsonexception, jsonobject, list, list, log, logging, map, map, object, object, runtimeexception, string, string, util

The Glassfish MarshallingUtils.java source code

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License.  You can
 * obtain a copy of the License at
 * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
 * or packager/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at packager/legal/LICENSE.txt.
 *
 * GPL Classpath Exception:
 * Oracle designates this particular file as subject to the "Classpath"
 * exception as provided by Oracle in the GPL Version 2 section of the License
 * file that accompanied this code.
 *
 * Modifications:
 * If applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyright [year] [name of copyright owner]"
 *
 * Contributor(s):
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package org.glassfish.admin.rest.clientutils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 * @author jasonlee
 */
public class MarshallingUtils {
    public static List<Map getPropertiesFromJson(String json) {
        List<Map properties = null;
        json = json.trim();
        if (json.startsWith("{")) {
            properties = new ArrayList<Map();
            properties.add(processJsonMap(json));
        } else if (json.startsWith("[")) {
            try {
                properties = processJsonArray(new JSONArray(json));
            } catch (JSONException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } else {
            throw new RuntimeException("The JSON string must start with { or ["); // i18n
        }

        return properties;
    }

    public static List<Map getPropertiesFromXml(String xml) {
        List<Map list = new ArrayList>();
        InputStream input = null;
        try {
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            inputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
            input = new ByteArrayInputStream(xml.trim().getBytes("UTF-8"));
            XMLStreamReader parser = inputFactory.createXMLStreamReader(input);
            while (parser.hasNext()) {
                int event = parser.next();
                switch (event) {
                    case XMLStreamConstants.START_ELEMENT: {
                        if ("list".equals(parser.getLocalName())) {
                            list = processXmlList(parser);
                        }
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(MarshallingUtils.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex);
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                Logger.getLogger(MarshallingUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return list;
    }

    public static String getXmlForProperties(final Map<String, String> properties) {
        return getXmlForProperties(new ArrayList<Map() {{ add(properties); }} );
    }

    public static String getXmlForProperties(List<Map properties) {
        try {
            String xml = null;
            XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
            StringWriter sw = new StringWriter();
            XMLStreamWriter writer = outputFactory.createXMLStreamWriter(sw);
            writer.writeStartDocument("UTF-8","1.0");
            writer.writeStartElement("list");
            for (Map<String, String> property : properties) {
                writer.writeStartElement("map");
                for (Map.Entry<String, String> entry : property.entrySet()) {
                writer.writeStartElement("entry");
                    writer.writeAttribute("key", entry.getKey());
                    writer.writeAttribute("value", entry.getValue());
                writer.writeEndElement();
                }
                writer.writeEndElement();
            }
            writer.writeEndElement();
            writer.writeEndDocument();
            writer.flush();
            writer.close();
            return sw.toString();
        } catch (Exception ex) {
            Logger.getLogger(MarshallingUtils.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex);
        }
    }

    public static String getJsonForProperties(final Map<String, String> properties) {
        return getJsonForProperties(new ArrayList<Map() {{ add(properties); }} );
    }
    public static String getJsonForProperties(List<Map properties) {
        JSONArray list = new JSONArray();

        for (Map<String, String> property : properties) {
            JSONObject map = new JSONObject();

            list.put(property);
        }

        return list.toString();
    }

    public static Map buildMapFromDocument(String text) {
        Map map = null;
        if (text == null) {
            return new HashMap();
        }

        text = text.trim();

        if (text.startsWith("{")) {
            map = processJsonMap(text);
        } else if (text.startsWith("<")) {
            InputStream input = null;
            try {
                XMLInputFactory inputFactory = XMLInputFactory.newInstance();
                inputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
                input = new ByteArrayInputStream(text.trim().getBytes("UTF-8"));
                XMLStreamReader parser = inputFactory.createXMLStreamReader(input);
                while (parser.hasNext()) {
                    int event = parser.next();
                    switch (event) {
                        case XMLStreamConstants.START_ELEMENT: {
                            if ("map".equals(parser.getLocalName())) {
                                map = processXmlMap(parser);
                            }
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(MarshallingUtils.class.getName()).log(Level.SEVERE, null, ex);
                throw new RuntimeException(ex);
            } finally {
                try {
                    input.close();
                } catch (IOException ex) {
                    Logger.getLogger(MarshallingUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            throw new RuntimeException ("An unknown document type was provided:  " + text.substring(0, 10));
        }

        return map;
    }

    private static Map processJsonMap(String json) {
        Map map;
        try {
            map = processJsonObject(new JSONObject(json));
        } catch (JSONException e) {
            map = new HashMap();
        }
        return map;
    }

    private static Map processJsonObject(JSONObject jo) {
        Map<String, Object> map = new HashMap();
        try {
            Iterator i = jo.keys();
            while (i.hasNext()) {
                String key = (String)i.next();
                Object value = jo.get(key);
                if (value instanceof JSONArray) {
                    map.put(key, processJsonArray((JSONArray)value));
                } else if (value instanceof JSONObject) {
                    map.put(key, processJsonObject((JSONObject)value));
                } else {
                    map.put(key, value);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return map;
    }

    private static List processJsonArray(JSONArray ja) {
        List results = new ArrayList();

        try {
            for (int i = 0; i < ja.length(); i++) {
                Object entry = ja.get(i);
                if (entry instanceof JSONArray) {
                    results.add(processJsonArray((JSONArray)entry));
                } else if (entry instanceof JSONObject) {
                    results.add(processJsonObject((JSONObject)entry));
                } else {
                    results.add(entry);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return results;
    }

    private static Map processXmlMap(XMLStreamReader parser) throws XMLStreamException {
        boolean endOfMap = false;
        Map<String, Object> entry = new HashMap();
        String key = null;
        String element = null;
        while (!endOfMap) {
            int event = parser.next();
            switch (event) {
                case XMLStreamConstants.START_ELEMENT: {
                    if ("entry".equals(parser.getLocalName())) {
                        key = parser.getAttributeValue(null, "key");
                        String value = parser.getAttributeValue(null, "value");
                        if (value != null) {
                            entry.put(key, value);
                            key = null;
                        }
                    } else if ("map".equals(parser.getLocalName())) {
                        Map value = processXmlMap(parser);
                        entry.put(key, value);
                    } else if ("list".equals(parser.getLocalName())) {
                        List value = processXmlList(parser);
                        entry.put(key, value);
                    } else {
                        element = parser.getLocalName();
                    }
                    break;
                }
                case XMLStreamConstants.END_ELEMENT: {
                    if ("map".equals(parser.getLocalName())) {
                        endOfMap = true;
                    }
                    element = null;
                    break;
                }
                default: {
                    String text=parser.getText();
                    if (element != null) {
                        if ("number".equals(element)) {
                            if (text.contains(".")) {
                                entry.put(key, Double.parseDouble(text));
                            } else {
                                entry.put(key, Long.parseLong(text));
                            }
                        } else if ("string".equals(element)) {
                            entry.put(key, text);
                        }

                        element = null;
                    }
                }
            }
        }
        return entry;
    }

    private static List processXmlList(XMLStreamReader parser) throws XMLStreamException {
        List list = new ArrayList();
        boolean endOfList = false;
        String element = null;
        while (!endOfList) {
            int event = parser.next();
            switch (event) {
                case XMLStreamConstants.START_ELEMENT: {
                    if ("map".equals(parser.getLocalName())) {
                        list.add(processXmlMap(parser));
                    } else {
                        element = parser.getLocalName();
                    }
                    break;
                }
                case XMLStreamConstants.END_ELEMENT: {
                    if ("list".equals(parser.getLocalName())) {
                        endOfList = true;
                    }
                    element = null;
                    break;
                }
                default: {
                    String text = parser.getText();
                    if (element != null) {
                        if ("number".equals(element)) {
                            if (text.contains(".")) {
                                list.add(Double.parseDouble(text));
                            } else {
                                list.add(Long.parseLong(text));
                            }
                        } else if ("string".equals(element)) {
                            list.add(text);
                        }

                        element = null;
                    }
                }
            }
        }
        return list;
    }
}

Other Glassfish examples (source code examples)

Here is a short list of links related to this Glassfish MarshallingUtils.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.