Example usage for org.xml.sax SAXException getException

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

Introduction

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

Prototype

public Exception getException() 

Source Link

Document

Return the embedded exception, if any.

Usage

From source file:org.apache.geode.internal.cache.xmlcache.CacheXmlParser.java

/**
 * Parses XML data and from it creates an instance of <code>CacheXmlParser</code> that can be used
 * to {@link #create}the {@link Cache}, etc.
 *
 * @param is the <code>InputStream</code> of XML to be parsed
 *
 * @return a <code>CacheXmlParser</code>, typically used to create a cache from the parsed XML
 *
 * @throws CacheXmlException Something went wrong while parsing the XML
 *
 * @since GemFire 4.0//www . j  av a 2  s.  com
 *
 */
public static CacheXmlParser parse(InputStream is) {

    /**
     * The API doc http://java.sun.com/javase/6/docs/api/org/xml/sax/InputSource.html for the SAX
     * InputSource says: "... standard processing of both byte and character streams is to close
     * them on as part of end-of-parse cleanup, so applications should not attempt to re-use such
     * streams after they have been handed to a parser."
     *
     * In order to block the parser from closing the stream, we wrap the InputStream in a filter,
     * i.e., UnclosableInputStream, whose close() function does nothing.
     * 
     */
    class UnclosableInputStream extends BufferedInputStream {
        public UnclosableInputStream(InputStream stream) {
            super(stream);
        }

        @Override
        public void close() {
        }
    }

    CacheXmlParser handler = new CacheXmlParser();
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, true);
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        UnclosableInputStream bis = new UnclosableInputStream(is);
        try {
            SAXParser parser = factory.newSAXParser();
            // Parser always reads one buffer plus a little extra worth before
            // determining that the DTD is there. Setting mark twice the parser
            // buffer size.
            bis.mark((Integer) parser.getProperty(BUFFER_SIZE) * 2);
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
            parser.parse(bis, new DefaultHandlerDelegate(handler));
        } catch (CacheXmlException e) {
            if (null != e.getCause() && e.getCause().getMessage().contains(DISALLOW_DOCTYPE_DECL_FEATURE)) {
                // Not schema based document, try dtd.
                bis.reset();
                factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, false);
                SAXParser parser = factory.newSAXParser();
                parser.parse(bis, new DefaultHandlerDelegate(handler));
            } else {
                throw e;
            }
        }
        return handler;
    } catch (Exception ex) {
        if (ex instanceof CacheXmlException) {
            while (true /* ex instanceof CacheXmlException */) {
                Throwable cause = ex.getCause();
                if (!(cause instanceof CacheXmlException)) {
                    break;
                } else {
                    ex = (CacheXmlException) cause;
                }
            }
            throw (CacheXmlException) ex;
        } else if (ex instanceof SAXException) {
            // Silly JDK 1.4.2 XML parser wraps RunTime exceptions in a
            // SAXException. Pshaw!
            SAXException sax = (SAXException) ex;
            Exception cause = sax.getException();
            if (cause instanceof CacheXmlException) {
                while (true /* cause instanceof CacheXmlException */) {
                    Throwable cause2 = cause.getCause();
                    if (!(cause2 instanceof CacheXmlException)) {
                        break;
                    } else {
                        cause = (CacheXmlException) cause2;
                    }
                }
                throw (CacheXmlException) cause;
            }
        }
        throw new CacheXmlException(LocalizedStrings.CacheXmlParser_WHILE_PARSING_XML.toLocalizedString(), ex);
    }
}

From source file:org.apache.jackrabbit.jcr2spi.SessionImpl.java

/**
 * @see javax.jcr.Session#importXML(String, java.io.InputStream, int)
 *//*from w  w w. jav a2 s.  c  o  m*/
@Override
public void importXML(String parentAbsPath, InputStream in, int uuidBehavior)
        throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException,
        VersionException, InvalidSerializedDataException, LockException, RepositoryException {
    // NOTE: checks are performed by 'getImportContentHandler'
    ImportHandler handler = (ImportHandler) getImportContentHandler(parentAbsPath, uuidBehavior);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

        SAXParser parser = factory.newSAXParser();
        parser.parse(new InputSource(in), handler);
    } catch (SAXException se) {
        // check for wrapped repository exception
        Exception e = se.getException();
        if (e != null && e instanceof RepositoryException) {
            throw (RepositoryException) e;
        } else {
            String msg = "failed to parse XML stream";
            log.debug(msg);
            throw new InvalidSerializedDataException(msg, se);
        }
    } catch (ParserConfigurationException e) {
        throw new RepositoryException("SAX parser configuration error", e);
    } finally {
        in.close(); // JCR-2903
    }
}

From source file:org.apache.xmlrpc.server.XmlRpcStreamServer.java

protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig, InputStream pStream)
        throws XmlRpcException {
    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);//from  ww  w .j av a  2s.  c  o  m
    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() {
            return parser.getMethodName();
        }

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

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

From source file:org.architecturerules.configuration.xml.DigesterConfigurationFactory.java

void processProperties(final String xml) throws IOException, SAXException, ParserConfigurationException {

    final Digester digester = getDigester();
    digester.addObjectCreate(XmlConfiguration.properties, Properties.class);
    digester.addCallMethod(XmlConfiguration.property, "put", 2);
    digester.addCallParam(XmlConfiguration.property, 0, "key");
    digester.addCallParam(XmlConfiguration.property, 1, "value");

    final StringReader reader = new StringReader(xml.trim());

    final Object o;

    try {//from   w w w  .ja  v  a 2  s.co m

        o = digester.parse(reader);
    } catch (SAXException e) {

        if (e.getException().toString().equals("java.lang.NullPointerException")) {

            throw new InvalidConfigurationException(
                    "Invalid XML configuration for <properties>. <property> must only contain both a key and a value attribute.",
                    e);
        }

        // at this time, I don't even know how to get to this path, but I'm sure some user will figure it out : P
        throw new InvalidConfigurationException(
                "Unable to parse XML configuration for <properties>: " + e.getMessage(), e);
    }

    if (o == null) {

        return;
    }

    final Properties properties = (Properties) o;

    addProperties(properties);
}

From source file:org.archive.crawler.restlet.XmlMarshaller.java

/**
 * Writes {@code content} as xml to {@code writer}. Recursively descends
 * into Maps, using keys as tag names. Iterates over items in arrays and
 * Iterables, using "value" as the tag name. Marshals simple object values
 * with {@link #toString()}. The result looks something like this:
 * /* w  ww .  j  av a  2  s. co m*/
 * <pre>
 * {@literal
 * <rootTag> <!-- root object is a Map -->
 *   <key1>simpleObjectValue1</key1>
 *   <key2>  <!-- /rootTag/key2 is another Map -->
 *     <subkey1>subvalue1</subkey1>
 *     <subkey2> <!-- an array or Iterable-->
 *       <value>item1Value</value>
 *       <value>item2Value</value>
 *     </subkey2>
 *     <subkey3>subvalue3</subkey3>
 *   </key2>
 * </rootTag>
 * }
 * </pre>
 * 
 * @param writer
 *            output writer
 * @param rootTag
 *            xml document root tag name
 * @param content
 *            data structure to marshal
 * @throws IOException 
 */
public static void marshalDocument(Writer writer, String rootTag, Object content) throws IOException {
    XmlWriter xmlWriter = getXmlWriter(writer);
    try {
        xmlWriter.startDocument();
        marshal(xmlWriter, rootTag, content);
        xmlWriter.endDocument(); // calls flush()
    } catch (SAXException e) {
        if (e.getException() instanceof IOException) {
            // e.g. broken tcp connection
            throw (IOException) e.getException();
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.carrot2.source.yahoo.YahooSearchService.java

/**
 * Parse the response stream, assuming it is XML.
 */// w w w. j a  v  a  2s  .c om
private static SearchEngineResponse parseResponseXML(final InputStream is) throws IOException {
    try {
        final XMLResponseParser parser = new XMLResponseParser();
        final XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();

        reader.setFeature("http://xml.org/sax/features/validation", false);
        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setContentHandler(parser);

        reader.parse(new InputSource(is));

        return parser.response;
    } catch (final SAXException e) {
        final Throwable cause = e.getException();
        if (cause != null && cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw new IOException("XML parsing exception: " + e.getMessage());
    } catch (final ParserConfigurationException e) {
        throw new IOException("Could not acquire XML parser.");
    }
}

From source file:org.castor.xmlctf.xmldiff.xml.XMLFileReader.java

/**
 * Reads an XML Document into an BaseNode from the provided file.
 *
 * @return the BaseNode/*from  ww  w. ja  v  a 2 s . c o  m*/
 * @throws java.io.IOException if any exception occurs during parsing
 */
public XMLNode read() throws java.io.IOException {
    XMLNode node = null;

    try {
        InputSource source = new InputSource();
        source.setSystemId(_location);
        source.setCharacterStream(new FileReader(_file));

        XMLContentHandler builder = new XMLContentHandler();

        _parser.setContentHandler(builder);
        _parser.parse(source);

        node = builder.getRoot();
    } catch (SAXException sx) {
        Exception nested = sx.getException();

        SAXParseException sxp = null;
        if (sx instanceof SAXParseException) {
            sxp = (SAXParseException) sx;
        } else if (nested != null && (nested instanceof SAXParseException)) {
            sxp = (SAXParseException) nested;
        } else {
            throw new NestedIOException(sx);
        }

        String err = new StringBuilder(sxp.toString()).append("\n - ").append(sxp.getSystemId())
                .append("; line: ").append(sxp.getLineNumber()).append(", column: ")
                .append(sxp.getColumnNumber()).toString();
        throw new NestedIOException(err, sx);
    }

    Root root = (Root) node;
    return root;
}

From source file:org.hippoecm.repository.impl.SessionDecorator.java

@Override
public void exportDereferencedView(String absPath, OutputStream out, boolean binaryAsLink, boolean noRecurse)
        throws IOException, PathNotFoundException, RepositoryException {
    try {/* ww  w .  ja  v a  2 s.  co m*/
        ContentHandler handler = getExportContentHandler(out);
        this.exportDereferencedView(absPath, handler, binaryAsLink, noRecurse);
    } catch (SAXException e) {
        Exception exception = e.getException();
        if (exception instanceof RepositoryException) {
            throw (RepositoryException) exception;
        } else if (exception instanceof IOException) {
            throw (IOException) exception;
        } else {
            throw new RepositoryException("Error serializing system view XML", e);
        }
    }
}

From source file:org.hippoecm.repository.impl.SessionDecorator.java

@Override
public void exportSystemView(String absPath, OutputStream out, boolean binaryAsLink, boolean noRecurse)
        throws IOException, PathNotFoundException, RepositoryException {
    try {// ww w.j  av a  2  s.c  om
        ContentHandler handler = getExportContentHandler(out);
        this.exportSystemView(absPath, handler, binaryAsLink, noRecurse);
    } catch (SAXException e) {
        Exception exception = e.getException();
        if (exception instanceof RepositoryException) {
            throw (RepositoryException) exception;
        } else if (exception instanceof IOException) {
            throw (IOException) exception;
        } else {
            throw new RepositoryException("Error serializing system view XML", e);
        }
    }
}

From source file:org.hippoecm.repository.impl.SessionDecorator.java

@Override
public void exportDocumentView(String absPath, OutputStream out, boolean binaryAsLink, boolean noRecurse)
        throws IOException, PathNotFoundException, RepositoryException {
    try {/*from   w w w.  j  a v a2  s.c  o m*/
        ContentHandler handler = new ToXmlContentHandler(out);
        exportDocumentView(absPath, handler, binaryAsLink, noRecurse);
    } catch (SAXException e) {
        Exception exception = e.getException();
        if (exception instanceof RepositoryException) {
            throw (RepositoryException) exception;
        } else if (exception instanceof IOException) {
            throw (IOException) exception;
        } else {
            throw new RepositoryException("Error serializing document view XML", e);
        }
    }
}