Example usage for org.xml.sax SAXException getMessage

List of usage examples for org.xml.sax SAXException getMessage

Introduction

In this page you can find the example usage for org.xml.sax SAXException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Return a detail message for this exception.

Usage

From source file:org.limy.common.xml.XmlUtils.java

/**
 * XML??DOM Document???//from www  . java  2s  . com
 * @param in XML
 * @return DOM Document
 * @throws IOException I/O
 */
public static Document parseDoc(InputStream in) throws IOException {
    try {
        return createBuilder().parse(in);
    } catch (SAXException e) {
        IOException exception = new IOException(e.getMessage());
        exception.setStackTrace(e.getStackTrace());
        throw exception;
    }
}

From source file:org.limy.common.xml.XmlUtils.java

/**
 * XML??XMLElement???/*from  ww w . j a  va  2 s  . c o m*/
 * @param in XML
 * @return XMLElement
 * @throws IOException I/O
 */
public static XmlElement parse(InputStream in) throws IOException {
    try {
        Document document = createBuilder().parse(in);
        Element root = document.getDocumentElement();
        SimpleElement el = new SimpleElement(root.getNodeName());
        parse(el, root);
        return el;
    } catch (SAXException e) {
        IOException exception = new IOException(e.getMessage());
        exception.setStackTrace(e.getStackTrace());
        throw exception;
    }
}

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void cmdImportNntpRssChannelConfig(HttpServletResponse response, MultiPartRequest mpRequest)
        throws ServletException, IOException {

    Writer writer = response.getWriter();
    writeHeader(writer, TAB_CONFIG);/*from w ww .ja  v a  2  s  .  co m*/

    ChannelManager channelManager = (ChannelManager) getServletContext()
            .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER);

    writer.write("<b>Import status</b><p>");

    List errors = new ArrayList();
    int channelsAdded = 0;

    // Parse XML
    try {
        DocumentBuilder db = AppConstants.newDocumentBuilder();
        Document doc = db.parse(mpRequest.getInputStream("file"));
        Element docElm = doc.getDocumentElement();
        NodeList channels = docElm.getElementsByTagName("channel");

        for (int channelCount = 0; channelCount < channels.getLength(); channelCount++) {
            Element chanElm = (Element) channels.item(channelCount);

            String name = chanElm.getAttribute("name");
            String urlString = chanElm.getAttribute("url");
            boolean historical = false;
            Node historicalNode = chanElm.getAttributeNode("historical");
            if (historicalNode != null) {
                historical = historicalNode.getNodeValue().equalsIgnoreCase("true");
            }

            long expiration = Channel.EXPIRATION_KEEP;
            Node expirationNode = chanElm.getAttributeNode("expiration");
            if (expirationNode != null) {
                expiration = Long.parseLong(expirationNode.getNodeValue());
            } else {
                expiration = historical ? Channel.EXPIRATION_KEEP : 0;
            }

            String categoryName = chanElm.getAttribute("category");

            // Check name...
            List currentErrors = new ArrayList();
            Channel existingChannel = channelManager.channelByName(name);

            if (name.length() == 0) {
                currentErrors.add("Channel with empty name - URL=" + urlString);
            } else if (name.indexOf(' ') > -1) {
                currentErrors.add("Channel name cannot contain spaces - name=" + name);
            } else if (existingChannel != null) {
                currentErrors.add("Channel name " + name + " is already is use");
            }

            if (urlString.length() == 0) {
                currentErrors.add("URL cannot be empty, channel name=" + name);
            } else if (urlString.equals("http://") || urlString.equals("https://")) {
                currentErrors.add("You must specify a URL, channel name=" + name);
            } else if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
                currentErrors.add("Only URLs starting http:// or https:// are supported, channel name=" + name
                        + ", url=" + urlString);
            }

            if (existingChannel == null) {

                Channel newChannel = null;
                if (currentErrors.size() == 0) {
                    try {
                        newChannel = new Channel(name, urlString);
                        //                     newChannel.setHistorical(historical);
                        newChannel.setExpiration(expiration);
                        channelManager.addChannel(newChannel);
                        channelsAdded++;
                    } catch (MalformedURLException me) {
                        errors.add("Channel " + name + " - URL (" + urlString + ") is malformed");
                    }
                }

                if (categoryName.length() > 0) {
                    //Handle category...
                    Category category = channelManager.categoryByName(categoryName);
                    if (category == null) {
                        // Need to create category...
                        category = new Category();
                        category.setName(categoryName);
                        channelManager.addCategory(category);
                    }
                    category.addChannel(newChannel);
                    newChannel.setCategory(category);
                    newChannel.save();
                }

                // Removed channel validation... channels will be validated
                // on next iteration of channel poller - will be highlighted
                // in channel list if invalid
                // Validate channel...
                //               if(Channel.isValid(new URL(urlString))) {
                //// Add channel...
                //                  Channel newChannel = null;
                //                  if(currentErrors.size() == 0) {
                //                     try {
                //                        newChannel = new Channel(name, urlString);
                //                        newChannel.setHistorical(historical);
                //                        channelManager.addChannel(newChannel);
                //                        channelsAdded++;
                //                     } catch(MalformedURLException me) {
                //                        errors.add("Channel " + name + " - URL (" 
                //                           + urlString + ") is malformed");
                //                     }
                //                  }            
                //                  
                //               } else {
                //// URL points to invalid document
                //                  errors.add("Channel " + name + "'s URL (" + urlString + ") "
                //                     + "points to an invalid document");
                //               }
            }

            errors.addAll(currentErrors);

        }
    } catch (SAXException se) {
        errors.add("There was an error parsing your channel file:<br>" + se.getMessage());
    } catch (ParserConfigurationException pce) {
        errors.add("There was a problem reading your channelf file:<br>" + pce.getMessage());
    }

    // Display any errors encountered during parsing...
    if (errors.size() > 0) {
        writer.write("Problems were encountered while adding channels.<p>");
        writeErrors(writer, errors);

        if (channelsAdded > 0) {
            writer.write("<p>" + channelsAdded + " channel(s) were successfully imported.");
        }
    } else {
        if (channelsAdded > 0) {
            writer.write("<p>" + channelsAdded + " channel(s) were successfully imported.");
        } else {
            writer.write("The configuration file did not contain any channels!");
        }
    }

    writeFooter(writer);
    writer.flush();

}

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void cmdImportOpmlChannelConfigValidate(HttpServletResponse response, MultiPartRequest mpRequest)
        throws ServletException, IOException {

    Writer writer = response.getWriter();
    writeHeader(writer, TAB_CONFIG);//w  w w  .  j a v  a 2  s  . c  o  m

    writeCheckboxSelector(writer, "checkAllImport", "import", "channels");

    writer.write("<b>mySubscriptions.opml validation</b><p>");

    List errors = new ArrayList();

    // Parse XML
    try {
        DocumentBuilder db = AppConstants.newDocumentBuilder();
        Document doc = db.parse(mpRequest.getInputStream("file"));
        Element docElm = doc.getDocumentElement();

        NodeList channels = docElm.getElementsByTagName("outline");
        if (channels.getLength() > 0) {

            writer.write("<form name='channels' action='?action=importopml' method='POST'>");
            writer.write("<table class='tableBorder'><tr><th>Import<br>"
                    + "<input type='checkbox' name='changeImport' onClick='checkAllImport(this);' checked>"
                    + "</th><th>Channel Name</th><th>Expiration" + "</th><th>URL</th></tr>");

            int channelCount = 0;
            for (int chlLoopCounter = 0; chlLoopCounter < channels.getLength(); chlLoopCounter++) {
                Element chanElm = (Element) channels.item(chlLoopCounter);

                String name = fixChannelName(chanElm.getAttribute("title"));
                String urlString = chanElm.getAttribute("xmlUrl");
                if (urlString == null || urlString.length() == 0) {
                    urlString = chanElm.getAttribute("xmlurl");
                }

                if (urlString == null || urlString.length() == 0) {
                    continue;
                }

                if (name.length() == 0) {
                    name = createChannelName(urlString);
                }

                String rowClass = (((channelCount % 2) == 1) ? "row1" : "row2");

                writer.write("<tr>" + "<td class='" + rowClass
                        + "' align='center'><input type='checkbox' name='import" + channelCount
                        + "' checked></td>" + "<td class='" + rowClass
                        + "'><input type='value' size='50' name='name" + channelCount + "' value='"
                        + HTMLHelper.escapeString(name) + "'></td>" + "<td class='" + rowClass
                        + "' align='center'>" + "<select name='expiration" + channelCount + "'>");

                long expiration = Channel.EXPIRATION_KEEP;

                writeOption(writer, "Keep all items", Channel.EXPIRATION_KEEP, expiration);
                writeOption(writer, "Keep only current items", 0, expiration);
                writeOption(writer, "Keep items for 1 day", (1000 * 60 * 60 * 24 * 1), expiration);
                writeOption(writer, "Keep items for 2 days", (1000 * 60 * 60 * 24 * 2), expiration);
                writeOption(writer, "Keep items for 4 days", (1000 * 60 * 60 * 24 * 4), expiration);
                writeOption(writer, "Keep items for 1 week", (1000 * 60 * 60 * 24 * 7), expiration);
                writeOption(writer, "Keep items for 2 weeks", (1000 * 60 * 60 * 24 * 14), expiration);
                writeOption(writer, "Keep items for 4 weeks", (1000 * 60 * 60 * 24 * 28), expiration);

                writer.write("</select></td>" + "<td class='" + rowClass + "' ><input type='hidden' name='url"
                        + channelCount + "' value='" + HTMLHelper.escapeString(urlString) + "'>"
                        + HTMLHelper.escapeString(urlString) + "</td></tr>\n");

                channelCount++;
            }

            writer.write(
                    "<tr><td align='center' class='row2' colspan='4'><input type='submit' value='Import Channels'></td></tr>");
            writer.write("</table></form>");
        } else {
            writer.write(
                    "Your mySubscriptions.opml file did not contain any channels, or was in an invalid format.<p>");
        }

    } catch (SAXException se) {
        errors.add("There was an error parsing your channel file:<br>" + se.getMessage());
    } catch (ParserConfigurationException pce) {
        errors.add("There was a problem reading your channelf file:<br>" + pce.getMessage());
    }

    // Display any errors encountered during parsing...
    if (errors.size() > 0) {
        writer.write("Problems were encountered while adding channels.<p>");
        writeErrors(writer, errors);
    }

    writeFooter(writer);
    writer.flush();

}

From source file:org.mule.config.spring.InvalidSchemaValidationTestCase.java

@Test
public void testJdbcInvalidPollingFrequencyInOutboundEndpoint() throws SAXException, IOException {
    addSchema("http://www.mulesoft.org/schema/mule/jdbc", "META-INF/mule-jdbc.xsd");
    addSchema("http://www.mulesoft.org/schema/mule/test",
            "http://www.mulesoft.org/schema/mule/test/3.2/mule-test.xsd");
    try {//  w ww .j  a  va 2 s .c o  m
        doTest("org/mule/config/spring/schema-validation-jdbc-invalid-polling-frequency.xml");
    } catch (SAXException e) {
        // Check that the pollingFrequency exception is because of the outbound endpoint and not the inbound
        assertTrue(e.getMessage() != null && e.getMessage().contains("jdbc:outbound-endpoint"));
    }
}

From source file:org.n52.ifgicopter.spf.xml.SchematronValidator.java

/**
 * Here the real validation process is started.
 * //from w w  w  .  java 2  s.c om
 * @return true if no schematron rule was violated.
 */
public boolean validate() {
    Transform trans = new Transform();

    /*
     * transform the schematron
     */
    String[] arguments = new String[] { "-x", "org.apache.xerces.parsers.SAXParser", "-w1", "-o",
            DOCS_FOLDER + "/tmp/tmp.xsl", this.schematronFile, DOCS_FOLDER + "/iso_svrl_for_xslt2.xsl",
            "generate-paths=yes" };
    trans.doTransform(arguments, "java net.sf.saxon.Transform");

    /*
     * transform the instance
     */
    String report = DOCS_FOLDER + "/tmp/"
            + this.xmlInstanceFile.substring(this.xmlInstanceFile.lastIndexOf("/") + 1) + ".report.xml";
    arguments = new String[] { "-x", "org.apache.xerces.parsers.SAXParser", "-w1", "-o", report,
            this.xmlInstanceFile, DOCS_FOLDER + "/tmp/tmp.xsl" };
    trans.doTransform(arguments, "java net.sf.saxon.Transform");

    LocatorImpl locator = new LocatorImpl();
    /*
     * an extension of DefaultHandler
     */
    DefaultHandler handler = new DefaultHandler() {

        private String failTmp;
        private Locator locator2;
        private boolean insideFail = false;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (qName.endsWith("failed-assert")) {
                this.failTmp = "Assertion error at \"" + attributes.getValue("test") + "\" (line "
                        + this.locator2.getLineNumber() + "): ";
                this.insideFail = true;
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (qName.endsWith("failed-assert")) {
                SchematronValidator.this.assertFails.add(this.failTmp);
                this.failTmp = null;
                this.insideFail = false;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (this.insideFail) {
                this.failTmp += new String(ch, start, length).trim();
            }
        }

        @Override
        public void setDocumentLocator(Locator l) {
            this.locator2 = l;
        }

    };
    handler.setDocumentLocator(locator);

    try {
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(new File(report), handler);
    } catch (SAXException e) {
        log.warn(e.getMessage(), e);
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        log.warn(e.getMessage(), e);
    }

    return (this.assertFails.size() == 0) ? true : false;
}

From source file:org.n52.wps.server.handler.RequestHandler.java

/**
 * Handles requests of type HTTP_POST (currently executeProcess). A Document
 * is used to represent the client input. This Document must first be parsed
 * from an InputStream.//  www. java 2s .c om
 * 
 * @param is
 *            The client input
 * @param os
 *            The OutputStream to write the response to.
 * @throws ExceptionReport
 */
public RequestHandler(InputStream is, OutputStream os) throws ExceptionReport {
    String nodeName, localName, nodeURI, version = null;
    Document doc;
    this.os = os;

    boolean isCapabilitiesNode = false;

    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);

        // parse the InputStream to create a Document
        doc = fac.newDocumentBuilder().parse(is);

        // Get the first non-comment child.
        Node child = doc.getFirstChild();
        while (child.getNodeName().compareTo("#comment") == 0) {
            child = child.getNextSibling();
        }
        nodeName = child.getNodeName();
        localName = child.getLocalName();
        nodeURI = child.getNamespaceURI();
        Node versionNode = child.getAttributes().getNamedItem("version");

        /*
         * check for service parameter. this has to be present for all requests
         */
        Node serviceNode = child.getAttributes().getNamedItem("service");

        if (serviceNode == null) {
            throw new ExceptionReport("Parameter <service> not specified.",
                    ExceptionReport.MISSING_PARAMETER_VALUE, "service");
        } else {
            if (!serviceNode.getNodeValue().equalsIgnoreCase("WPS")) {
                throw new ExceptionReport("Parameter <service> not specified.",
                        ExceptionReport.INVALID_PARAMETER_VALUE, "service");
            }
        }

        isCapabilitiesNode = nodeName.toLowerCase().contains("capabilities");
        if (versionNode == null && !isCapabilitiesNode) {
            throw new ExceptionReport("Parameter <version> not specified.",
                    ExceptionReport.MISSING_PARAMETER_VALUE, "version");
        }
        //TODO: I think this can be removed, as capabilities requests do not have a version parameter (BenjaminPross)
        if (!isCapabilitiesNode) {
            //            version = child.getFirstChild().getTextContent();//.getNextSibling().getFirstChild().getNextSibling().getFirstChild().getNodeValue();
            version = child.getAttributes().getNamedItem("version").getNodeValue();
        }
        /*
         * check language, if not supported, return ExceptionReport
         * Fix for https://bugzilla.52north.org/show_bug.cgi?id=905
         */
        Node languageNode = child.getAttributes().getNamedItem("language");
        if (languageNode != null) {
            String language = languageNode.getNodeValue();
            Request.checkLanguageSupported(language);
        }
    } catch (SAXException e) {
        throw new ExceptionReport("There went something wrong with parsing the POST data: " + e.getMessage(),
                ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (IOException e) {
        throw new ExceptionReport("There went something wrong with the network connection.",
                ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (ParserConfigurationException e) {
        throw new ExceptionReport("There is a internal parser configuration error",
                ExceptionReport.NO_APPLICABLE_CODE, e);
    }
    //Fix for Bug 904 https://bugzilla.52north.org/show_bug.cgi?id=904
    if (!isCapabilitiesNode && version == null) {
        throw new ExceptionReport("Parameter <version> not specified.", ExceptionReport.MISSING_PARAMETER_VALUE,
                "version");
    }
    if (!isCapabilitiesNode && !version.equals(Request.SUPPORTED_VERSION)) {
        throw new ExceptionReport("Version not supported.", ExceptionReport.INVALID_PARAMETER_VALUE, "version");
    }
    // get the request type
    if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("Execute")) {
        req = new ExecuteRequest(doc);
        setResponseMimeType((ExecuteRequest) req);
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("GetCapabilities")) {
        req = new CapabilitiesRequest(doc);
        this.responseMimeType = "text/xml";
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("DescribeProcess")) {
        req = new DescribeProcessRequest(doc);
        this.responseMimeType = "text/xml";

    } else if (!localName.equals("Execute")) {
        throw new ExceptionReport(
                "The requested Operation not supported or not applicable to the specification: " + nodeName,
                ExceptionReport.OPERATION_NOT_SUPPORTED, localName);
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE)) {
        throw new ExceptionReport("specified namespace is not supported: " + nodeURI,
                ExceptionReport.INVALID_PARAMETER_VALUE);
    }
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.HtmlParser.java

public HtmlParser() {
    super(new HTMLConfiguration());
    try {//from  ww w. j  a va2s  . c o m
        // make sure we do not download the DTD URI
        setFeature("http://xml.org/sax/features/validation", false);
        setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (SAXException e) {
        log.debug("Could not switch parser to non-validating: " + e.getMessage());
    }
}

From source file:org.nuxeo.ecm.platform.xmlrpc.connector.NuxeoXmlRpcServletServer.java

/**
 * Same as base class method, but with an additionnal parameter
 * that contains component name extracted from request.
 *
 * @param pConfig//  w  w w.  ja v a2 s  .com
 * @param pStream
 * @param handlerPrefix componentName extracted from request
 * @return
 * @throws XmlRpcException
 */
protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig, InputStream pStream,
        final String handlerPrefix) throws XmlRpcException {

    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);
    try {
        xr.parse(new InputSource(pStream));
    } catch (SAXException e) {
        Exception ex = e.getException();
        if (ex != null && ex instanceof XmlRpcException) {
            throw (XmlRpcException) ex;
        }
        throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    return new XmlRpcRequest() {
        public XmlRpcRequestConfig getConfig() {
            return pConfig;
        }

        public String getMethodName() {
            String mName = parser.getMethodName();
            if (handlerPrefix == null || "".equals(handlerPrefix)) {
                return mName;
            } else {
                return handlerPrefix + '.' + mName;
            }
        }

        public int getParameterCount() {
            return params == null ? 0 : params.size();
        }

        public Object getParameter(int pIndex) {
            return params.get(pIndex);
        }
    };
}

From source file:org.ojbc.pep.PolicyDecisionPoint.java

/**
 * Evaluate a XACML request against the policies
 * @param request the request/*from  w  w w  .j av a  2 s.  c  o  m*/
 * @return the result
 */
public XacmlResponse evaluate(XacmlRequest request) {
    XacmlResponse ret = new XacmlResponse();
    AbstractRequestCtx requestCtx;
    try {
        requestCtx = RequestCtxFactory.getFactory()
                .getRequestCtx(request.getRequestDocument().getDocumentElement());
        ResponseCtx responseCtx = pdp.evaluate(requestCtx);
        Set<AbstractResult> resultSet = responseCtx.getResults();
        ret.setDocument(parseResponseDocument(responseCtx.encode()));
        if (resultSet.size() > 1) {
            LOG.warn("WARNING: Result set contains multiple results. " + resultSet);
        }
        for (AbstractResult ar : resultSet) {
            ret.addResult(new XacmlResult(ar.getDecision()));
        }
    } catch (ParsingException e) {
        LOG.error("Invalid request  : " + e.getMessage());
        String error = "Invalid request  : " + e.getMessage();
        ArrayList<String> code = new ArrayList<String>();
        code.add(Status.STATUS_SYNTAX_ERROR);
        Status status = new Status(code, error);
        org.wso2.balana.ctx.xacml3.Result r = new org.wso2.balana.ctx.xacml3.Result(
                AbstractResult.DECISION_INDETERMINATE, status);
        try {
            ret.addResult(new XacmlResult(r.getDecision()));
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
    } catch (SAXException se) {
        LOG.error("Invalid xml in response  : " + se.getMessage());
        String error = "Invalid xml in response  : " + se.getMessage();
        ArrayList<String> code = new ArrayList<String>();
        code.add(Status.STATUS_PROCESSING_ERROR);
        Status status = new Status(code, error);
        org.wso2.balana.ctx.xacml3.Result r = new org.wso2.balana.ctx.xacml3.Result(
                AbstractResult.DECISION_INDETERMINATE, status);
        try {
            ret.addResult(new XacmlResult(r.getDecision()));
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
    }
    return ret;
}