Example usage for org.xml.sax XMLReader parse

List of usage examples for org.xml.sax XMLReader parse

Introduction

In this page you can find the example usage for org.xml.sax XMLReader parse.

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:org.eclipse.swordfish.plugins.compression.CompressorImpl.java

public Source asUncompressedSource(Source src) {
    try {//w w  w  .ja v  a2 s . com
        String encoded = null;
        if (src instanceof DOMSource) {
            Node root = ((DOMSource) src).getNode();
            if (root instanceof Document) {
                root = ((Document) root).getDocumentElement();
            }
            Element rootElement = (Element) root;
            String qName = rootElement.getNodeName();
            String localName = qName.substring(qName.indexOf(":") + 1, qName.length());
            if (localName.equalsIgnoreCase(CompressionConstants.COMPRESSED_ELEMENT)) {
                Node node = rootElement.getFirstChild();
                if (node != null && node.getNodeType() == Node.TEXT_NODE) {
                    encoded = node.getNodeValue();
                }
            }
            if (null != encoded && encoded.length() > 0) {
                byte[] decoded = new Base64().decode(encoded.getBytes());
                InputStream is = new GZIPInputStream(new ByteArrayInputStream(decoded));
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = builder.parse(is);
                return new DOMSource(doc);
            } else {
                return src;
            }
        } else if (src instanceof StreamSource) {
            XMLReader xmlReader = XMLReaderFactory.createXMLReader();
            CompressedContentHandler ch = new CompressedContentHandler();
            xmlReader.setContentHandler(ch);
            xmlReader.parse(new InputSource(((StreamSource) src).getInputStream()));
            encoded = ch.getContent();
            if (null != encoded && encoded.length() > 0) {
                byte[] decoded = new Base64().decode(encoded.getBytes());
                InputStream is = new GZIPInputStream(new ByteArrayInputStream(decoded));
                return new StreamSource(is);
            } else {
                throw new SwordfishException("Payload is empty, cannot uncompress.");
            }
        } else {
            return asUncompressedSource(new SourceTransformer().toDOMSource(src));
        }
    } catch (Exception e) {
        LOG.error("Couldn't decompress source", e);
        throw new SwordfishException("Couldn't decompress source", e);
    }
}

From source file:org.entcore.feeder.aaf.BaseImportProcessing.java

protected void parse(final Handler<Message<JsonObject>> handler, final ImportProcessing importProcessing) {
    final String[] files = vertx.fileSystem().readDirSync(path, getFileRegex());
    final VoidHandler[] handlers = new VoidHandler[files.length + 1];
    handlers[handlers.length - 1] = new VoidHandler() {
        @Override/*  w  ww .j  a  v  a2 s . c  o m*/
        protected void handle() {
            next(handler, importProcessing);
        }
    };
    Arrays.sort(files);
    for (int i = files.length - 1; i >= 0; i--) {
        final int j = i;
        handlers[i] = new VoidHandler() {
            @Override
            protected void handle() {
                try {
                    String file = files[j];
                    log.info("Parsing file : " + file);
                    byte[] encoded = Files.readAllBytes(Paths.get(file));
                    String content = UNESCAPE_AAF.translate(new String(encoded, "UTF-8"));
                    InputSource in = new InputSource(new StringReader(content));
                    AAFHandler sh = new AAFHandler(BaseImportProcessing.this);
                    XMLReader xr = XMLReaderFactory.createXMLReader();
                    xr.setContentHandler(sh);
                    xr.setEntityResolver(new EntityResolver2() {
                        @Override
                        public InputSource getExternalSubset(String name, String baseURI)
                                throws SAXException, IOException {
                            return null;
                        }

                        @Override
                        public InputSource resolveEntity(String name, String publicId, String baseURI,
                                String systemId) throws SAXException, IOException {
                            return resolveEntity(publicId, systemId);
                        }

                        @Override
                        public InputSource resolveEntity(String publicId, String systemId)
                                throws SAXException, IOException {
                            if (systemId.equals("ficAlimMENESR.dtd")) {
                                Reader reader = new FileReader(path + File.separator + "ficAlimMENESR.dtd");
                                return new InputSource(reader);
                            } else {
                                return null;
                            }
                        }
                    });
                    xr.parse(in);
                    importer.flush(new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> message) {
                            if ("ok".equals(message.body().getString("status"))) {
                                handlers[j + 1].handle(null);
                            } else {
                                error(message, handler);
                            }
                        }
                    });
                } catch (Exception e) {
                    error(e, handler);
                }
            }
        };
    }
    handlers[0].handle(null);
}

From source file:org.everit.authentication.cas.CasAuthentication.java

/**
 * Returns the value of an XML element. This method is used to process the XMLs sent by the CAS
 * server./*  w w  w  . j av  a 2 s. c om*/
 *
 * @param xmlAsString
 *          the XML string to process
 * @param elementName
 *          the name of the queried element
 * @return the value assigned to the queried element name
 * @throws RuntimeException
 *           if any error occurs during the parsing of the XML string
 */
private String getTextForElement(final String xmlAsString, final String elementName) {

    XMLReader xmlReader;
    try {
        xmlReader = saxParserFactory.newSAXParser().getXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
        xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (SAXException | ParserConfigurationException e) {
        throw new RuntimeException("Unable to create XMLReader", e);
    }

    StringBuilder builder = new StringBuilder();

    DefaultHandler handler = new DefaultHandlerExt(builder, elementName);

    xmlReader.setContentHandler(handler);
    xmlReader.setErrorHandler(handler);

    try {
        xmlReader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return builder.toString();
}

From source file:org.everit.osgi.authentication.cas.internal.CasAuthenticationComponent.java

/**
 * Returns the value of an XML element. This method is used to process the XMLs sent by the CAS server.
 *
 * @param xmlAsString/*from  w  w  w  .j a  v a 2 s . c o  m*/
 *            the XML string to process
 * @param elementName
 *            the name of the queried element
 * @return the value assigned to the queried element name
 * @throws RuntimeException
 *             if any error occurs during the parsing of the XML string
 */
private String getTextForElement(final String xmlAsString, final String elementName) {

    XMLReader xmlReader;
    try {
        xmlReader = saxParserFactory.newSAXParser().getXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
        xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (final Exception e) {
        throw new RuntimeException("Unable to create XMLReader", e);
    }

    StringBuilder builder = new StringBuilder();

    DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        @Override
        public void characters(final char[] ch, final int start, final int length) throws SAXException {
            if (foundElement) {
                builder.append(ch, start, length);
            }
        }

        @Override
        public void endElement(final String uri, final String localName, final String qName)
                throws SAXException {
            if (localName.equals(elementName)) {
                foundElement = false;
            }
        }

        @Override
        public void startElement(final String uri, final String localName, final String qName,
                final Attributes attributes) throws SAXException {
            if (localName.equals(elementName)) {
                foundElement = true;
            }
        }
    };

    xmlReader.setContentHandler(handler);
    xmlReader.setErrorHandler(handler);

    try {
        xmlReader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return builder.toString();
}

From source file:org.exist.collections.Collection.java

/** Stores an XML document in the database. {@link #validateXMLResourceInternal(org.exist.storage.txn.Txn,
 * org.exist.storage.DBBroker, org.exist.xmldb.XmldbURI, CollectionConfiguration, org.exist.collections.Collection.ValidateBlock)} 
 * should have been called previously in order to acquire a write lock for the document. Launches the finish trigger.
 * /* w w  w .j  av a  2  s .co  m*/
 * @param transaction
 * @param broker
 * @param info
 * @param source
 * @param privileged
 * 
 * @throws EXistException
 * @throws PermissionDeniedException
 * @throws TriggerException
 * @throws SAXException
 * @throws LockException
 */
public void store(final Txn transaction, final DBBroker broker, final IndexInfo info, final InputSource source,
        boolean privileged)
        throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException {

    storeXMLInternal(transaction, broker, info, privileged, new StoreBlock() {
        @Override
        public void run() throws EXistException, SAXException {
            try {
                final InputStream is = source.getByteStream();
                if (is != null && is.markSupported()) {
                    is.reset();
                } else {
                    final Reader cs = source.getCharacterStream();
                    if (cs != null && cs.markSupported()) {
                        cs.reset();
                    }
                }
            } catch (final IOException e) {
                // mark is not supported: exception is expected, do nothing
                LOG.debug(
                        "InputStream or CharacterStream underlying the InputSource does not support marking and therefore cannot be re-read.");
            }
            final XMLReader reader = getReader(broker, false, info.getCollectionConfig());
            info.setReader(reader, null);
            try {
                reader.parse(source);
            } catch (final IOException e) {
                throw new EXistException(e);
            } finally {
                releaseReader(broker, info, reader);
            }
        }
    });
}

From source file:org.exist.collections.Collection.java

/** 
 * Stores an XML document in the database. {@link #validateXMLResourceInternal(org.exist.storage.txn.Txn,
 * org.exist.storage.DBBroker, org.exist.xmldb.XmldbURI, CollectionConfiguration, org.exist.collections.Collection.ValidateBlock)} 
 * should have been called previously in order to acquire a write lock for the document. Launches the finish trigger.
 * /*from w w w .  j  av a  2  s  . c  o  m*/
 * @param transaction
 * @param broker
 * @param info
 * @param data
 * @param privileged
 * 
 * @throws EXistException
 * @throws PermissionDeniedException
 * @throws TriggerException
 * @throws SAXException
 * @throws LockException
 */
public void store(final Txn transaction, final DBBroker broker, final IndexInfo info, final String data,
        boolean privileged)
        throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException {

    storeXMLInternal(transaction, broker, info, privileged, new StoreBlock() {
        @Override
        public void run() throws SAXException, EXistException {
            final CollectionConfiguration colconf = info.getDocument().getCollection().getConfiguration(broker);
            final XMLReader reader = getReader(broker, false, colconf);
            info.setReader(reader, null);
            try {
                reader.parse(new InputSource(new StringReader(data)));
            } catch (final IOException e) {
                throw new EXistException(e);
            } finally {
                releaseReader(broker, info, reader);
            }
        }
    });
}

From source file:org.exist.collections.Collection.java

/** 
 * Validates an XML document et prepares it for further storage. Launches prepare and postValidate triggers.
 * Since the process is dependant from the collection configuration, the collection acquires a write lock during the process.
 * /* ww  w .  j a va  2s  . co  m*/
 * @param transaction
 * @param broker
 * @param docUri
 * @param source
 * 
 * @return An {@link IndexInfo} with a write lock on the document. 
 * 
 * @throws EXistException
 * @throws PermissionDeniedException
 * @throws TriggerException
 * @throws SAXException
 * @throws LockException
 */
public IndexInfo validateXMLResource(final Txn transaction, final DBBroker broker, final XmldbURI docUri,
        final InputSource source) throws EXistException, PermissionDeniedException, TriggerException,
        SAXException, LockException, IOException {
    final CollectionConfiguration colconf = getConfiguration(broker);

    return validateXMLResourceInternal(transaction, broker, docUri, colconf, new ValidateBlock() {
        @Override
        public void run(final IndexInfo info) throws SAXException, EXistException {
            final XMLReader reader = getReader(broker, true, colconf);
            info.setReader(reader, null);
            try {

                /*
                 * Note - we must close shield the input source,
                 * else it can be closed by the Reader, so subsequently
                 * when we try and read it in storeXmlInternal we will get
                 * an exception.
                 */
                final InputSource closeShieldedInputSource = closeShieldInputSource(source);

                reader.parse(closeShieldedInputSource);
            } catch (final SAXException e) {
                throw new SAXException("The XML parser reported a problem: " + e.getMessage(), e);
            } catch (final IOException e) {
                throw new EXistException(e);
            } finally {
                releaseReader(broker, info, reader);
            }
        }
    });
}

From source file:org.exist.collections.MutableCollection.java

@Override
public void store(final Txn transaction, final DBBroker broker, final IndexInfo info, final InputSource source)
        throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException {
    storeXMLInternal(transaction, broker, info, storeInfo -> {
        try {//from ww  w.j  a va 2s .  c  o m
            final InputStream is = source.getByteStream();
            if (is != null && is.markSupported()) {
                is.reset();
            } else {
                final Reader cs = source.getCharacterStream();
                if (cs != null && cs.markSupported()) {
                    cs.reset();
                }
            }
        } catch (final IOException e) {
            // mark is not supported: exception is expected, do nothing
            LOG.debug(
                    "InputStream or CharacterStream underlying the InputSource does not support marking and therefore cannot be re-read.");
        }
        final XMLReader reader = getReader(broker, false, storeInfo.getCollectionConfig());
        storeInfo.setReader(reader, null);
        try {
            reader.parse(source);
        } catch (final IOException e) {
            throw new EXistException(e);
        } finally {
            releaseReader(broker, storeInfo, reader);
        }
    });
}

From source file:org.exist.collections.MutableCollection.java

@Override
public void store(final Txn transaction, final DBBroker broker, final IndexInfo info, final String data)
        throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException {
    storeXMLInternal(transaction, broker, info, storeInfo -> {
        final CollectionConfiguration colconf = storeInfo.getDocument().getCollection()
                .getConfiguration(broker);
        final XMLReader reader = getReader(broker, false, colconf);
        storeInfo.setReader(reader, null);
        try {/*from  w  w  w .ja  v  a  2 s.  c o m*/
            reader.parse(new InputSource(new StringReader(data)));
        } catch (final IOException e) {
            throw new EXistException(e);
        } finally {
            releaseReader(broker, storeInfo, reader);
        }
    });
}

From source file:org.exist.collections.MutableCollection.java

@Override
public IndexInfo validateXMLResource(final Txn transaction, final DBBroker broker, final XmldbURI name,
        final InputSource source) throws EXistException, PermissionDeniedException, TriggerException,
        SAXException, LockException, IOException {
    final CollectionConfiguration colconf = getConfiguration(broker);

    return validateXMLResourceInternal(transaction, broker, name, colconf, (info) -> {
        final XMLReader reader = getReader(broker, true, colconf);
        info.setReader(reader, null);/* ww w. j  a  v a  2 s  .com*/
        try {

            /*
             * Note - we must close shield the input source,
             * else it can be closed by the Reader, so subsequently
             * when we try and read it in storeXmlInternal we will get
             * an exception.
             */
            final InputSource closeShieldedInputSource = closeShieldInputSource(source);

            reader.parse(closeShieldedInputSource);
        } catch (final SAXException e) {
            throw new SAXException("The XML parser reported a problem: " + e.getMessage(), e);
        } catch (final IOException e) {
            throw new EXistException(e);
        } finally {
            releaseReader(broker, info, reader);
        }
    });
}