Example usage for javax.xml.parsers DocumentBuilder setErrorHandler

List of usage examples for javax.xml.parsers DocumentBuilder setErrorHandler

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setErrorHandler.

Prototype


public abstract void setErrorHandler(ErrorHandler eh);

Source Link

Document

Specify the ErrorHandler to be used by the parser.

Usage

From source file:com.kenshoo.freemarker.util.DataModelParser.java

private static Object parseValue(String value, TimeZone timeZone) throws DataModelParsingException {
    // Note: Because we fall back to interpret the input as a literal string value when it doesn't look like
    // anything else (like a number, boolean, etc.), it's important to avoid misunderstandings, and throw exception
    // in suspicious situations. The user can always quote the string value if we are "too smart". But he will
    // be confused about the rules of FreeMarker if what he believes to be a non-string is misinterpreted by this
    // parser as a string. Getting sometimes an error and then quoting the string is better than that.

    if (value.endsWith(";")) { // Tolerate this habit of Java and JavaScript programmers
        value = value.substring(value.length() - 1).trim();
    }//  ww w  .j a  v a 2 s  .  co  m

    if (NUMBER_LIKE.matcher(value).matches()) {
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException e) {
            // Maybe it's a ISO 8601 Date/time/datetime
            CalendarFieldsToDateConverter calToDateConverter = new TrivialCalendarFieldsToDateConverter();

            DateParseException attemptedTemportalPExc = null;
            String attemptedTemporalType = null;
            final int dashIdx = value.indexOf('-');
            final int colonIdx = value.indexOf(':');
            if (value.indexOf('T') > 1 || (dashIdx > 1 && colonIdx > dashIdx)) {
                try {
                    return new Timestamp(
                            DateUtil.parseISO8601DateTime(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date-time";
                    attemptedTemportalPExc = pExc;
                }
            } else if (dashIdx > 1) {
                try {
                    return new java.sql.Date(
                            DateUtil.parseISO8601Date(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "date";
                    attemptedTemportalPExc = pExc;
                }
            } else if (colonIdx > 1) {
                try {
                    return new Time(DateUtil.parseISO8601Time(value, timeZone, calToDateConverter).getTime());
                } catch (DateParseException pExc) {
                    attemptedTemporalType = "time";
                    attemptedTemportalPExc = pExc;
                }
            }
            if (attemptedTemportalPExc == null) {
                throw new DataModelParsingException("Malformed number: " + value, e);
            } else {
                throw new DataModelParsingException("Malformed ISO 8601 " + attemptedTemporalType
                        + " (or malformed number): " + attemptedTemportalPExc.getMessage(), e.getCause());
            }
        }
    } else if (value.startsWith("\"")) {
        try {
            return JSON_MAPPER.readValue(value, String.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed quoted string (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("\'")) {
        throw new DataModelParsingException(
                "Malformed quoted string (using JSON syntax): Use \" character for quotation, not \' character.");
    } else if (value.startsWith("[")) {
        try {
            return JSON_MAPPER.readValue(value, List.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("{")) {
        try {
            return JSON_MAPPER.readValue(value, LinkedHashMap.class);
        } catch (IOException e) {
            throw new DataModelParsingException(
                    "Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e);
        }
    } else if (value.startsWith("<")) {
        try {
            DocumentBuilder builder = NodeModel.getDocumentBuilderFactory().newDocumentBuilder();
            ErrorHandler errorHandler = NodeModel.getErrorHandler();
            if (errorHandler != null)
                builder.setErrorHandler(errorHandler);
            final Document doc = builder.parse(new InputSource(new StringReader(value)));
            NodeModel.simplify(doc);
            return doc;
        } catch (SAXException e) {
            final String saxMsg = e.getMessage();
            throw new DataModelParsingException("Malformed XML: " + (saxMsg != null ? saxMsg : e), e);
        } catch (Exception e) {
            throw new DataModelParsingException("XML parsing has failed with internal error: " + e, e);
        }
    } else if (value.equalsIgnoreCase(KEYWORD_TRUE)) {
        checkKeywordCase(value, KEYWORD_TRUE);
        return Boolean.TRUE;
    } else if (value.equalsIgnoreCase(KEYWORD_FALSE)) {
        checkKeywordCase(value, KEYWORD_FALSE);
        return Boolean.FALSE;
    } else if (value.equalsIgnoreCase(KEYWORD_NULL)) {
        checkKeywordCase(value, KEYWORD_NULL);
        return null;
    } else if (value.equalsIgnoreCase(KEYWORD_NAN)) {
        checkKeywordCase(value, KEYWORD_NAN);
        return Double.NaN;
    } else if (value.equalsIgnoreCase(KEYWORD_INFINITY)) {
        checkKeywordCase(value, KEYWORD_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_POSITIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_POSITIVE_INFINITY);
        return Double.POSITIVE_INFINITY;
    } else if (value.equalsIgnoreCase(KEYWORD_NEGATIVE_INFINITY)) {
        checkKeywordCase(value, KEYWORD_NEGATIVE_INFINITY);
        return Double.NEGATIVE_INFINITY;
    } else if (value.length() == 0) {
        throw new DataModelParsingException(
                "Empty value. (If you indeed wanted a 0 length string, quote it, like \"\".)");
    } else {
        return value;
    }
}

From source file:Main.java

/**
 * Parses an XML document into a DOM tree.
 *
 * <div class="nonnormative">//from   w  ww  .ja v a  2s . c  o  m
 *
 * <p>
 * Remember that when parsing XML files you often want to set an explicit
 * entity resolver. For example, consider a file such as this:</p>
 *
 * <pre>
 * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
 * &lt;!DOCTYPE root PUBLIC "-//NetBeans//DTD Foo 1.0//EN" "http://www.netbeans.org/dtds/foo-1_0.dtd"&gt;
 * &lt;root/&gt;
 * </pre>
 *
 * <p>
 * If you parse this with a null entity resolver, or you use the default
 * resolver (EntityCatalog.getDefault) but do not do anything special with
 * this DTD, you will probably find the parse blocking to make a network
 * connection <em>even when you are not validating</em>. That is because
 * DTDs can be used to define entities and other XML oddities, and are not a
 * pure constraint language like Schema or RELAX-NG.</p>
 *
 * <p>
 * There are three basic ways to avoid the network connection.</p>
 *
 * <ol>
 *
 * <li><p>
 * Register the DTD. This is generally the best thing to do. See
 * EntityCatalog's documentation for details, but for example in your layer
 * use:</p>
 *
 * <pre>
 * &lt;filesystem&gt;
 *   &lt;folder name="xml"&gt;
 *     &lt;folder name="entities"&gt;
 *       &lt;folder name="NetBeans"&gt;
 *         &lt;file name="DTD_Foo_1_0"
 *               url="resources/foo-1_0.dtd"&gt;
 *           &lt;attr name="hint.originalPublicID"
 *                 stringvalue="-//NetBeans//DTD Foo 1.0//EN"/&gt;
 *         &lt;/file&gt;
 *       &lt;/folder&gt;
 *     &lt;/folder&gt;
 *   &lt;/folder&gt;
 * &lt;/filesystem&gt;
 * </pre>
 *
 * <p>
 * Now the default system entity catalog will resolve the public ID to the
 * local copy in your module, not the network copy. Additionally, anyone who
 * mounts the "NetBeans Catalog" in the XML Entity Catalogs node in the
 * Runtime tab will be able to use your local copy of the DTD automatically,
 * for validation, code completion, etc. (The network URL should really
 * exist, though, for the benefit of other tools!)</p></li>
 *
 * <li><p>
 * You can also set an explicit entity resolver which maps that particular
 * public ID to some local copy of the DTD, if you do not want to register
 * it globally in the system for some reason. If handed other public IDs,
 * just return null to indicate that the system ID should be
 * loaded.</p></li>
 *
 * <li><p>
 * In some cases where XML parsing is very performance-sensitive, and you
 * know that you do not need validation and furthermore that the DTD defines
 * no infoset (there are no entity or character definitions, etc.), you can
 * speed up the parse. Turn off validation, but also supply a custom entity
 * resolver that does not even bother to load the DTD at all:</p>
 *
 * <pre>
 * public InputSource resolveEntity(String pubid, String sysid)
 *     throws SAXException, IOException {
 *   if (pubid.equals("-//NetBeans//DTD Foo 1.0//EN")) {
 *     return new InputSource(new ByteArrayInputStream(new byte[0]));
 *   } else {
 *     return EntityCatalog.getDefault().resolveEntity(pubid, sysid);
 *   }
 * }
 * </pre></li>
 *
 * </ol>
 *
 * </div>
 *
 * @param input          a parser input (for URL users use:
 *                       <code>new InputSource(url.toString())</code>
 * @param validate       if true validating parser is used
 * @param namespaceAware if true DOM is created by namespace aware parser
 * @param errorHandler   a error handler to notify about exception (such as
 *                       {@link #defaultErrorHandler}) or <code>null</code>
 * @param entityResolver SAX entity resolver (such as
 *                       EntityCatalog#getDefault) or <code>null</code>
 *
 * @throws IOException               if an I/O problem during parsing occurs
 * @throws SAXException              is thrown if a parser error occurs
 * @throws FactoryConfigurationError Application developers should never
 *                                   need to directly catch errors of this
 *                                   type.
 *
 * @return document representing given input
 */
public static Document parse(InputSource input, boolean validate, boolean namespaceAware,
        ErrorHandler errorHandler, EntityResolver entityResolver) throws IOException, SAXException {

    DocumentBuilder builder = null;
    DocumentBuilderFactory factory = getFactory(validate, namespaceAware);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        throw new SAXException("Cannot create parser satisfying configuration parameters", ex); //NOI18N
    }

    if (errorHandler != null) {
        builder.setErrorHandler(errorHandler);
    }

    if (entityResolver != null) {
        builder.setEntityResolver(entityResolver);
    }

    return builder.parse(input);
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml./*from w  ww . j  a  v a  2  s .  co  m*/
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(String[] inSchemas, String inXml, String schemaLanguage)
        throws MotuException {

    XMLErrorHandler errorHandler = new XMLErrorHandler();
    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        documentBuilderFactory.setExpandEntityReferences(true);

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage);
        // final String[] srcSchemas =
        // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd",
        // };

        // final String[] srcSchemas =
        // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd",
        // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", };

        // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml
        // final String[] srcSchemas =
        // {"C:/Documents and Settings/us/userocuments/Atoll/SchemaIso/srv/serviceMetadata.xsd",
        // };
        // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd",
        // };

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas);
        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd");
        // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
        // url.toString());
        documentBuilderFactory.setValidating(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        documentBuilder.parse(inXml);

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml.//from www.  j a  v a 2s . c o m
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(String[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {

    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage);
        // final String[] srcSchemas =
        // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd",
        // };

        // final String[] srcSchemas =
        // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd",
        // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", };

        // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml
        // final String[] srcSchemas =
        // {"C:/Documents and Settings/users documents/Atoll/SchemaIso/srv/serviceMetadata.xsd",
        // };
        // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd",
        // };

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas);
        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd");
        // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
        // url.toString());
        documentBuilderFactory.setValidating(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        documentBuilder.parse(inXml);

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml.//from   w ww .  j  ava  2  s  .co m
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(InputStream[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {
    // parse an XML document into a DOM tree
    Document document;
    // create a Validator instance, which can be used to validate an instance document
    Validator validator;
    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        document = documentBuilder.parse(inXml);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
        schemaFactory.setErrorHandler(errorHandler);

        // load a WXS schema, represented by a Schema instance

        Source[] schemaFiles = new Source[inSchemas.length];

        // InputStream inShema = null;
        int i = 0;
        for (InputStream inSchema : inSchemas) {
            schemaFiles[i] = new StreamSource(inSchema);
            i++;
        }

        Schema schema = schemaFactory.newSchema(schemaFiles);

        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new DOMSource(document));

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Creates the parser instance based on dom parser factory Validates the xml file against the
 * XSD schema Return the documentElement of the xml document if validations succeeded
 * /*from  w  w  w  . j  a  va 2  s  .c  o  m*/
 * @param xmlFile - XML file to be parsed
 * @param xmlSchema - XSD that XML file should be validated against
 * @return documentElement of the XML file
 */
public static Document getXmlDocumentElement(String xmlFile, String xmlSchema) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setCoalescing(true);
    factory.setNamespaceAware(false);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
            XMLUtil.class.getResource(xmlSchema).getFile());
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler());
    // Parse the document from the classpath.
    URL xmlFileUri = XMLUtil.class.getResource(xmlFile);
    if (null == xmlFileUri) {
        log.error("Unable to find file on classpath: " + xmlFile);
        return null;
    }
    return builder.parse(xmlFileUri.getFile());
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Reads the content of the persistence.xml file into an object model, with
 * the root node of type {@link Document}.
 * //from   ww w . j  a  v  a2s.  com
 * @param is
 *            {@link InputStream} of the persistence.xml content
 * @return root node of the parsed xml content
 * @throws InvalidConfigurationException
 *             if the content could not be read due to an I/O error or could
 *             not be parsed?
 */
private static Document parseDocument(final InputStream is) throws InvalidConfigurationException {
    Document persistenceXmlDoc;
    final List parsingErrors = new ArrayList();
    final InputSource source = new InputSource(is);
    final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);

    try {
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new ErrorLogger("XML InputStream", parsingErrors));
        persistenceXmlDoc = docBuilder.parse(source);
    } catch (ParserConfigurationException e) {
        log.error("Error during parsing, Caused by: {}.", e);
        throw new PersistenceLoaderException("Error during parsing persistence.xml, caused by: ", e);
    } catch (IOException e) {
        throw new InvalidConfigurationException("Error reading persistence.xml, caused by: ", e);
    } catch (SAXException e) {
        throw new InvalidConfigurationException("Error parsing persistence.xml, caused by: ", e);
    }

    if (!parsingErrors.isEmpty()) {
        throw new InvalidConfigurationException("Invalid persistence.xml", (Throwable) parsingErrors.get(0));
    }

    return persistenceXmlDoc;
}

From source file:com.connexta.arbitro.ctx.InputParser.java

/**
 * Tries to Parse the given output as a Context document.
 * /*from   ww  w  .ja v a2  s .  c  o m*/
 * @param input the stream to parse
 * @param rootTag either "Request" or "Response"
 * 
 * @return the root node of the request/response
 * 
 * @throws ParsingException if a problem occurred parsing the document
 */
public static Node parseInput(InputStream input, String rootTag) throws ParsingException {
    NodeList nodes = null;

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);

        DocumentBuilder builder = null;

        // as of 1.2, we always are namespace aware
        factory.setNamespaceAware(true);

        if (ipReference == null) {
            // we're not validating
            factory.setValidating(false);

            builder = factory.newDocumentBuilder();
        } else {
            // we are validating
            factory.setValidating(true);

            factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            factory.setAttribute(JAXP_SCHEMA_SOURCE, ipReference.schemaFile);

            builder = factory.newDocumentBuilder();
            builder.setErrorHandler(ipReference);
        }

        Document doc = builder.parse(input);
        nodes = doc.getElementsByTagName(rootTag);
    } catch (Exception e) {
        throw new ParsingException("Error tring to parse " + rootTag + "Type", e);
    }

    if (nodes.getLength() != 1)
        throw new ParsingException("Only one " + rootTag + "Type allowed " + "at the root of a Context doc");

    return nodes.item(0);
}

From source file:com.amalto.webapp.core.util.Util.java

public static Document parse(String xmlString, String schema) throws Exception {
    // parse//  w  w w . j  ava2 s  .c om
    Document d;
    SAXErrorHandler seh = new SAXErrorHandler();
    try {
        // initialize the sax parser which uses Xerces
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Schema validation based on schemaURL
        factory.setNamespaceAware(true);
        factory.setValidating((schema != null));
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", //$NON-NLS-1$
                "http://www.w3.org/2001/XMLSchema"); //$NON-NLS-1$
        if (schema != null) {
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", //$NON-NLS-1$
                    new InputSource(new StringReader(schema)));
        }
        DocumentBuilder builder;
        builder = factory.newDocumentBuilder();
        builder.setErrorHandler(seh);
        d = builder.parse(new InputSource(new StringReader(xmlString)));
    } catch (Exception e) {
        String err = "Unable to parse the document" + ": " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                + e.getLocalizedMessage() + "\n " //$NON-NLS-1$
                + xmlString;
        throw new Exception(err);
    }
    // check if document parsed correctly against the schema
    if (schema != null) {
        String errors = seh.getErrors();
        if (!errors.equals("")) { //$NON-NLS-1$
            String err = "Document  did not parse against schema: \n" + errors + "\n" + xmlString; //$NON-NLS-1$//$NON-NLS-2$
            throw new Exception(err);
        }
    }
    return d;
}

From source file:com.ikon.util.FormUtils.java

/**
 * Parse params.xml definitions/*from  ww w .  java 2 s . c o m*/
 * 
 * @return A List parameter elements.
 */
public static List<FormElement> parseReportParameters(InputStream is) throws ParseException {
    log.debug("parseReportParameters({})", is);
    List<FormElement> params = new ArrayList<FormElement>();

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        ErrorHandler handler = new ErrorHandler();
        // EntityResolver resolver = new LocalResolver(Config.DTD_BASE);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(handler);
        db.setEntityResolver(resolver);

        if (is != null) {
            Document doc = db.parse(is);
            doc.getDocumentElement().normalize();
            NodeList nlForm = doc.getElementsByTagName("report-parameters");

            for (int i = 0; i < nlForm.getLength(); i++) {
                Node nForm = nlForm.item(i);

                if (nForm.getNodeType() == Node.ELEMENT_NODE) {
                    NodeList nlField = nForm.getChildNodes();
                    params = parseField(nlField);
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new ParseException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new ParseException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ParseException(e.getMessage(), e);
    }

    log.debug("parseReportParameters: {}", params);
    return params;
}