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.jts.protocolvalidator.DefinitionFinder.java

private static String getFileID(File file) throws Exception {
    Document doc = null;//  w  ww  .  j  ava  2 s  .c o m
    DocumentBuilder db = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    String id = "";

    try {
        db = dbf.newDocumentBuilder();
    } catch (javax.xml.parsers.ParserConfigurationException pce) {
        Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                "Exception while configuring parser: " + pce.toString(), pce);
        throw new CodeGeneratorException("Exception while configuring parser: " + pce.getMessage());
    }
    // see if the file can be parsed
    try {
        doc = db.parse(file);
    } catch (final IOException ioe) {
        Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                "Unable to read file" + file.getName() + " \n " + ioe.toString(), ioe);
    } catch (final SAXException saxe) {
        Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                "Unable to parse file" + file.getName() + " \n " + saxe.toString(), saxe);
    }

    // getting the id from the file
    Element root = doc.getDocumentElement();

    if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0")) {
        id = root.getAttribute("id");
    }

    return id;
}

From source file:org.jts.protocolvalidator.DefinitionFinder.java

/**
 * Filter jsidl files and place in a Map with associated id.
 * @param fileList list of JSIDL XML files
 *//*from   w  w  w.j av  a  2s .  com*/
private void populateIDMap(List<File> fileList, String schemaPath) throws Exception {

    Document doc = null;
    DocumentBuilder db = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    String id = "";

    try {
        db = dbf.newDocumentBuilder();
    } catch (javax.xml.parsers.ParserConfigurationException pce) {
        Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                "Exception while configuring parser: " + pce.toString(), pce);
        throw new CodeGeneratorException("Exception while configuring parser: " + pce.getMessage());
    }

    // store the path/id for each path in the list
    for (int ii = 0; ii < fileList.size(); ii++) {
        File file = fileList.get(ii);
        final String fileName = file.getPath();

        // see if the file can be parsed
        try {
            doc = db.parse(file);
        } catch (final IOException ioe) {
            Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                    "Unable to read file" + fileName + " \n " + ioe.toString(), ioe);
            continue; // weaken import to allow bad files in target dir
        } catch (final SAXException saxe) {
            Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                    "Unable to parse file" + fileName + " \n " + saxe.toString(), saxe);
            continue; // weaken import to allow bad files in target dir
        }

        // getting the id from the file
        Element root = doc.getDocumentElement();

        if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0")) {
            JSIDLReader reader = new JSIDLReader(fileName, schemaPath);
            Object rootObj = reader.getRootElement();
            if (rootObj instanceof ServiceDef) {
                serviceDefMap.put(((ServiceDef) rootObj).getId(), ((ServiceDef) rootObj));
                serviceSet.getServiceDef().add(((ServiceDef) rootObj));
            } else if (rootObj instanceof DeclaredTypeSet) {
                typeSetMap.put(((DeclaredTypeSet) rootObj).getId(), ((DeclaredTypeSet) rootObj));
                serviceSet.getDeclaredTypeSet().add(((DeclaredTypeSet) rootObj));
            } else if (rootObj instanceof DeclaredConstSet) {
                constSetMap.put(((DeclaredConstSet) rootObj).getId(), ((DeclaredConstSet) rootObj));
                serviceSet.getDeclaredConstSet().add(((DeclaredConstSet) rootObj));
            }
        }
    }

}

From source file:org.jts.protocolvalidator.FileFinder.java

/**
 * Filter jsidl files and place in a Map with associated id.
 * @param fileList list of JSIDL XML files
 *//*from  ww w .  ja va 2s  .c o m*/
private void populateIDMap(List<File> fileList) throws Exception {
    fileMap = new HashMap();
    reverseFileMap = new HashMap();
    processedFileMap = new HashMap();

    Document doc = null;
    DocumentBuilder db = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    String id = "";

    try {
        db = dbf.newDocumentBuilder();
    } catch (javax.xml.parsers.ParserConfigurationException pce) {
        Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                "Exception while configuring parser: " + pce.toString(), pce);
        throw new Exception("Exception while configuring parser: " + pce.getMessage());
    }

    // store the path/id for each path in the list
    for (int ii = 0; ii < fileList.size(); ii++) {
        File file = fileList.get(ii);
        final String fileName = file.getPath();

        // see if the file can be parsed
        try {
            doc = db.parse(file);
        } catch (final IOException ioe) {
            Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                    "Unable to read file" + fileName + " \n " + ioe.toString(), ioe);
            continue; // weaken import to allow bad files in target dir
        } catch (final SAXException saxe) {
            Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE,
                    "Unable to parse file" + fileName + " \n " + saxe.toString(), saxe);
            continue; // weaken import to allow bad files in target dir
        }

        // getting the id from the file
        Element root = doc.getDocumentElement();
        id = root.getAttribute("id");

        if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0") && !id.isEmpty()) {
            fileMap.put(fileName, root.getAttribute("id"));
            reverseFileMap.put(root.getAttribute("id"), fileName);
        }
    }

}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Parses a XML document and returns a DOM object.
 * /*  www  .  j  a  va 2s. co m*/
 * @param reader
 *          accessing the resource to parse
 * @return a DOM object
 * @throws IOException
 * @throws SAXException
 * @deprecated Probably code which uses this method is not safe for two reasons: the reader only gets closed if no
 *             exception is thrown, second probably the charset is not correctly set. Use {@link #parse(InputStream)} instead, charset encoding is set inside the xml-file.
 */
@Deprecated
public static Document parse(final Reader reader) throws IOException, SAXException {
    javax.xml.parsers.DocumentBuilder parser = null;

    try {
        parser = DOCUMENT_FACTORY.newDocumentBuilder();
    } catch (final ParserConfigurationException ex) {
        ex.printStackTrace();
        throw new IOException("Unable to initialize DocumentBuilder: " + ex.getMessage());
    }

    final Document doc = parser.parse(new InputSource(reader));
    reader.close();

    return doc;
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Parses a XML document and returns a DOM object.
 * <p>//from w ww  . j a  va 2 s . com
 * The stream is NOT closed by this method.
 * 
 * @param reader
 *          accessing the resource to parse
 * @return a DOM object
 * @throws IOException
 * @throws SAXException
 */
public static Document parse(final InputStream is) throws IOException, SAXException {
    try {
        final DocumentBuilder parser = DOCUMENT_FACTORY.newDocumentBuilder();
        return parser.parse(new InputSource(is));
    } catch (final ParserConfigurationException ex) {
        ex.printStackTrace();

        throw new IOException("Unable to initialize DocumentBuilder: " + ex.getMessage(), ex);
    }
}

From source file:org.kitodo.editor.XMLEditor.java

/**
 * Constructor./*from  www. j a  v  a2s  .c o m*/
 */
public XMLEditor() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("ERROR: unable to instantiate document builder: " + e.getMessage());
    }
}

From source file:org.kitodo.production.editor.XMLEditor.java

/**
 * Constructor./*from  w w  w .j  av  a  2 s.co  m*/
 */
public XMLEditor() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("ERROR: unable to instantiate document builder: " + e.getMessage());
    }
}

From source file:org.kitodo.production.services.data.ImportService.java

private Document transformXmlByXslt(String xmlString, File stylesheetFile) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {//from ww w . ja  v a2 s  .c  o  m
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    factory.setNamespaceAware(true);
    try {
        SAXBuilder saxBuilder = new SAXBuilder();
        DOMOutputter outputter = new DOMOutputter();
        StreamSource transformSource = new StreamSource(stylesheetFile);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        File outputFile = File.createTempFile("transformed", "xml");
        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            Transformer xsltTransformer = transformerFactory.newTransformer(transformSource);
            TransformerHandler handler = ((SAXTransformerFactory) SAXTransformerFactory.newInstance())
                    .newTransformerHandler();
            handler.setResult(new StreamResult(outputStream));
            Result saxResult = new SAXResult(handler);
            SAXSource saxSource = new SAXSource(new InputSource(new StringReader(xmlString)));
            xsltTransformer.transform(saxSource, saxResult);
        }
        return outputter.output(saxBuilder.build(outputFile));
    } catch (JDOMException | IOException | TransformerException e) {
        throw new ConfigException("Error in transforming the response in intern format : ", e);
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.OpportunitySchemaParserServiceImpl.java

/**
 * This method fetches all the forms required from a given schema of opportunity
 * /*from  w ww  . j av a 2s . c om*/
 * @param schema {@link String}
 * @return {@link HashMap} containing all form information
 */
@Override
public List<S2sOppForms> getForms(String proposalNumber, String schema) throws S2sCommunicationException {
    if (StringUtils.isBlank(proposalNumber)) {
        throw new IllegalArgumentException("proposalNumber is blank");
    }

    if (StringUtils.isBlank(schema)) {
        throw new IllegalArgumentException("schema is blank");
    }

    boolean mandatory;
    boolean available;
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    ArrayList<S2sOppForms> schemaList = new ArrayList<S2sOppForms>();
    Document document;
    try {
        builder = domFactory.newDocumentBuilder();
        InputStream is = (InputStream) new URL(schema).getContent();
        document = builder.parse(is);
    } catch (ParserConfigurationException e) {
        throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_PARSING, e.getMessage(), schema);
    } catch (SAXException e) {
        throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_PARSING_SAXEXCEPTION,
                e.getMessage(), schema);
    } catch (IOException e) {
        throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_SCHEMA_NOT_FOUND, e.getMessage(),
                schema);
    }

    Element schemaElement = document.getDocumentElement();
    NodeList importList = document.getElementsByTagNameNS(XSD_NS, IMPORT);
    Node allForms = document.getElementsByTagNameNS(XSD_NS, ALL).item(0);

    // If there is no "Forms" element, it's probably because this is an NIH complex project
    if (allForms == null) {
        Node topElementName = schemaElement.getElementsByTagNameNS(XSD_NS, ELEMENT).item(0).getAttributes()
                .item(0);
        if (topElementName.getNodeName().equals("name")
                && !topElementName.getNodeValue().equals("GrantApplication")) {
            throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_NO_FORM_ELEMENT, "", "");
        }
    }

    NodeList formsList = ((Element) allForms).getElementsByTagNameNS(XSD_NS, ELEMENT);
    String[] formNames = new String[formsList.getLength()];

    for (int formIndex = 0; formIndex < formsList.getLength(); formIndex++) {
        Node form = formsList.item(formIndex);
        String fullFormName = ((Element) form).getAttribute(REF);
        String formName = fullFormName.substring(0, fullFormName.indexOf(CH_COLON));
        String minOccurs = ((Element) form).getAttribute(MIN_OCCURS);
        String nameSpace = schemaElement.getAttribute(XMLNS + formName);
        FormMappingInfo info = formMappingService.getFormInfo(nameSpace, proposalNumber);
        String displayFormName = info == null ? formName : info.getFormName();
        formNames[formIndex] = nameSpace;
        for (int impIndex = 0; impIndex < importList.getLength(); impIndex++) {
            Node importNode = importList.item(impIndex);
            if (((Element) importNode).getAttribute(NAMESPACE).equalsIgnoreCase(nameSpace)) {
                String schemaUrl = ((Element) importNode).getAttribute(SCHEMA_LOCATION);
                S2sOppForms oppForm = new S2sOppForms();
                oppForm.setFormName(displayFormName);
                S2sOppFormsId oppFormId = new S2sOppFormsId();
                oppFormId.setProposalNumber(proposalNumber);
                oppFormId.setOppNameSpace(nameSpace);
                oppForm.setS2sOppFormsId(oppFormId);
                oppForm.getS2sOppFormsId().setOppNameSpace(nameSpace);
                oppForm.setSchemaUrl(schemaUrl);
                mandatory = (minOccurs == null || minOccurs.trim().equals("")
                        || Integer.parseInt(minOccurs) > 0);
                oppForm.setMandatory(mandatory);
                if (info != null) {
                    available = true;
                    oppForm.setUserAttachedForm(info.getUserAttachedForm());
                } else {
                    available = false;
                }
                oppForm.setAvailable(available);
                oppForm.setInclude(mandatory && available);
                schemaList.add(oppForm);
            }
        }
    }
    return schemaList;
}

From source file:org.kuali.kfs.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

protected byte[] addNamespaceDefinition(ElectronicInvoiceLoad eInvoiceLoad, File invoiceFile) {

    boolean result = true;

    if (LOG.isInfoEnabled()) {
        LOG.info("Adding namespace definition");
    }/*  w ww . j  a va2 s .  c  o  m*/

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(false); // It's not needed to validate here
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch (ParserConfigurationException e) {
        LOG.error("Error getting document builder - " + e.getMessage());
        throw new RuntimeException(e);
    }

    Document xmlDoc = null;

    try {
        xmlDoc = builder.parse(invoiceFile);
    } catch (Exception e) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Error parsing the file - " + e.getMessage());
        }
        rejectElectronicInvoiceFile(eInvoiceLoad, UNKNOWN_DUNS_IDENTIFIER, invoiceFile, e.getMessage(),
                PurapConstants.ElectronicInvoice.FILE_FORMAT_INVALID);
        return null;
    }

    Node node = xmlDoc.getDocumentElement();
    Element element = (Element) node;

    String xmlnsValue = element.getAttribute("xmlns");
    String xmlnsXsiValue = element.getAttribute("xmlns:xsi");

    File namespaceAddedFile = getInvoiceFile(invoiceFile.getName());

    if (StringUtils.equals(xmlnsValue, "http://www.kuali.org/kfs/purap/electronicInvoice")
            && StringUtils.equals(xmlnsXsiValue, "http://www.w3.org/2001/XMLSchema-instance")) {
        if (LOG.isInfoEnabled()) {
            LOG.info("xmlns and xmlns:xsi attributes already exists in the invoice xml");
        }
    } else {
        element.setAttribute("xmlns", "http://www.kuali.org/kfs/purap/electronicInvoice");
        element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    }

    OutputFormat outputFormat = new OutputFormat(xmlDoc);
    outputFormat.setOmitDocumentType(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(out, outputFormat);
    try {
        serializer.asDOMSerializer();
        serializer.serialize(xmlDoc.getDocumentElement());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("Namespace validation completed");
    }

    return out.toByteArray();

}