Example usage for javax.xml.parsers ParserConfigurationException getMessage

List of usage examples for javax.xml.parsers ParserConfigurationException getMessage

Introduction

In this page you can find the example usage for javax.xml.parsers ParserConfigurationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.corpus_tools.pepper.core.PepperJobImpl.java

/**
 * {@inheritDoc PepperJob#load(URI)}//from   w  w  w. j  a  va  2  s .c o  m
 */
@Override
public void load(URI uri) {
    if (uri.isFile()) {
        File wdFile = new File(uri.toFileString());
        // set folder containing workflow description as base dir
        setBaseDir(uri.trimSegments(1));

        SAXParser parser;
        XMLReader xmlReader;
        SAXParserFactory factory = SAXParserFactory.newInstance();

        WorkflowDescriptionReader contentHandler = new WorkflowDescriptionReader();
        contentHandler.setPepperJob(this);
        contentHandler.setLocation(uri);

        // remove all existing steps
        clear();

        try {
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setContentHandler(contentHandler);
        } catch (ParserConfigurationException e) {
            throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file '"
                    + wdFile.getAbsolutePath() + "': " + e.getMessage() + ". ", e);
        } catch (Exception e) {
            throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file '"
                    + wdFile.getAbsolutePath() + "': " + e.getMessage() + ". ", e);
        }
        try {
            InputStream inputStream = new FileInputStream(wdFile);
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            InputSource is = new InputSource(reader);
            is.setEncoding("UTF-8");
            xmlReader.parse(is);
        } catch (SAXException e) {
            try {
                parser = factory.newSAXParser();
                xmlReader = parser.getXMLReader();
                xmlReader.setContentHandler(contentHandler);
                xmlReader.parse(wdFile.getAbsolutePath());
            } catch (Exception e1) {
                throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file '"
                        + wdFile.getAbsolutePath() + "': " + e1.getMessage() + ". ", e1);
            }
        } catch (Exception e) {
            if (e instanceof PepperModuleException) {
                throw (PepperModuleException) e;
            } else {
                throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file'"
                        + wdFile + "', because of a nested exception: " + e.getMessage() + ". ", e);
            }
        }
    } else {
        throw new UnsupportedOperationException(
                "Currently Pepper can only load workflow description from local files.");
    }
}

From source file:org.dataconservancy.ui.model.builder.xstream.XstreamBusinessObjectBuilder.java

/**
 * Constructs a builder that will perform validation when de-serializing XML streams if <code>isValidating</code>
 * is <code>true</code>.  The schema used for validation is the BOP 1.0 schema.
 * <p/>/*from  w  w  w .j a  v a 2s  .c o  m*/
 * <strong><em>N.B.</em></strong>: currently this class will only validate incoming DC BOPs (it will <em>not</em>
 * validate entities).  At a later time this implementation may be updated to validate entities as well.
 *
 * @param isValidating flag indicating whether or not validation should be enabled
 * @throws IllegalStateException if the BOP schema cannot be resolved or parsed
 */
public XstreamBusinessObjectBuilder(XStream xStream, boolean isValidating) {
    x = xStream;
    validating = isValidating;

    if (validating) {
        try {
            // Create a namespace-aware parser that will parse XML into a DOM tree.
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            parser = dbf.newDocumentBuilder();

            // Create a SchemaFactory
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // Load the schema
            final URL businessObjectSchema = this.getClass().getResource(BOP_SCHEMA_RESOURCE);
            Source schemaFile = new StreamSource(businessObjectSchema.openStream());
            Schema schema = factory.newSchema(schemaFile);

            // Create a Validator instance, which can be used to validate an instance document
            validator = schema.newValidator();
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException("Unable to initialize " + this.getClass().getName()
                    + ": error configuring parser: " + e.getMessage(), e);
        } catch (SAXException e) {
            throw new IllegalStateException(
                    "Unable to initialize " + this.getClass().getName() + ": error retrieving "
                            + " or parsing class path resource " + BOP_SCHEMA_RESOURCE + ": " + e.getMessage(),
                    e);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to initialize " + this.getClass().getName() + ": IO error: " + e.getMessage(), e);
        }
    }
}

From source file:org.deegree.portal.owswatch.validator.AbstractValidator.java

/**
 * Creates a new instance of DocumentBuilder
 *
 * @return DocumentBuilder//w ww .j a va  2s  . c  o m
 * @throws IOException
 */
protected DocumentBuilder instantiateParser() throws IOException {

    DocumentBuilder parser = null;

    try {
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);
        fac.setValidating(false);
        fac.setIgnoringElementContentWhitespace(false);
        parser = fac.newDocumentBuilder();
        return parser;
    } catch (ParserConfigurationException e) {
        throw new IOException("Unable to initialize DocumentBuilder: " + e.getMessage());
    }
}

From source file:org.docx4j.XmlUtils.java

/**
 * Use the suitably configured DocumentBuilderFactory to provide
 * a new instance of DocumentBuilder. Remember that DocumentBuilder is not thread-safe!
 * @return/* w w  w.j  av a  2  s  . c  o  m*/
 * @since 3.2.0
 */
public static DocumentBuilder getNewDocumentBuilder() {
    synchronized (documentBuilderFactory) {
        // see https://community.oracle.com/thread/1626108 for inconclusive discussion about whether a pool would be worthwhile 
        try {
            return documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // Catch this, since its unlikely to happen 
            log.error(e.getMessage(), e);
            return null;
        }
    }
}

From source file:org.dspace.app.sfx.SFXFileReader.java

/** Parses XML file and returns XML document.
 * @param fileName XML file to parse// w  w w.j  av a  2 s .c  o  m
 * @return XML document or <B>null</B> if error occured. The error is caught and logged.
 */

public static Document parseFile(String fileName) {
    log.info("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        log.error("Wrong parser configuration: " + e.getMessage());
        return null;
    }
    File sourceFile = new File(fileName);
    try {
        doc = docBuilder.parse(sourceFile);
    } catch (SAXException e) {
        log.error("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        log.error("Could not read source file: " + e.getMessage());
    }
    log.info("XML file parsed");
    return doc;
}

From source file:org.dspace.app.sfx.SFXFileReaderServiceImpl.java

@Override
public Document parseFile(String fileName) {
    log.info("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder;//from w  ww  . ja v  a 2 s .co  m
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        log.error("Wrong parser configuration: " + e.getMessage());
        return null;
    }
    File sourceFile = new File(fileName);
    try {
        doc = docBuilder.parse(sourceFile);
    } catch (SAXException e) {
        log.error("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        log.error("Could not read source file: " + e.getMessage());
    }
    log.info("XML file parsed");
    return doc;
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.util.ErrorLibraryUtils.java

public static boolean validateAgainstSchema(String xmlLocation, String xsdLocation)
        throws PreProcessFailedException {
    boolean isValidate = false;

    Document document = null;// ww w.j a  va2 s .  c o m
    Schema schema = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder parser = domFactory.newDocumentBuilder();
        document = parser.parse(new File(xmlLocation));

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = Thread.currentThread().getContextClassLoader().getResource(xsdLocation);
        if (schemaUrl == null) {
            throw new PreProcessFailedException("Unable to find schema resource: " + xsdLocation);
        }

        InputStream stream = null;
        try {
            stream = schemaUrl.openStream();
            Source schemaFile = new StreamSource(stream);
            schema = factory.newSchema(schemaFile);
        } finally {
            IOUtils.closeQuietly(stream);
        }

    } catch (ParserConfigurationException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "XML parsing failed because of IOException : " + exception.getMessage(), exception);
    } catch (Exception exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);
    }

    Validator validator = schema.newValidator();

    try {
        validator.validate(new DOMSource(document));
        isValidate = true;
    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML validation against XSD failed : " + exception.getMessage(),
                exception);
    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "Schema validation failed because of IOException : " + exception.getMessage(), exception);
    }

    return isValidate;
}

From source file:org.ebayopensource.turmeric.tools.library.utils.TypeLibraryUtilities.java

public static AdditionalXSDInformation parseTheXSDFile(String xsdSrcPath) {

    final AdditionalXSDInformation additionalXSDInformation = new AdditionalXSDInformation();

    class ParseClass extends DefaultHandler {

        @Override//  w  w  w. j  a v  a2s .  c  o  m
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            String elementName = ("".equals(localName)) ? qName : localName;

            if (elementName.startsWith("schema") || elementName.contains(":schema")) {
                String tns = attributes.getValue("targetNamespace");
                String version = attributes.getValue("version");
                additionalXSDInformation.setTargetNamespace(tns);
                additionalXSDInformation.setVersion(version);
            }

            if (elementName.startsWith("simpleType") || elementName.contains(":simpleType")) {
                additionalXSDInformation.setSimpleType(true);
                String typeName = attributes.getValue("name");
                additionalXSDInformation.setTypeName(typeName);
                additionalXSDInformation.getTypeNamesList().add(typeName);
            }

            if (elementName.startsWith("complexType") || elementName.contains(":complexType")) {
                additionalXSDInformation.setSimpleType(false);
                String typeName = attributes.getValue("name");
                additionalXSDInformation.setTypeName(typeName);
                additionalXSDInformation.getTypeNamesList().add(typeName);
            }

        }

    }

    File xsdFile = new File(xsdSrcPath);
    if (!xsdFile.exists()) {
        //need to do additional check for backward compatibility
        if (!checkIfXsdExistsInOlderPath(xsdSrcPath, additionalXSDInformation)) {
            logger.log(Level.INFO, "Xsd file not found in " + xsdSrcPath);
            additionalXSDInformation.setDoesFileExist(false);
            logger.log(Level.INFO, "Setting AdditionalXsdInformation setDoesFileExist to false");
            return additionalXSDInformation;
        }
    } else {
        additionalXSDInformation.setDoesFileExist(true);
    }

    DefaultHandler defaultHandler = new ParseClass();
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    if (additionalXSDInformation.isXsdPathChanged()) {
        String newXsdLocation = getOlderXsdSrcPath(xsdSrcPath);
        xsdFile = new File(newXsdLocation);
    }

    try {
        SAXParser saxParser = parserFactory.newSAXParser();
        saxParser.parse(xsdFile, defaultHandler);
    } catch (ParserConfigurationException e) {
        getLogger().log(Level.WARNING,
                "ParserConfigurationException while parsing XSD file " + xsdSrcPath + "\n" + e.getMessage());
    } catch (SAXException e) {
        getLogger().log(Level.WARNING,
                "SAXException while parsing XSD file " + xsdSrcPath + "\n" + e.getMessage());
    } catch (IOException e) {
        getLogger().log(Level.WARNING,
                "IOException while parsing XSD file " + xsdSrcPath + "\n" + e.getMessage());
    }

    return additionalXSDInformation;

}

From source file:org.eclipse.winery.common.ModelUtilities.java

/**
 * This is a special method for Winery. Winery allows to define a property by specifying
 * name/value values. We convert the given Properties to XML.
 * /*from ww  w . j  a v  a 2s.  c o  m*/
 * @param wpd the Winery's properties definition of the type of the given template (i.e., wpd =
 *        getWinerysPropertiesDefinition(template.getType()))
 * @param template the node template to set the associated properties
 */
public static void setPropertiesKV(WinerysPropertiesDefinition wpd, TEntityTemplate template,
        Properties properties) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ModelUtilities.logger.debug(e.getMessage(), e);
        throw new IllegalStateException("Could not instantiate document builder", e);
    }
    Document doc = db.newDocument();

    Element root = doc.createElementNS(wpd.getNamespace(), wpd.getElementName());
    doc.appendChild(root);

    // we produce the serialization in the same order the XSD would be generated (because of the
    // usage of xsd:sequence)
    for (PropertyDefinitionKV prop : wpd.getPropertyDefinitionKVList()) {
        // we always write the element tag as the XSD forces that
        Element element = doc.createElementNS(wpd.getNamespace(), prop.getKey());
        root.appendChild(element);
        String value = properties.getProperty(prop.getKey());
        if (value != null) {
            Text text = doc.createTextNode(value);
            element.appendChild(text);
        }
    }

    org.eclipse.winery.model.tosca.TEntityTemplate.Properties tprops = new org.eclipse.winery.model.tosca.TEntityTemplate.Properties();
    tprops.setAny(doc.getDocumentElement());
    template.setProperties(tprops);
}

From source file:org.eclipse.winery.common.ModelUtilities.java

/**
 * Generates a XSD when Winery's K/V properties are used. This method is put here instead of
 * WinerysPropertiesDefinitionResource to avoid generating the subresource
 * //  ww  w.  j a  v a 2s . c om
 * public because of the usage by TOSCAEXportUtil
 * 
 * @return empty Document, if Winery's Properties Definition is not fully filled (e.g., no
 *         wrapping element defined)
 */
public static Document getWinerysPropertiesDefinitionXSDAsDocument(WinerysPropertiesDefinition wpd) {
    /*
     * This is a quick hack: an XML schema container is created for each element. Smarter
     * solution: create a hash from namespace to XML schema element and re-use that for each new
     * element Drawback of "smarter" solution: not a single XSD file any more
     */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ModelUtilities.logger.debug(e.getMessage(), e);
        throw new IllegalStateException("Could not instantiate document builder", e);
    }
    Document doc = docBuilder.newDocument();

    if (!ModelUtilities.allRequiredFieldsNonNull(wpd)) {
        // wpd not fully filled -> valid XSD cannot be provided
        // fallback: add comment and return "empty" document
        Comment comment = doc
                .createComment("Required fields are missing in Winery's key/value properties definition.");
        doc.appendChild(comment);
        return doc;
    }

    // create XSD schema container
    Element schemaElement = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
    doc.appendChild(schemaElement);
    schemaElement.setAttribute("elementFormDefault", "qualified");
    schemaElement.setAttribute("attributeFormDefault", "unqualified");
    schemaElement.setAttribute("targetNamespace", wpd.getNamespace());

    // create XSD element itself
    Element el = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
    schemaElement.appendChild(el);
    el.setAttribute("name", wpd.getElementName());
    Element el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "complexType");
    el.appendChild(el2);
    el = el2;
    el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "sequence");
    el.appendChild(el2);
    el = el2;

    // currently, "xsd" is a hardcoded prefix in the type definition
    el.setAttribute("xmlns:xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);

    for (PropertyDefinitionKV prop : wpd.getPropertyDefinitionKVList()) {
        el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
        el.appendChild(el2);
        el2.setAttribute("name", prop.getKey());
        // prop.getType has the prefix included
        el2.setAttribute("type", prop.getType());
    }

    return doc;
}