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:eu.apenet.dpt.utils.util.Ead2EdmInformation.java

private void determineDaoInformation(File fileToRead)
        throws IOException, SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    EadContentHandler myContentHandler = new EadContentHandler();
    xr.setContentHandler(myContentHandler);
    xr.parse(new InputSource(new InputStreamReader(new BOMInputStream(new FileInputStream(fileToRead)))));

    if (this.roleType == null) {
        this.roleType = "UNSPECIFIED";
    }//from   w w  w .  jav  a  2 s. c  o  m
}

From source file:com.thruzero.common.core.infonode.builder.SaxInfoNodeBuilder.java

/** construct complete {@code InfoNodeElement} from dom. */
protected InfoNodeElement doBuildInfoNode(final String xml, final InfoNodeElement targetNode,
        final InfoNodeFilterChain infoNodeFilterChain) throws Exception {
    handlePrimaryKey(targetNode);/*w w w .jav  a  2 s .c  om*/
    if (StringUtils.isNotEmpty(xml)) {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InfoNodeSaxHandler dnHandler = new InfoNodeSaxHandler(targetNode, infoNodeFilterChain); // state for this build is kept in this InfoNode Handler instance

        parser.setContentHandler(dnHandler);
        parser.setErrorHandler(dnHandler);
        parser.setFeature("http://xml.org/sax/features/validation", false);

        InputSource input = new InputSource(new StringReader(xml));
        parser.parse(input);
    }
    handleRootNode(targetNode);

    return targetNode;
}

From source file:com.zyz.mobile.book.UserBookData.java

/**
 * open the info xml file. create one if it cannot be found
 *//*from w  ww . ja v  a  2  s  .co  m*/
public boolean parse() {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader reader = sp.getXMLReader();
        reader.setContentHandler(this);
        reader.parse(new InputSource(new FileReader(mInfoFile)));
    } catch (Exception e) {
        // constructor doesn't check for validity of the file
        // catch all exceptions here
        Log.e(TAG, "Failed to parse xml file?");
        return false;
    }
    return true;
}

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

@Override
public String fromXML(String source) throws MessageSerializerException {
    /*//from w  ww.  j a va2 s  . c  om
     * Need to determine the version by looking at the raw message.
     * The transaction header will contain the version ("51" for 5.1 and
     * "D0" for D.0)
     */
    String version = "D0";

    if (source.indexOf("D0") == -1) {
        version = "51";
    } else if (source.indexOf("51") == -1) {
        version = "D0";
    } else if (source.indexOf("51") < source.indexOf("D0")) {
        version = "51";
    }

    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        NCPDPXMLHandler handler = new NCPDPXMLHandler(deserializationSegmentDelimiter,
                deserializationGroupDelimiter, deserializationFieldDelimiter, version);
        reader.setContentHandler(handler);

        if (deserializationProperties.isUseStrictValidation()) {
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    "ncpdp" + version + ".xsd");
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    "/ncpdp" + version + ".xsd");
        }

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

From source file:com.webcohesion.ofx4j.client.impl.OFXHomeFIDataStore.java

private BaseFinancialInstitutionData loadInstitutionData(String href) throws IOException, SAXException {
    if (LOG.isInfoEnabled()) {
        LOG.info("Loading institution data from: " + href);
    }//from www  . jav  a  2 s .co m

    URL url = new URL(href);
    XMLReader xmlReader = new Parser();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    InstitutionContentHandler institutionHandler = new InstitutionContentHandler();
    xmlReader.setContentHandler(institutionHandler);
    xmlReader.parse(new InputSource(url.openStream()));
    return institutionHandler.data;
}

From source file:es.prodevelop.gvsig.mini.tasks.weather.WeatherFunctionality.java

@Override
public boolean execute() {
    URL url;/*from w ww  .jav a2  s .c o m*/
    try {
        String queryString = "http://ws.geonames.org/findNearbyPlaceName?lat=" + lat + "&lng=" + lon;
        InputStream is = Utils.openConnection(queryString);
        BufferedInputStream bis = new BufferedInputStream(is);

        /* Read bytes to the Buffer until there is nothing more to read(-1). */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            if (isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);

        }

        place = this.parseGeoNames(baf.toByteArray());

        queryString = "http://www.google.com/ig/api?weather=" + place;
        /* Replace blanks with HTML-Equivalent. */
        url = new URL(queryString.replace(" ", "%20"));

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /*
         * Create a new ContentHandler and apply it to the XML-Reader
         */
        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Parse the xml-data our URL-call returned. */
        xr.parse(new InputSource(url.openStream()));

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Our Handler now provides the parsed weather-data to us. */
        ws = gwh.getWeatherSet();

        ws.place = place;
        res = TaskHandler.FINISHED;
        // map.showWeather(ws);
    } catch (IOException e) {
        if (e instanceof UnknownHostException) {
            res = TaskHandler.NO_RESPONSE;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        res = TaskHandler.ERROR;
    } finally {
        //         super.stop();
        return true;
    }
}

From source file:architecture.common.util.L10NUtils.java

private void loadProps(String resource, boolean breakOnError) throws IOException {

    HashSet<URL> hashset = new HashSet<URL>();
    if (log.isDebugEnabled()) {
        log.debug((new StringBuilder()).append("Searching ").append(resource).toString());
    }/*from   w w w  .j  a v  a2s.c om*/
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(resource);
    if (urls != null) {
        URL url;
        for (; urls.hasMoreElements(); hashset.add(url)) {
            url = urls.nextElement();
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Adding ").append(url).toString());
        }
    }

    for (URL url : hashset) {
        if (log.isDebugEnabled())
            log.debug((new StringBuilder()).append("Loading from ").append(url).toString());
        InputStream is = null;
        try {
            is = url.openStream();
            InputSource input = new InputSource(is);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XMLReader xmlreader = factory.newSAXParser().getXMLReader();
            I18nParsingHandler handler = new I18nParsingHandler();
            xmlreader.setContentHandler(handler);
            xmlreader.setDTDHandler(handler);
            xmlreader.setEntityResolver(handler);
            xmlreader.setErrorHandler(handler);
            xmlreader.parse(input);
            localizers.addAll(handler.localizers);
        } catch (IOException e) {
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Skipping ").append(url).toString());
            if (breakOnError)
                throw e;
        } catch (Exception e) {
            log.error(e);
        } finally {
            if (is != null)
                IOUtils.closeQuietly(is);
        }
    }

}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and SAX events out.
 *//*from   w  ww .  ja va 2s .com*/
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:Examples.java

/**
 * Show the Transformer as a simple XMLFilter.  This is pretty similar
 * to exampleXMLReader, except that here the parent XMLReader is created 
 * by the caller, instead of automatically within the XMLFilter.  This 
 * gives the caller more direct control over the parent reader.
 *///from   w  w w.j  a  v  a  2 s  .  co m
public static void exampleXMLFilter(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException // , ParserConfigurationException
{
    TransformerFactory tfactory = TransformerFactory.newInstance();

    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();
    // The transformer will use a SAX parser as it's reader.    
    reader.setContentHandler(new ExampleContentHandler());
    try {
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);
    } catch (SAXException se) {

        // What can we do?
        // TODO: User diagnostics.
    }

    XMLFilter filter = ((SAXTransformerFactory) tfactory).newXMLFilter(new StreamSource(xslID));

    filter.setParent(reader);

    // Now, when you call transformer.parse, it will set itself as 
    // the content handler for the parser object (it's "parent"), and 
    // will then call the parse method on the parser.
    filter.parse(new InputSource(sourceID));
}