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:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

public boolean setICSasMultiStatus(String stringMultiStatus) {
    boolean Result = false;
    String ics = "";
    MultiStatus multistatus;//from w w w.j av a  2s .  co m
    ArrayList<Response> responselist;
    Response response;
    PropStat propstat;
    Prop prop;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        MultiStatusHandler contentHandler = new MultiStatusHandler();
        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(new StringReader(stringMultiStatus)));

        multistatus = contentHandler.mMultiStatus;
        if (multistatus != null) {
            responselist = multistatus.ResponseList;
            if (responselist.size() == 1) {
                response = responselist.get(0);
                //HINT: bugfix for google calendar
                if (response.href.equals(this.getUri().getPath().replace("@", "%40"))) {
                    propstat = response.propstat;
                    if (propstat.status.contains("200 OK")) {
                        prop = propstat.prop;
                        ics = prop.calendardata;
                        this.setETag(prop.getetag);
                        Result = true;
                    }
                }
            }
        }
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (SAXException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.stringIcs = ics;
    return Result;
}

From source file:net.sf.joost.trax.TrAXFilter.java

/**
 * Parses the <code>InputSource</code>
 * @param input A <code>InputSource</code> object.
 * @throws SAXException/* w  w w .  j  a v a2s.  c o m*/
 * @throws IOException
 */
public void parse(InputSource input) throws SAXException, IOException {

    Transformer transformer = null;
    if (DEBUG) {
        if (log.isDebugEnabled())
            log.debug("parsing InputSource " + input.getSystemId());
    }

    try {
        // get a new Transformer
        transformer = this.templates.newTransformer();
        if (transformer instanceof TransformerImpl) {
            this.processor = ((TransformerImpl) transformer).getStxProcessor();
        } else {
            String msg = "An error is occured, because the given transformer is "
                    + "not an instance of TransformerImpl";
            if (log != null)
                log.fatal(msg);
            else
                System.err.println("Fatal error - " + msg);

        }
        XMLReader parent = this.getParent();

        if (parent == null) {
            parent = XMLReaderFactory.createXMLReader();
            setParent(parent);
        }
        ContentHandler handler = this.getContentHandler();

        if (handler == null) {
            handler = parent.getContentHandler();
        }
        if (handler == null) {
            throw new SAXException("no ContentHandler registered");
        }
        //init StxEmitter
        StxEmitter out = null;

        //SAX specific Implementation
        out = new SAXEmitter(handler);

        if (this.processor != null) {
            this.processor.setContentHandler(out);
            this.processor.setLexicalHandler(out);
        } else {
            throw new SAXException("Joost-Processor is not correct configured.");
        }
        if (parent == null) {
            throw new SAXException("No parent for filter");
        }
        parent.setContentHandler(this.processor);
        parent.setProperty("http://xml.org/sax/properties/lexical-handler", this.processor);
        parent.setEntityResolver(this);
        parent.setDTDHandler(this);
        parent.setErrorHandler(this);
        parent.parse(input);

    } catch (TransformerConfigurationException tE) {
        try {
            configErrListener.fatalError(tE);
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (SAXException sE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(sE.getMessage(), sE));
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (IOException iE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(iE.getMessage(), iE));
        } catch (TransformerConfigurationException innerE) {
            throw new IOException(innerE.getMessage());
        }
    }
}

From source file:de.tlabs.ssr.g1.client.XmlInputThread.java

@Override
public void run() {
    Log.d(TAG, "(" + this.getId() + ") HELLO");

    try {/*from w  w  w  .j  a va2  s .c o m*/
        // create sax parser
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        // get an xml reader 
        XMLReader xr = sp.getXMLReader();

        // set up xml input source
        XMLChunkInputStream xmlChunkInputStream;
        synchronized (GlobalData.socketChannel) {
            xmlChunkInputStream = new XMLChunkInputStream(new ByteArrayBuffer(32 * 1024),
                    GlobalData.socketChannel.socket().getInputStream());
        }
        InputSource inputSource = new InputSource(xmlChunkInputStream);

        // create handler for scene description and assign it
        SceneDescrXMLHandler sceneDescrXMLHandler = new SceneDescrXMLHandler(GlobalData.audioScene);
        xr.setContentHandler(sceneDescrXMLHandler);

        // parse scene description
        //Log.d(TAG, "(" + this.getId() + ") parsing description...");
        //xmlChunkInputStream.printToLog = true;
        while (xmlChunkInputStream.bufferNextChunk() && !sceneDescrXMLHandler.receivedSceneDescr()) {
            // parse and process xml input
            xr.parse(inputSource);
        }
        //xmlChunkInputStream.printToLog = false;

        // signal that scene description was parsed
        //Log.d(TAG, "(" + this.getId() + ") sending SCENEPARSED_OK_MSG");
        GlobalData.sourcesMoverMsgHandler
                .sendMessage(GlobalData.sourcesMoverMsgHandler.obtainMessage(SourcesMover.SCENEPARSED_OK_MSG));

        // create handler for scene updates and assign it
        SceneUpdateXMLHandler sceneUpdateXMLHandler = new SceneUpdateXMLHandler(GlobalData.audioScene);
        xr.setContentHandler(sceneUpdateXMLHandler);

        // parse scene updates
        Log.d(TAG, "(" + this.getId() + ") starting xml input loop...");
        while (xmlChunkInputStream.bufferNextChunk()) {
            // parse and process xml input
            xr.parse(inputSource);

            // check if we should abort
            synchronized (abortFlag) {
                if (abortFlag == true) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        Log.d(TAG, "(" + this.getId() + ") Exception " + e.toString() + ": " + e.getMessage());

        // check if this thread was aborted and/or stopped by a call to interrupt()
        if (Thread.interrupted() || abortFlag) {
            Log.d(TAG, "(" + this.getId() + ") interrupted/aborted");
        } else {
            GlobalData.sourcesMoverMsgHandler.sendMessage(GlobalData.sourcesMoverMsgHandler
                    .obtainMessage(SourcesMover.XMLINPUT_ERR_MSG, e.getMessage()));
            Log.d(TAG, "(" + this.getId() + ") sending XMLINPUT_ERR_MSG");
        }
    }

    Log.d(TAG, "(" + this.getId() + ") GOOD BYE");
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

private String updateContentLinks(AbstractPage page, String content, String id, String divCls)
        throws Exception {
    XMLReader parser = createTagSoupParser();
    StringWriter w = new StringWriter();
    parser.setContentHandler(createContentHandler(page, w, id, divCls));
    parser.parse(new InputSource(new StringReader(content)));
    content = w.toString();//from   www  .  j  a  va 2 s  . c  o m

    if (content.indexOf("html>") != -1) {
        content = content.substring("<html><body>".length());
        content = content.substring(0, content.lastIndexOf("</body></html>"));
    }

    int idx = content.indexOf('>');
    if (idx != -1 && content.substring(idx + 1).startsWith("<p></p>")) {
        //new confluence tends to stick an empty paragraph at the beginning for some pages (like Banner)
        //that causes major formatting issues.  Strip it.
        content = content.substring(0, idx + 1) + content.substring(idx + 8);
    }
    return content;
}

From source file:edu.wisc.my.portlets.dmp.tools.XmlMenuPublisher.java

/**
 * Publishes all the menus in the XML specified by the URL.
 * // w w  w  .j  a  v a 2 s . c o m
 * @param xmlSourceUrl URL to the menu XML.
 */
public void publishMenus(URL xmlSourceUrl) {
    LOG.info("Publishing menus from: " + xmlSourceUrl);

    try {
        //The XMLReader will read in the XML document
        final XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");

        try {
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);

            final URL menuSchema = this.getClass().getResource("/menu.xsd");
            if (menuSchema == null) {
                throw new MissingResourceException("Could not load menu schema. '/menu.xsd'",
                        this.getClass().getName(), "/menu.xsd");
            }

            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    menuSchema.toString());
        } catch (SAXNotRecognizedException snre) {
            LOG.warn("Could not enable XSD validation", snre);
        } catch (SAXNotSupportedException xnse) {
            LOG.warn("Could not enable XSD validation", xnse);
        }

        final MenuItemGeneratingHandler handler = new MenuItemGeneratingHandler();

        reader.setContentHandler(handler);
        reader.parse(new InputSource(xmlSourceUrl.openStream()));

        final Map menus = handler.getMenus();

        final BeanFactory factory = this.getFactory();
        final MenuDao dao = (MenuDao) factory.getBean("menuDao", MenuDao.class);

        for (final Iterator nameItr = menus.entrySet().iterator(); nameItr.hasNext();) {
            final Map.Entry entry = (Map.Entry) nameItr.next();
            final String menuName = (String) entry.getKey();
            final MenuItem rootItem = (MenuItem) entry.getValue();

            LOG.info("Publishing menu='" + menuName + "' item='" + rootItem + "'");
            dao.storeMenu(menuName, rootItem);
        }

        LOG.info("Published menus from: " + xmlSourceUrl);
    } catch (IOException ioe) {
        LOG.error("Error publishing menus", ioe);
    } catch (SAXException saxe) {
        LOG.error("Error publishing menus", saxe);
    }
}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

/**
 * Parses an XML response from a WFS Transaction (Insert) request and
 * reports if the response contains a Service Exception.
 * @param xmlResponse String containing the XML response from a DescribeFeatureType request.
 *///from  w  w w .ja v a  2 s.  c om
protected boolean parseXMLResponse(InputStream xmlResponse) {
    Log.d(TAG, "parseXMLResponse(InputStream) called.");

    mInsertedIDs = new ArrayList<Long>();

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return false;
    }
    return true;
}

From source file:com.larvalabs.svgandroid.SVGParser.java

private static SVG parse(InputStream in, Integer searchColor, Integer replaceColor, boolean whiteMode)
        throws SVGParseException {
    // Util.debug("Parsing SVG...");
    SVGHandler svgHandler = null;/*from w  w w.  j a  v  a 2 s  .c o  m*/
    try {
        // long start = System.currentTimeMillis();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        final Picture picture = new Picture();
        svgHandler = new SVGHandler(picture);
        svgHandler.setColorSwap(searchColor, replaceColor);
        svgHandler.setWhiteMode(whiteMode);

        CopyInputStream cin = new CopyInputStream(in);

        IDHandler idHandler = new IDHandler();
        xr.setContentHandler(idHandler);
        xr.parse(new InputSource(cin.getCopy()));
        svgHandler.idXml = idHandler.idXml;

        xr.setContentHandler(svgHandler);
        xr.parse(new InputSource(cin.getCopy()));
        // Util.debug("Parsing complete in " + (System.currentTimeMillis() - start) + " millis.");
        SVG result = new SVG(picture, svgHandler.bounds);
        // Skip bounds if it was an empty pic
        if (!Float.isInfinite(svgHandler.limits.top)) {
            result.setLimits(svgHandler.limits);
        }
        return result;
    } catch (Exception e) {
        //for (String s : handler.parsed.toString().replace(">", ">\n").split("\n"))
        //   Log.d(TAG, "Parsed: " + s);
        throw new SVGParseException(e);
    }
}

From source file:com.pontecultural.flashcards.ReadSpreadsheet.java

public void run() {
    try {//  w ww .  j a va  2s  .co m
        // This class is used to upload a zip file via 
        // the web (ie,fileData). To test it, the file is 
        // give to it directly via odsFile. One of 
        // which must be defined. 
        assertFalse(odsFile == null && fileData == null);
        XMLReader reader = null;
        final String ZIP_CONTENT = "content.xml";
        // Open office files are zipped. 
        // Walk through it and find "content.xml"

        ZipInputStream zin = null;
        try {
            if (fileData != null) {
                zin = new ZipInputStream(new BufferedInputStream(fileData.getInputStream()));
            } else {
                zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(odsFile)));
            }

            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                if (entry.getName().equals(ZIP_CONTENT)) {
                    break;
                }
            }
            SAXParserFactory spf = SAXParserFactory.newInstance();
            //spf.setValidating(validate);

            SAXParser parser = spf.newSAXParser();
            reader = parser.getXMLReader();

            // reader.setErrorHandler(new MyErrorHandler());
            reader.setContentHandler(this);
            // reader.parse(new InputSource(zf.getInputStream(entry)));

            reader.parse(new InputSource(zin));

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXParseException spe) {
            spe.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zin != null)
                zin.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //from w  w  w . j a va  2s . c om
 * getArtistArt
 * 
 *********************************/
private String getArtistArt(String artistName) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader;
        xmlReader = saxParser.getXMLReader();
        XMLArtistInfoHandler xmlHandler = new XMLArtistInfoHandler();
        xmlReader.setContentHandler(xmlHandler);
        /*
         * Get artist art from Last.FM
         */
        String artistNameFiltered = filterString(artistName);
        URL lastFmApiRequest = new URL(
                this.LAST_FM_ARTIST_GETINFO_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
        BufferedReader in = new BufferedReader(new InputStreamReader(lastFmApiRequest.openStream()));
        xmlReader.parse(new InputSource(in));

        if (xmlHandler.xlargeAlbumArt != null) {
            return xmlHandler.xlargeAlbumArt;
        } else if (xmlHandler.largeAlbumArt != null) {
            return xmlHandler.largeAlbumArt;
        } else if (xmlHandler.mediumAlbumArt != null) {
            return xmlHandler.mediumAlbumArt;
        }

        return null;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //from  w w w.  j  a  v a 2 s.  com
 * getAlbumArtByAlbumName
 * 
 *********************************/
private String getAlbumArtByAlbumName(String albumName, String artistName) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader;
        xmlReader = saxParser.getXMLReader();
        XMLAlbumSearchHandler xmlHandler = new XMLAlbumSearchHandler();
        xmlReader.setContentHandler(xmlHandler);
        /*
         * Get artist art from Last.FM
         */
        String artistNameFiltered = filterString(artistName);
        String albumNameFiltered = filterString(albumName);
        URL lastFmApiRequest = new URL(
                this.LAST_FM_ALBUM_SEARCH_URL + "&album=" + URLEncoder.encode(albumNameFiltered));
        BufferedReader in = new BufferedReader(new InputStreamReader(lastFmApiRequest.openStream()));
        xmlReader.parse(new InputSource(in));

        for (int i = 0; i < xmlHandler.albumSearchList.size(); i++) {
            AlbumSearch albumSearch = xmlHandler.albumSearchList.get(i);
            if (artistNameIsSimilarEnough(filterString(albumSearch.artistName), artistNameFiltered)) {
                if (albumSearch.xlargeAlbumArt != null) {
                    return albumSearch.xlargeAlbumArt;
                } else if (albumSearch.largeAlbumArt != null) {
                    return albumSearch.largeAlbumArt;
                } else if (albumSearch.mediumAlbumArt != null) {
                    return albumSearch.mediumAlbumArt;
                }
            }
        }
        return null;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}