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.asimba.utility.xml.XMLUtils.java

/**
 * Create the DOM Document from the XML-document in the provided string
 * /*from ww  w . j av a 2  s .  c o m*/
 * @param sXML String that contains XML document
 * @param namespaceAware Whether the document should be built with namespace awareness
 * @return DOM Document representation of the XML document
 * @throws OAException
 */
public static Document getDocumentFromString(String sXML, boolean namespaceAware) throws OAException {
    DocumentBuilderFactory oDocumentBuilderFactory = DocumentBuilderFactory.newInstance();

    oDocumentBuilderFactory.setNamespaceAware(namespaceAware);

    try {
        DocumentBuilder oDocumentBuilder;
        oDocumentBuilder = oDocumentBuilderFactory.newDocumentBuilder();

        InputSource is = new InputSource(new StringReader(sXML));
        return oDocumentBuilder.parse(is);
    } catch (ParserConfigurationException e) {
        _oLogger.error("Exception before processing the XML document: " + e.getMessage());
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (SAXException e) {
        _oLogger.warn(
                "SAX Exception when parsing the XML-document" + e.getMessage() + "Document was: \n" + sXML);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (IOException e) {
        _oLogger.warn(
                "IO Exception when parsing the XML-document" + e.getMessage() + "Document was: \n" + sXML);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.atombeat.xquery.functions.util.RequestGetData.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);

    // request object is read from global variable $request
    Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR);

    if (var == null || var.getValue() == null)
        throw new XPathException(this, "No request object found in the current XQuery context.");

    if (var.getValue().getItemType() != Type.JAVA_OBJECT)
        throw new XPathException(this, "Variable $request is not bound to an Java object.");

    JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);

    if (value.getObject() instanceof RequestWrapper) {
        RequestWrapper request = (RequestWrapper) value.getObject();

        //if the content length is unknown, return
        if (request.getContentLength() == -1) {
            return Sequence.EMPTY_SEQUENCE;
        }/*from   www .j  ava 2  s .c  o  m*/

        //first, get the content of the request
        byte[] bufRequestData = null;
        try {
            InputStream is = request.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(request.getContentLength());
            byte[] buf = new byte[256];
            int l = 0;
            while ((l = is.read(buf)) > -1) {
                bos.write(buf, 0, l);
            }
            bufRequestData = bos.toByteArray();
        } catch (IOException ioe) {
            throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe);
        }

        //was there any POST content
        if (bufRequestData != null) {
            //determine if exists mime database considers this binary data
            String contentType = request.getContentType();
            if (contentType != null) {
                //strip off any charset encoding info
                if (contentType.indexOf(";") > -1)
                    contentType = contentType.substring(0, contentType.indexOf(";"));

                MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
                //<atombeat>
                // this code will only encode the request data if the mimeType
                // is present in the mime table, and the mimeType is stated
                // as binary...

                //               if(mimeType != null)
                //               {
                //                  if(!mimeType.isXMLType())
                //                  {
                //                     //binary data
                //                     return new Base64Binary(bufRequestData);
                //                  }
                //               }

                // this code takes a more conservative position and assumes that
                // if the mime type is not present in the table, the request
                // data should be treated as binary, and should be encoded as 
                // base 64...

                if (mimeType == null || !mimeType.isXMLType()) {
                    return new Base64Binary(bufRequestData);
                }
                //</atombeat>               
            }

            //try and parse as an XML documemnt, otherwise fallback to returning the data as a string
            context.pushDocumentContext();
            try {
                //try and construct xml document from input stream, we use eXist's in-memory DOM implementation
                SAXParserFactory factory = SAXParserFactory.newInstance();
                factory.setNamespaceAware(true);
                //TODO : we should be able to cope with context.getBaseURI()            
                InputSource src = new InputSource(new ByteArrayInputStream(bufRequestData));
                SAXParser parser = factory.newSAXParser();
                XMLReader reader = parser.getXMLReader();
                MemTreeBuilder builder = context.getDocumentBuilder();
                DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
                reader.setContentHandler(receiver);
                reader.parse(src);
                Document doc = receiver.getDocument();
                return (NodeValue) doc.getDocumentElement();
            } catch (ParserConfigurationException e) {
                //do nothing, we will default to trying to return a string below
            } catch (SAXException e) {
                //do nothing, we will default to trying to return a string below
            } catch (IOException e) {
                //do nothing, we will default to trying to return a string below
            } finally {
                context.popDocumentContext();
            }

            //not a valid XML document, return a string representation of the document
            String encoding = request.getCharacterEncoding();
            if (encoding == null) {
                encoding = "UTF-8";
            }
            try {
                String s = new String(bufRequestData, encoding);
                return new StringValue(s);
            } catch (IOException e) {
                throw new XPathException(this, "An IO exception ocurred: " + e.getMessage(), e);
            }
        } else {
            //no post data
            return Sequence.EMPTY_SEQUENCE;
        }
    } else {
        throw new XPathException(this, "Variable $request is not bound to a Request object.");
    }
}

From source file:org.beepcore.beep.example.Beepd.java

public static void main(String[] argv) {
    File config = new File("config.xml");

    for (int i = 0; i < argv.length; ++i) {
        if (argv[i].equalsIgnoreCase("-config")) {
            config = new File(argv[++i]);
            if (config.exists() == false) {
                System.err.println("Beepd: Error file " + config.getAbsolutePath() + " does not exist");
                return;
            }//from  ww w .j  a v a  2  s  . co m
        } else {
            System.err.println(usage);
            return;
        }
    }

    Document doc;
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = builder.parse(new FileInputStream(config));
    } catch (ParserConfigurationException e) {
        System.err.println("Beepd: Error parsing config\n" + e.getMessage());
        return;
    } catch (SAXException e) {
        System.err.println("Beepd: Error parsing config\n" + e.getMessage());
        return;
    } catch (IOException e) {
        System.err.println("Beepd: Error parsing config\n" + e.getMessage());
        return;
    }

    // Parse the configuration file
    Collection servers;
    try {
        servers = parseConfig(doc.getDocumentElement());
    } catch (Exception e) {
        System.err.println(e.getMessage());
        return;
    }

    // Start the servers listening
    Iterator i = servers.iterator();
    while (i.hasNext()) {
        ((Beepd) i.next()).start();
    }

    System.out.println("Beepd: started");
}

From source file:org.bigbluebutton.impl.BBBProxyImpl.java

/** Make an API call */
public static Map<String, Object> doAPICall(String query) {
    Map<String, Object> response = new HashMap<String, Object>();

    StringBuilder urlStr = new StringBuilder(query);
    try {/* ww  w . jav a 2 s  . c om*/
        // open connection
        log.debug("doAPICall.call: " + query);

        URL url = new URL(urlStr.toString());
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setUseCaches(false);
        httpConnection.setDoOutput(true);
        httpConnection.setRequestMethod("GET");
        httpConnection.connect();

        int responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // read response
            InputStreamReader isr = null;
            BufferedReader reader = null;
            StringBuilder xml = new StringBuilder();
            try {
                isr = new InputStreamReader(httpConnection.getInputStream(), "UTF-8");
                reader = new BufferedReader(isr);
                String line = reader.readLine();
                while (line != null) {
                    if (!line.startsWith("<?xml version=\"1.0\"?>"))
                        xml.append(line.trim());
                    line = reader.readLine();
                }
            } finally {
                if (reader != null)
                    reader.close();
                if (isr != null)
                    isr.close();
            }
            httpConnection.disconnect();

            // parse response
            log.debug("doAPICall.responseXml: " + xml);
            //Patch to fix the NaN error
            String stringXml = xml.toString();
            stringXml = stringXml.replaceAll(">.\\s+?<", "><");

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder;
            try {
                docBuilder = docBuilderFactory.newDocumentBuilder();
                Document dom = null;
                dom = docBuilder.parse(new InputSource(new StringReader(stringXml)));

                response = getNodesAsMap(dom, "response");
                log.debug("doAPICall.responseMap: " + response);

                String returnCode = (String) response.get("returncode");
                if (BBBProxy.APIRESPONSE_FAILED.equals(returnCode)) {
                    log.debug("doAPICall." + (String) response.get("messageKey") + ": Message="
                            + (String) response.get("message"));
                }

            } catch (ParserConfigurationException e) {
                log.debug("Failed to initialise BaseProxy: " + e.getMessage());
            }

        } else {
            log.debug("doAPICall.HTTPERROR: Message=" + "BBB server responded with HTTP status code "
                    + responseCode);
        }

    } catch (IOException e) {
        log.debug("doAPICall.IOException: Message=" + e.getMessage());
    } catch (SAXException e) {
        log.debug("doAPICall.SAXException: Message=" + e.getMessage());
    } catch (IllegalArgumentException e) {
        log.debug("doAPICall.IllegalArgumentException: Message=" + e.getMessage());
    } catch (Exception e) {
        log.debug("doAPICall.Exception: Message=" + e.getMessage());
    }
    return response;
}

From source file:org.callimachusproject.xproc.DecodeTextStep.java

public void run() throws SaxonApiException {
    try {/*from w w w .  j a  va2  s . co  m*/
        while (source.moreDocuments()) {
            String text = decodeText(source.read());

            Document doc = DocumentFactory.newInstance().newDocument();
            doc.setDocumentURI(doc.getBaseURI());
            Element data = doc.createElementNS(XPROC_STEP, DATA);
            data.setAttribute("content-type", contentType);
            data.appendChild(doc.createTextNode(text));
            doc.appendChild(data);
            result.write(runtime.getProcessor().newDocumentBuilder().wrap(doc));
        }
    } catch (ParserConfigurationException e) {
        throw XProcException.dynamicError(30, step.getNode(), e, e.getMessage());
    } catch (UnsupportedEncodingException uee) {
        throw XProcException.stepError(10, uee);
    } catch (DecoderException e) {
        throw XProcException.dynamicError(30, step.getNode(), e, e.getMessage());
    }
}

From source file:org.chiba.xml.xforms.ChibaBean.java

/**
 * reads serialized host document from ObjectInputStream and parses the resulting String
 * to a DOM Document. After that the host document is passed to the processor. init() is NOT yet
 * called on the processor to allow an using application to do its own configuration work (like
 * setting of baseURI and passing of context params).
 *
 * todo: rethink the question of the baseURI - is this still necessary when deaserializing? Presumably yes to further allow dynamic resolution.
 * @param objectInput/*from  www.j  av a2  s .c om*/
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("deserializing XForms host document");
    }
    String read = objectInput.readUTF();
    Document host = null;
    try {
        host = DOMUtil.parseString(read, true, false);
        setXMLContainer(host.getDocumentElement());
    } catch (ParserConfigurationException e) {
        throw new IOException("Parser misconfigured: " + e.getMessage());
    } catch (SAXException e) {
        throw new IOException("Parsing failed: " + e.getMessage());
    } catch (XFormsException e) {
        throw new IOException("An XForms error occurred when passing the host document: " + e.getMessage());
    }

}

From source file:org.codehaus.groovy.grails.plugins.CorePluginFinder.java

@SuppressWarnings("rawtypes")
private void loadCorePluginsFromResources(Resource[] resources) throws IOException {

    LOG.debug("Attempting to load [" + resources.length + "] core plugins");
    try {/*from   ww w . j a  va 2s  . com*/
        XmlSlurper slurper = new XmlSlurper();
        for (Resource resource : resources) {
            InputStream input = null;

            try {
                input = resource.getInputStream();
                final GPathResult result = slurper.parse(input);
                GPathResult pluginClass = (GPathResult) result.getProperty("type");
                if (pluginClass.size() == 1) {
                    final String pluginClassName = pluginClass.text();
                    if (StringUtils.hasText(pluginClassName)) {
                        loadCorePlugin(pluginClassName, resource, result);
                    }
                } else {
                    final Iterator iterator = pluginClass.nodeIterator();
                    while (iterator.hasNext()) {
                        Node node = (Node) iterator.next();
                        final String pluginClassName = node.text();
                        if (StringUtils.hasText(pluginClassName)) {
                            loadCorePlugin(pluginClassName, resource, result);
                        }
                    }
                }
            } finally {
                if (input != null) {
                    input.close();
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new GrailsConfigurationException("XML parsing error loading core plugins: " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new GrailsConfigurationException("XML parsing error loading core plugins: " + e.getMessage(), e);
    }
}

From source file:org.codehaus.groovy.grails.plugins.DefaultGrailsPluginManager.java

private void doWebDescriptor(InputStream inputStream, Writer target) {
    checkInitialised();//from ww w. j  a  v  a2s.c  o  m
    try {
        Document document = DOMBuilder.parse(new InputStreamReader(inputStream));
        Element documentElement = document.getDocumentElement();

        for (GrailsPlugin plugin : pluginList) {
            if (plugin.supportsCurrentScopeAndEnvironment()) {
                plugin.doWithWebDescriptor(documentElement);
            }
        }

        boolean areServlet3JarsPresent = ClassUtils.isPresent("javax.servlet.AsyncContext",
                Thread.currentThread().getContextClassLoader());
        String servletVersion = application.getMetadata().getServletVersion();
        if (areServlet3JarsPresent && GrailsVersionUtils.supportsAtLeastVersion(servletVersion, "3.0")) {
            new Servlet3AsyncWebXmlProcessor().process(documentElement);
        }
        writeWebDescriptorResult(documentElement, target);
    } catch (ParserConfigurationException e) {
        throw new PluginException(
                "Unable to configure web.xml due to parser configuration problem: " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new PluginException("XML parsing error configuring web.xml: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PluginException("Unable to read web.xml" + e.getMessage(), e);
    }
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public DocumentBuilder newDocumentBuilder() throws GalleyMavenXMLException {
    try {/*from  w w w .j av a 2s .c o m*/
        return dbFactory.newDocumentBuilder();
    } catch (final ParserConfigurationException e) {
        throw new GalleyMavenXMLException("Failed to create DocumentBuilder: %s", e, e.getMessage());
    }
}

From source file:org.commonvox.hbase_column_manager.TestRepositoryAdmin.java

private void validateXmlAgainstXsd(File xmlFile) throws IOException {
    Document hsaDocument = null;// w ww .j a v a 2s.  c  o  m
    Schema hsaSchema = null;
    try {
        hsaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    } catch (ParserConfigurationException pce) {
        fail(TEST_ENVIRONMENT_SETUP_PROBLEM + " parser config exception thrown: " + pce.getMessage());
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " SAX exception thrown while loading test document: "
                + se.getMessage());
    }
    try {
        hsaSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(Paths
                        .get(ClassLoader.getSystemResource(XmlSchemaGenerator.DEFAULT_OUTPUT_FILE_NAME).toURI())
                        .toFile());
    } catch (URISyntaxException ue) {
        fail(TEST_ENVIRONMENT_SETUP_PROBLEM + " URI syntax exception thrown: " + ue.getMessage());
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " SAX exception thrown while loading XML-schema: " + se.getMessage());
    }
    // validate against XSD
    try {
        hsaSchema.newValidator().validate(new DOMSource(hsaDocument));
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " exported HSA file is invalid with respect to " + "XML schema: "
                + se.getMessage());
    }
}