com.surveypanel.form.xml.ParserHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.surveypanel.form.xml.ParserHelper.java

Source

/*
* SurveyPanel
* Copyright (C) 2009 Serge Tan Panza
* All rights reserved.
* License: GNU/GPL License v3 , see LICENSE.txt
* SurveyPanel is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/
package com.surveypanel.form.xml;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class ParserHelper {

    protected static Log log = LogFactory.getLog(ParserHelper.class);

    /**
     * Return a reader to parse content
     * @param path
     * @return
     */
    protected static FormValuesHandler getReader(InputStream is) {
        FormValuesHandler formValuesHandler = new FormValuesHandler();
        XMLReader parser = null;
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
            parser = XMLReaderFactory.createXMLReader();
            parser.setContentHandler(formValuesHandler);
            parser.setErrorHandler(formValuesHandler);
            InputSource inputSource = new InputSource(inputStreamReader);
            parser.parse(inputSource);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formValuesHandler;
    }

    public static Map<String, Object> getProps(InputStream is) {
        FormValuesHandler valuesHandler = getReader(is);
        return valuesHandler.getValues();
    }

    public static String toXML(Map<String, Object> frmValues) throws Exception {
        StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><vals>");
        for (Entry<String, Object> value : frmValues.entrySet()) {
            Object textValue = value.getValue();
            if (textValue != null) {
                xml.append("<val key=\"");
                xml.append(value.getKey());
                xml.append("\"><![CDATA[");
                xml.append(textValue.toString());
                xml.append("]]></val>\n");
            }
        }
        xml.append("</vals>");
        return xml.toString();
    }

}