Example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader

List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader

Introduction

In this page you can find the example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader.

Prototype

public static XMLReader createXMLReader() throws SAXException 

Source Link

Document

Obtains a new instance of a org.xml.sax.XMLReader .

Usage

From source file:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java

/**
 * Reads all CONE-entries with a citation-style field filled in. 
 * Generates a Map with citation styles and idValue-Type-Pairs. 
 * @throws Exception/*  w w w.j av a  2 s  .c  om*/
 */
public static void getJournalsXML() throws Exception {
    HttpClient client = new HttpClient();

    String coneQuery =
            // JUS-Testserver CoNE
            //   "http://193.174.132.114/cone/journals/query?format=rdf&escidoc:citation-style=*&m=full&n=0";
            PropertyReader.getProperty("escidoc.cone.service.url")
                    + "journals/query?format=rdf&escidoc:citation-style=*&m=full&n=0";
    logger.info("cone query:" + coneQuery);
    GetMethod getMethod = new GetMethod(coneQuery);

    ProxyHelper.executeMethod(client, getMethod);

    XMLReader xr;

    xr = XMLReaderFactory.createXMLReader();
    JusXmlHandler handler = new JusXmlHandler();
    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);

    Reader r = new InputStreamReader(getMethod.getResponseBodyAsStream());
    xr.parse(new InputSource(r));

    citationMap = handler.getCitationStyleMap();

}

From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java

private Document getDocumentFromFile(File preparsedXMLfile, String editionFileName) throws Exception {
    if (log.isInfoEnabled())
        log.info("Finished writing Edition to File, starting to import it as GZIP-InputStream...");
    XMLFilter filter = new XMLFilterImpl(XMLReaderFactory.createXMLReader());
    preparsedXMLfile = File.createTempFile("edition_import_preparsed_", ".xml");
    if (log.isDebugEnabled())
        log.debug("preparsedXMLfile: " + preparsedXMLfile.getAbsolutePath());
    XMLWriter xmlWriter = new XMLWriter(new OutputStreamWriter(new FileOutputStream(preparsedXMLfile)));
    filter.setContentHandler(new EditionBlobContentHandler(xmlWriter, preparsedXMLfile));
    InputSource saxIn = null;//from w w  w  .j a va2 s .c o  m
    try {
        try {
            saxIn = new InputSource(new GZIPInputStream(new FileInputStream(editionFileName)));
        } catch (Exception exe) {
            saxIn = new InputSource(new BufferedReader(new FileReader(editionFileName)));
        }
    } catch (FileNotFoundException exe) {
        log.error("Edition file isnt available anymore. Edition needs to be deleted!");
    }
    filter.parse(saxIn);
    xmlWriter.flush();
    xmlWriter = null;
    filter = null;
    System.gc();
    if (log.isInfoEnabled())
        log.info("Finished cutting BLOBs, starting to open XML Document...");
    // BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
    // InputSource in = new InputSource(br);
    InputSource domIn = new InputSource(new FileInputStream(preparsedXMLfile));
    return XercesHelper.inputSource2Dom(domIn);
}

From source file:com.farmafene.commons.cas.ValidateTGT.java

/**
 * Get an instance of an XML reader from the XMLReaderFactory.
 * /*from w  w w .ja v  a2 s.c  o m*/
 * @return the XMLReader.
 */
private XMLReader getXmlReader() {
    try {
        return XMLReaderFactory.createXMLReader();
    } catch (final SAXException e) {
        throw new RuntimeException("Unable to create XMLReader", e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.VersionInfoManager.java

private static String getSchemaVersion(final File f) throws SAXException, IOException {

    class StopParsingException extends SAXException {
        private static final long serialVersionUID = -7499102356648608429L;
    }//from w w w  .  j  ava2s. co  m
    ;

    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    final InputStream s = new FileInputStream(f);

    final String[] result = new String[1];

    try {

        xmlReader.setContentHandler(new ContentHandler() {

            boolean repositoryTagFound = false;

            @Override
            public void startPrefixMapping(String prefix, String uri) throws SAXException {
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes atts)
                    throws SAXException {
                if (localName.equals("versions")) {
                    result[0] = atts.getValue("schemaVersion");

                    if (result[0] != null)
                        throw new StopParsingException();
                }

                if (localName.equals("repository")) {
                    repositoryTagFound = true;
                }
            }

            @Override
            public void startDocument() throws SAXException {
            }

            @Override
            public void skippedEntity(String name) throws SAXException {
            }

            @Override
            public void setDocumentLocator(Locator locator) {
            }

            @Override
            public void processingInstruction(String target, String data) throws SAXException {
            }

            @Override
            public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            }

            @Override
            public void endPrefixMapping(String prefix) throws SAXException {
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
            }

            @Override
            public void endDocument() throws SAXException {
                if (!repositoryTagFound && result[0] == null)
                    result[0] = "1.2.0";
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
            }
        });

        try {
            xmlReader.parse(new InputSource(s));
        } catch (StopParsingException ex) {
            //OK, StopParsingException is thrown when we know all we need from the document.
        }
    } finally {
        IOUtils.closeQuietly(s);
    }
    return result[0];
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.xlsx.XLSXFileReader.java

public XMLReader fetchSheetParser(SharedStringsTable sst, DataTable dataTable, PrintWriter tempOut)
        throws SAXException {
    // An attempt to use org.apache.xerces.parsers.SAXParser resulted 
    // in some weird conflict in the app; the default XMLReader obtained 
    // from the XMLReaderFactory (from xml-apis.jar) appears to be working
    // just fine. however, 
    // TODO: verify why the app gets built with xml-apis-1.0.b2.jar; it's 
    // an old version - 1.4 seems to be the current release, and 2.0.2
    // (a new development?) appears to be available. We don't specifically
    // request this 1.0.* version, so another package must have it defined
    // as a dependency. We need to verify our dependencies, we most likely 
    // have some hard-coded versions in our pom.xml that are both old and 
    // unnecessary.
    // -- L.A. 4.0 alpha 1

    XMLReader xReader = XMLReaderFactory.createXMLReader();
    dbglog.fine("creating new SheetHandler;");
    ContentHandler handler = new SheetHandler(sst, dataTable, tempOut);
    xReader.setContentHandler(handler);/*from  w  w w  .  ja  v  a2  s  .  c  om*/
    return xReader;
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Serializer.java

/**
 * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message.
 * //from www  .  ja  v a2 s .c  om
 * @param source
 *            a XML-encoded HL7 message.
 * @return
 */
@Override
public String fromXML(String source) throws MessageSerializerException {
    try {
        if (deserializationProperties.isUseStrictParser()) {
            return deserializationPipeParser.encode(deserializationXmlParser.parse(source));
        } else {
            /*
             * The delimiters below need to come from the XML somehow. The
             * ER7 handler should take care of it TODO: Ensure you get these
             * elements from the XML
             */

            String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>");

            if (StringUtils.isEmpty(fieldSeparator)) {
                fieldSeparator = "|";
            }

            String componentSeparator = "^";
            String repetitionSeparator = "~";
            String subcomponentSeparator = "&";
            String escapeCharacter = "\\";

            /*
             * Our delimiters usually look like this:
             * <MSH.2>^~\&amp;</MSH.2> We need to decode XML entities
             */
            String separators = ampersandPattern.matcher(getNodeValue(source, "<MSH.2>", "</MSH.2>"))
                    .replaceAll("&");

            if (separators.length() == 4) {
                // usually ^
                componentSeparator = separators.substring(0, 1);
                // usually ~
                repetitionSeparator = separators.substring(1, 2);
                // usually \
                escapeCharacter = separators.substring(2, 3);
                // usually &
                subcomponentSeparator = separators.substring(3, 4);
            }

            XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(deserializationSegmentDelimiter,
                    fieldSeparator, componentSeparator, repetitionSeparator, escapeCharacter,
                    subcomponentSeparator, true);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);

            /*
             * Parse, but first replace all spaces between brackets. This
             * fixes pretty-printed XML we might receive.
             */
            reader.parse(new InputSource(new StringReader(prettyPattern2
                    .matcher(prettyPattern1.matcher(source).replaceAll("<$1>")).replaceAll("<$1>"))));
            return handler.getOutput().toString();
        }
    } catch (Exception e) {
        throw new MessageSerializerException("Error converting XML to ER7", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to ER7", e));
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerImpl.java

/**
 * reads a WSDL from input stream, modifies it and returns input stream to the result
 * @param wsdl//from  w  w  w .java 2s  .co m
 * @return
 */
private InputStream modifyWsdl(InputStream wsdl) {
    try {
        TransformerHandler serializer = TRANSFORMER_FACTORY.newTransformerHandler();
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        serializer.setResult(result);

        OverwriteAttributeFilter filter = getModifyWsdlFilter();
        filter.setContentHandler(serializer);

        XMLReader xmlreader = XMLReaderFactory.createXMLReader();
        xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        xmlreader.setProperty("http://xml.org/sax/properties/lexical-handler", new CommentsHandler(serializer));
        xmlreader.setContentHandler(filter);

        // parse XML, filter it, put end result to a String
        xmlreader.parse(new InputSource(wsdl));
        String resultString = writer.toString();
        log.debug("result of WSDL cleanup: {}", resultString);

        // offer InputStream into processed String
        return new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8));
    } catch (IOException | SAXException | TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and SAX events out.
 *///  w  w  w  .  j  a  va  2 s .co  m
public static void exampleContentHandlerToContentHandler(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // If so, we can safely cast.
        SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // A TransformerHandler is a ContentHandler that will listen for 
        // SAX events, and transform them to the result.
        TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID));

        // Set the result handling to be a serialization to System.out.
        Result result = new SAXResult(new ExampleContentHandler());
        handler.setResult(result);

        // Create a reader, and set it's content handler to be the TransformerHandler.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);

        // It's a good idea for the parser to send lexical events.
        // The TransformerHandler is also a LexicalHandler.
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Parse the source XML, and send the parse events to the TransformerHandler.
        reader.parse(sourceID);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:com.amalto.core.query.DataRecordCreationTest.java

public void testCreationFromSAX() throws Exception {
    MetadataRepository repository = new MetadataRepository();
    repository.load(this.getClass().getResourceAsStream("metadata.xsd"));

    ComplexTypeMetadata product = repository.getComplexType("Product");
    assertNotNull(product);//from   w  w w  .  ja va 2s .c om

    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    DataRecordReader<XmlSAXDataRecordReader.Input> dataRecordReader = new XmlSAXDataRecordReader();
    XmlSAXDataRecordReader.Input input = new XmlSAXDataRecordReader.Input(xmlReader,
            new InputSource(this.getClass().getResourceAsStream("DataRecordCreationTest_1.xml")));
    DataRecord dataRecord = dataRecordReader.read(repository, product, input);

    performAsserts(dataRecord);
}

From source file:com.amalto.core.query.DataRecordCreationTest.java

public void testCreationFromSAXWithMetadata() throws Exception {
    MetadataRepository repository = new MetadataRepository();
    repository.load(this.getClass().getResourceAsStream("metadata.xsd"));

    ComplexTypeMetadata product = repository.getComplexType("Product");
    assertNotNull(product);//from  w  ww. jav  a2  s.  c  o m

    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    DataRecordReader<XmlSAXDataRecordReader.Input> dataRecordReader = new XmlSAXDataRecordReader();
    XmlSAXDataRecordReader.Input input = new XmlSAXDataRecordReader.Input(xmlReader,
            new InputSource(this.getClass().getResourceAsStream("DataRecordCreationTest_3.xml")));
    DataRecord dataRecord = dataRecordReader.read(repository, product, input);

    performAsserts(dataRecord);
    performMetadataAsserts(dataRecord);
}