Example usage for org.xml.sax XMLReader setContentHandler

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

Introduction

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

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:net.sf.janos.model.xml.ResultParser.java

public static Map<AVTransportEventHandler.AVTransportEventType, String> parseAVTransportEvent(String xml)
        throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    AVTransportEventHandler handler = new AVTransportEventHandler();
    reader.setContentHandler(handler);
    try {//from   w  w w  .  j ava  2  s  .co  m
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse AV Transport Event: ", e);
    }
    return handler.getChanges();
}

From source file:com.surveypanel.form.xml.ParserHelper.java

/**
 * Return a reader to parse content/*from  w  w w . j av a 2s.  co m*/
 * @param path
 * @return
 */
protected static FormValuesHandler getReader(InputStream is) {
    FormValuesHandler formValuesHandler = new FormValuesHandler();
    XMLReader parser = null;
    try {
        InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
        parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(formValuesHandler);
        parser.setErrorHandler(formValuesHandler);
        InputSource inputSource = new InputSource(inputStreamReader);
        parser.parse(inputSource);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return formValuesHandler;
}

From source file:net.sf.janos.model.xml.ResultParser.java

public static Map<RenderingControlEventHandler.RenderingControlEventType, String> parseRenderingControlEvent(
        String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    RenderingControlEventHandler handler = new RenderingControlEventHandler();
    reader.setContentHandler(handler);
    try {/*from  www  . j a  v a  2  s .c  o  m*/
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse Rendering Control event: ", e);
    }
    return handler.getChanges();
}

From source file:com.mindquarry.desktop.I18N.java

protected static Map<String, String> initTranslationMap(String fileBase, String fileSuffix) {
    try {/*from   ww w .ja  va2s .  co m*/
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(false);
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        TranslationMessageParser translationParser = new TranslationMessageParser();
        reader.setContentHandler(translationParser);
        reader.setErrorHandler(translationParser);
        // TODO: use "xx_YY" if available, use "xx" otherwise:
        String transFile = fileBase + Locale.getDefault().getLanguage() + fileSuffix;
        InputStream is = I18N.class.getResourceAsStream(transFile);
        if (is == null) {
            // no translation available for this language
            log.debug("No translation file available for language: " + Locale.getDefault().getLanguage());
            return new HashMap<String, String>();
        }
        log.debug("Loading translation file " + transFile + " from JAR");
        reader.parse(new InputSource(is));
        return translationParser.getMap();
    } catch (Exception e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:eu.project.ttc.test.unit.TestUtil.java

public static String getTeiTxt(String filename)
        throws ParserConfigurationException, SAXException, IOException, FileNotFoundException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);// w  ww  . j a  va2  s .  c  om
    spf.setValidating(false);
    spf.setFeature("http://xml.org/sax/features/namespaces", true);
    spf.setFeature("http://xml.org/sax/features/validation", false);
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    TeiToTxtSaxHandler handler = new TeiToTxtSaxHandler();
    xmlReader.setContentHandler(handler);
    xmlReader.parse(new InputSource(TestUtil.getInputStream(filename)));
    String text = handler.getText();
    return text;
}

From source file:com.mirth.connect.plugins.datatypes.ncpdp.test.NCPDPTest.java

private static long runTest(String testMessage) throws MessageSerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    //      Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    //        properties.put("useStrictParser", "true");
    //        properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource",SchemaUrl);
    stopwatch.start();//  ww w .  j a v  a 2s . c o m
    NCPDPSerializer serializer = new NCPDPSerializer(null);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.serialize(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java

private static long runTest(String testMessage) throws SerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    properties.put("useStrictParser", "true");
    properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource", SchemaUrl);
    stopwatch.start();/*from  ww  w .  j a va2 s  .c  om*/
    NCPDPSerializer serializer = new NCPDPSerializer(properties);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.toXML(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:XMLUtilities.java

/**
 * Convenience method for parsing an XML file. This method will
 * wrap the resource in an InputSource and set the source's
 * systemId to "jedit.jar" (so the source should be able to
 * handle any external entities by itself).
 *
 * <p>SAX Errors are caught and are not propagated to the caller;
 * instead, an error message is printed to jEdit's activity
 * log. So, if you need custom error handling, <b>do not use
 * this method</b>.//from  w w w.  j a va 2s .  c  o m
 *
 * <p>The given stream is closed before the method returns,
 * regardless whether there were errors or not.</p>
 *
 * @return true if any error occured during parsing, false if success.
 */
public static boolean parseXML(InputStream in, DefaultHandler handler) throws IOException {
    try {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InputSource isrc = new InputSource(new BufferedInputStream(in));
        isrc.setSystemId("jedit.jar");
        parser.setContentHandler(handler);
        parser.setDTDHandler(handler);
        parser.setEntityResolver(handler);
        parser.setErrorHandler(handler);
        parser.parse(isrc);
    } catch (SAXParseException se) {
        int line = se.getLineNumber();
        return true;
    } catch (SAXException e) {
        return true;
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException io) {
        }
    }
    return false;
}

From source file:org.apache.clerezza.commons.rdf.impl.sparql.SparqlResultParser.java

static Object parse(InputStream in) throws IOException {
    try {/*from  ww w .j av  a2  s  .  co  m*/
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException | SAXException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.textocat.textokit.commons.io.axml.AXMLReader.java

/**
 * Populate the specified CAS by a text and annotations from the specified
 * input assuming that it is formatted as described above.
 *
 * @param in  input Reader. It is a caller's responsibility to close this
 *            reader instance./*from ww  w.j a v  a 2s .c om*/
 * @param cas CAS
 * @throws IOException
 * @throws SAXException
 */
public static void read(Reader in, final CAS cas) throws IOException, SAXException {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    AXMLContentHandler contentHandler = new AXMLContentHandler(cas.getTypeSystem());
    xmlReader.setContentHandler(contentHandler);
    InputSource inputSource = new InputSource(in);
    xmlReader.parse(inputSource);
    cas.setDocumentText(contentHandler.getText());
    // from axml ID to CAS FS
    final Map<Annotation, FeatureStructure> mapped = Maps.newHashMap();
    List<Runnable> delayedFeatureAssignments = Lists.newLinkedList();
    //
    for (Annotation _anno : contentHandler.getAnnotations()) {
        String typeName = _anno.getType();
        Type type = cas.getTypeSystem().getType(typeName);
        if (type == null) {
            throw new IllegalStateException(String.format("Unknown type: %s", typeName));
        }
        final AnnotationFS anno = cas.createAnnotation(type, _anno.getBegin(), _anno.getEnd());
        // set primitive features
        for (String featName : _anno.getFeatureNames()) {
            final Feature feat = type.getFeatureByBaseName(featName);
            if (feat == null)
                throw new IllegalStateException(
                        String.format("%s does not have feature %s", type.getName(), featName));
            if (feat.getRange().isPrimitive()) {
                String featValStr = _anno.getFeatureStringValue(featName);
                if (featValStr != null) {
                    anno.setFeatureValueFromString(feat, featValStr);
                }
            } else {
                if (feat.getRange().isArray()) {
                    final List<Annotation> srcFSes = _anno.getFeatureFSArrayValue(featName);
                    delayedFeatureAssignments.add(new Runnable() {
                        @Override
                        public void run() {
                            List<FeatureStructure> mappedFSes = Lists.transform(srcFSes,
                                    new Function<Annotation, FeatureStructure>() {
                                        @Override
                                        public FeatureStructure apply(Annotation srcFS) {
                                            FeatureStructure mappedFS = mapped.get(srcFS);
                                            if (mappedFS == null)
                                                throw new IllegalStateException();
                                            return mappedFS;
                                        }
                                    });
                            anno.setFeatureValue(feat, FSCollectionFactory.createArrayFS(cas, mappedFSes));
                        }
                    });
                } else {
                    final Annotation srcFS = _anno.getFeatureFSValue(featName);
                    delayedFeatureAssignments.add(new Runnable() {
                        @Override
                        public void run() {
                            FeatureStructure mappedFS = mapped.get(srcFS);
                            if (mappedFS == null)
                                throw new IllegalStateException();
                            anno.setFeatureValue(feat, mappedFS);
                        }
                    });
                }
            }
        }
        cas.addFsToIndexes(anno);
        mapped.put(_anno, anno);
    }
    // PHASE II -- set FS and FSArray features
    for (Runnable r : delayedFeatureAssignments) {
        r.run();
    }
}