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:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //from  w w  w  .  j  av a2s. c o m
 * Get AlbumArt
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getAlbumArt() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Album Cursor
     */
    albumCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ALBUM_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String albumName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLAlbumArtHandler xmlHandler = new XMLAlbumArtHandler();
    //        XMLGoogleAlbumArtHandler xmlGoogleHandler = new XMLGoogleAlbumArtHandler();

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Looking for missing art...");
    msg.setData(data);
    ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

    /*
     * Loop through the albums
     */
    albumCursor.moveToFirst();
    for (int i = 0; i < albumCursor.getCount(); i++) {
        System.gc();
        /*
         * Get Album Details
         */
        artistName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
        albumName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM));

        /*
         * If no Art is available fetch it
         */
        if (getAlbumArtPath(artistName, albumName) == null) {
            Log.i("LastFM", "Album with no Art " + albumName);
            try {
                if ((artistName.equals("<unknown>") && albumName.equals("<unknown>"))) {
                    Log.i("ALBUMART", "Unknown album");
                    albumCursor.moveToNext();
                    continue;
                }
            } catch (Exception e) {
                Log.i("ALBUMART", "Null album or artist");
                albumCursor.moveToNext();
                continue;
            }

            /*
             * Give feedback to the user
             */
            data = new Bundle();
            msg = new Message();
            data.putString("info", albumName);
            msg.setData(data);
            ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

            String albumArtURL = null;
            try {
                /*
                 * Get album URL from Last.FM
                 */
                String artistNameFiltered = filterString(artistName);
                String albumNameFiltered = filterString(albumName);

                if (USE_GOOGLE_IMAGES) {
                    //                    xmlReader.setContentHandler(xmlGoogleHandler);

                    URL googleImagesRequest = new URL(
                            this.GOOGLE_IMAGES_SEARCH_URL + URLEncoder.encode(artistNameFiltered) + "+"
                                    + URLEncoder.encode(albumNameFiltered));
                    //                    Log.i("GOOGLEIMAGES", googleImagesRequest.toString());

                    //                    DefaultHttpClientConnection httpCon = createGoogleImageConnection(
                    //                          googleImagesRequest.toString());
                    /*
                     * retreive URL
                     */
                    BasicHttpParams params = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(params, 10000);
                    DefaultHttpClient httpClient = new DefaultHttpClient();

                    // Get cookies from the login page (not the address same of the form post)
                    HttpGet httpGet = new HttpGet(googleImagesRequest.toString());

                    HttpResponse response;

                    try {
                        /*
                         * Get the page
                         */
                        response = httpClient.execute(httpGet);
                        HttpEntity entity = response.getEntity();
                        BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));

                        /*
                         * Parse 1st existing image on the result page
                         */
                        String line;
                        int idxStart = 0;
                        int idxStop;
                        do {
                            line = in.readLine();
                            if (line != null) {
                                //                           Log.i("GIMAGES", line);
                                if (line.startsWith("<table")) {
                                    boolean found = false;
                                    int tries = 0;
                                    while (!found) {
                                        tries++;
                                        if (tries > 12)
                                            break;
                                        idxStart = line.indexOf("<a href=", idxStart);

                                        if (idxStart == -1) {
                                            line = in.readLine();
                                            if (line == null)
                                                break;
                                            continue;
                                        }

                                        idxStart = line.indexOf("http://", idxStart);
                                        idxStop = line.indexOf("&imgrefurl=", idxStart);
                                        albumArtURL = line.substring(idxStart, idxStop);
                                        Log.i("GIMAGE", line.substring(idxStart, idxStop));

                                        try {
                                            //URL albumArt = new URL(URLEncoder.encode(albumArtURL));
                                            //                                    URL albumArt = new URL(albumArtURL);
                                            //                                    InputStream albumArtURLStream = albumArt.openStream();
                                            //                                    albumArtURLStream.close();
                                            if (albumArtURL != null) {
                                                if (createAlbumArt(artistName, albumName,
                                                        albumArtURL) == null) {
                                                    albumArtURL = null;
                                                    found = false;
                                                    Log.i("GIMAGES", "createAlbumArt FAIL");
                                                } else {
                                                    found = true;
                                                    Log.i("GIMAGES", "createAlbumArt WIN");
                                                }
                                            } else {
                                                albumArtURL = null;
                                                found = false;
                                                Log.i("GIMAGES", "albumArt URL FAIL!");
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            albumArtURL = null;
                                            found = false;
                                        }
                                    }
                                    break;
                                }
                            }
                        } while (line != null);

                        //                     xmlReader.parse(new InputSource(in));

                        entity.consumeContent();

                        //                     for(int j = 0; j < xmlGoogleHandler.MAX_IMAGES; j++){
                        //                        if(xmlGoogleHandler.albumArtUrl[j] != null){
                        //                           albumArtURL = xmlGoogleHandler.albumArtUrl[j];
                        //                           break;
                        //                        }
                        //                     }

                        /*
                         * No luck with the duck
                         */
                        //                     if(albumArtURL == null){
                        //                        Log.i("GOOGLEIMAGES", "Absolutely no luck");
                        //                        // mark this as a problematic album... 
                        //                        // so we dont refetch it all the time
                        //                         createSmallAlbumArt(artistName, albumName, false);
                        //                        albumCursor.moveToNext();
                        //                        continue;
                        //                     } else {
                        //                        Log.i("GOOGLEIMAGES", albumArtURL);
                        //                     }

                        /*
                         * Clear up the Handler
                         */
                        //                     xmlGoogleHandler.clear();

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //                  
                    //                  /*
                    //                  * No Album Art available
                    //                  *  1. try going by the album name
                    //                  *  2. get some artist pic and thats it
                    //                  */
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Could not get album art immediately");
                    //                  Log.i("LASTFM", "Trying sole album search");
                    //                  
                    //                  albumArtURL = getAlbumArtByAlbumName(albumName, artistName);
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Trying to get artist Art");
                    //                  albumArtURL = getArtistArt(artistName);
                    //                  }
                    //                  /*
                    //                  * No luck with the duck
                    //                  */
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Absolutely no luck");
                    //                  // mark this as a problematic album... 
                    //                  // so we dont refetch it all the time
                    //                  createSmallAlbumArt(artistName, albumName, false);
                    //                  albumCursor.moveToNext();
                    //                  continue;
                    //                  }
                    //                  }
                }

                /*
                 * If google images failed try last.fm
                 */
                if (albumArtURL == null) {
                    xmlReader.setContentHandler(xmlHandler);

                    URL lastFmApiRequest = new URL(
                            this.LAST_FM_ALBUM_GETINFO_URL + "&artist=" + URLEncoder.encode(artistNameFiltered)
                                    + "&album=" + URLEncoder.encode(albumNameFiltered));
                    try {
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(lastFmApiRequest.openStream()));
                        xmlReader.parse(new InputSource(in));

                        if (xmlHandler.xlargeAlbumArt != null) {
                            albumArtURL = xmlHandler.xlargeAlbumArt;
                        } else if (xmlHandler.largeAlbumArt != null) {
                            albumArtURL = xmlHandler.largeAlbumArt;
                        } else if (xmlHandler.mediumAlbumArt != null) {
                            albumArtURL = xmlHandler.mediumAlbumArt;
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    /*
                     * No Album Art available
                     *  1. try going by the album name
                     *  2. get some artist pic and thats it
                     */
                    if (albumArtURL == null) {
                        Log.i("LASTFM", "Could not get album art immediately");
                        Log.i("LASTFM", "Trying sole album search");

                        albumArtURL = getAlbumArtByAlbumName(albumName, artistName);
                        if (albumArtURL == null) {
                            Log.i("LASTFM", "Trying to get artist Art");
                            albumArtURL = getArtistArt(artistName);
                        }
                        /*
                         * No luck with the duck
                         */
                        if (albumArtURL == null) {
                            Log.i("LASTFM", "Absolutely no luck");
                            // mark this as a problematic album... 
                            // so we dont refetch it all the time
                            createSmallAlbumArt(artistName, albumName, false);
                            albumCursor.moveToNext();
                            continue;
                        }
                    }

                    /* only reaches here if not FAIL */
                    createAlbumArt(artistName, albumName, albumArtURL);

                }

                /*
                 * reset xml handler
                 */
                xmlHandler.smallAlbumArt = null;
                xmlHandler.mediumAlbumArt = null;
                xmlHandler.largeAlbumArt = null;
                xmlHandler.xlargeAlbumArt = null;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        /*
         * Create small album art
         */
        createSmallAlbumArt(artistName, albumName, true);

        /*
        * Give feedback to the user
        */
        //Bundle data = new Bundle();
        //Message msg = new Message();
        //data.putString("info", "Creating Thumbnail");
        //msg.setData(data);
        //((Filex) context).getAlbumArtHandler.sendMessage(msg);

        albumCursor.moveToNext();
    }

    /*
     * Give feedback to the user
     */
    data = new Bundle();
    msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

    /*
     * Set the last import date on preferences
     */
    //        SharedPreferences settings = ((Filex) this.context).getSharedPreferences(((Filex) this.context).PREFS_NAME, 0);
    //        Editor editor = settings.edit();
    //        editor.putLong("artImportDate", System.currentTimeMillis());
    //        editor.commit();
    RockOnPreferenceManager settings = new RockOnPreferenceManager(
            ((RockPlayer) context).FILEX_PREFERENCES_PATH);
    settings.putLong("artImportDate", System.currentTimeMillis());

    //settings.
    //   long lastAlbumArtImportDate = settings.getLong("artImportDate", 0);
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

private void xmlImport(InputStream in) throws IOException, SAXException, ParserConfigurationException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);
    prefs.edit().putBoolean("enabled", false).apply();
    ServiceSinkhole.stop("import", this);

    XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    XmlImportHandler handler = new XmlImportHandler(this);
    reader.setContentHandler(handler);//www  .  j  a v a2 s  . c o  m
    reader.parse(new InputSource(in));

    xmlImport(handler.application, prefs);
    xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE));
    xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE));
    xmlImport(handler.unused, getSharedPreferences("unused", Context.MODE_PRIVATE));
    xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE));
    xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE));
    xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE));
    xmlImport(handler.apply, getSharedPreferences("apply", Context.MODE_PRIVATE));
    xmlImport(handler.notify, getSharedPreferences("notify", Context.MODE_PRIVATE));

    // Upgrade imported settings
    Receiver.upgrade(true, this);

    // Refresh UI
    prefs.edit().putBoolean("imported", true).apply();
    prefs.registerOnSharedPreferenceChangeListener(this);
}

From source file:com.jiahuan.svgmapview.core.helper.map.SVGParser.java

static SVG parse(InputSource data, SVGHandler handler) throws SVGParseException {
    try {//w  w  w . ja  va  2 s  .  c o m
        final Picture picture = new Picture();
        handler.setPicture(picture);

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(handler);
        xr.setFeature("http://xml.org/sax/features/validation", false);
        if (DISALLOW_DOCTYPE_DECL) {
            try {
                xr.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            } catch (SAXNotRecognizedException e) {
                DISALLOW_DOCTYPE_DECL = false;
            }
        }
        xr.parse(data);

        SVG result = new SVG(picture, handler.bounds);
        // Skip bounds if it was an empty pic
        if (!Float.isInfinite(handler.limits.top)) {
            result.setLimits(handler.limits);
        }
        return result;
    } catch (Exception e) {
        Log.e(TAG, "Failed to parse SVG.", e);
        throw new SVGParseException(e);
    }
}

From source file:eu.faircode.netguard.ActivitySettings.java

private void xmlImport(InputStream in) throws IOException, SAXException, ParserConfigurationException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);
    prefs.edit().putBoolean("enabled", false).apply();
    ServiceSinkhole.stop("import", this, false);

    XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    XmlImportHandler handler = new XmlImportHandler(this);
    reader.setContentHandler(handler);/*from  ww  w.  ja  v  a2  s.  c  o m*/
    reader.parse(new InputSource(in));

    xmlImport(handler.application, prefs);
    xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE));
    xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE));
    xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE));
    xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE));
    xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE));
    xmlImport(handler.lockdown, getSharedPreferences("lockdown", Context.MODE_PRIVATE));
    xmlImport(handler.apply, getSharedPreferences("apply", Context.MODE_PRIVATE));
    xmlImport(handler.notify, getSharedPreferences("notify", Context.MODE_PRIVATE));

    // Upgrade imported settings
    ReceiverAutostart.upgrade(true, this);

    DatabaseHelper.clearCache();

    // Refresh UI
    prefs.edit().putBoolean("imported", true).apply();
    prefs.registerOnSharedPreferenceChangeListener(this);
}

From source file:net.tirasa.hct.cocoon.sax.HippoItemXMLDumper.java

public void dumpHtml(final HCTConnManager connManager, final HippoHtml rtf, final XMLReader xmlReader,
        final String dateFormat, final Locale locale)
        throws SAXException, IOException, ObjectBeanManagerException {

    final AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute(NS_EMPTY, Attribute.NAME.getName(), Attribute.NAME.getName(), XSD_STRING, rtf.getName());
    saxConsumer.startElement(NS_HCT, Element.FIELD.getName(), PREFIX_HCT + ":" + Element.FIELD.getName(),
            attrs);//from w  w w. j  a  v  a2 s  .co  m

    xmlReader.parse(new InputSource(new StringReader(rtf.getContent())));

    final List<HippoGalleryImageSet> images = new ArrayList<HippoGalleryImageSet>();
    final List<HippoAsset> assets = new ArrayList<HippoAsset>();
    final List<HippoDocument> docs = new ArrayList<HippoDocument>();
    for (HippoFacetSelect facetSelect : rtf.getChildBeans(HippoFacetSelect.class)) {
        final HippoItem subElement = ObjectUtils.getHippoItemByUuid(connManager,
                (String) facetSelect.getProperty(HippoNodeType.HIPPO_DOCBASE));
        if (subElement instanceof HippoGalleryImageSet) {
            images.add((HippoGalleryImageSet) subElement);
        }
        if (subElement instanceof HippoAsset) {
            assets.add((HippoAsset) subElement);
        } else if (subElement instanceof HippoDocument) {
            docs.add((HippoDocument) subElement);
        }
    }
    saxConsumer.startElement(NS_HCT, Element.LINKS.getName(), PREFIX_HCT + ":" + Element.LINKS.getName(),
            EMPTY_ATTRS);
    dumpImages(images, Element.LINK.getName(), false);
    dumpAssets(assets, Element.LINK.getName(), false, dateFormat, locale);
    dumpRelatedDocs(docs, Element.LINK.getName(), false);
    saxConsumer.endElement(NS_HCT, Element.LINKS.getName(), PREFIX_HCT + ":" + Element.LINKS.getName());

    saxConsumer.endElement(NS_HCT, Element.FIELD.getName(), PREFIX_HCT + ":" + Element.FIELD.getName());
}

From source file:net.unicon.academus.apps.XHTMLFilter.java

public static void filterHTML(InputSource in, OutputStream os, XHTMLFilterConfig config) {
    try {/* ww w . ja v a2 s .  c o  m*/
        XMLReader r = new Parser();
        Writer w = new OutputStreamWriter(os, "UTF-8");
        r.setFeature(Parser.ignoreBogonsFeature, true);
        r.setContentHandler(new XHTMLFilter(w, config));
        r.parse(in);
    } catch (Exception e) {
        log.error("Unable to parse the given HTML: " + e.getMessage(), e);
        throw new RuntimeException("Unable to parse the given HTML: " + e.getMessage(), e);
    }
}

From source file:nl.b3p.ogc.utils.OgcWfsClient.java

public static AnyNode xmlStringToAnyNode(String xml) throws Exception {
    AnyNode anyNode = null;//from w ww  .  jav a  2s  .c om
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        XMLReader reader = saxParser.getXMLReader();

        org.exolab.castor.xml.util.SAX2ANY handler = new org.exolab.castor.xml.util.SAX2ANY();

        IgnoreEntityResolver r = new IgnoreEntityResolver();
        reader.setEntityResolver(r);

        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        InputSource source = new InputSource(new StringReader(xml));
        reader.parse(source);

        anyNode = handler.getStartingNode();
    } catch (Exception e) {
        log.error("error", e);
    }
    return anyNode;

}

From source file:nl.nn.adapterframework.align.XmlTo.java

public static void translate(String xml, URL schemaURL, DocumentContainer documentContainer)
        throws SAXException, IOException {

    // create the ValidatorHandler
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemaURL);
    ValidatorHandler validatorHandler = schema.newValidatorHandler();

    // create the parser, setup the chain
    XMLReader parser = new SAXParser();
    XmlAligner aligner = new XmlAligner(validatorHandler);
    XmlTo<DocumentContainer> xml2object = new XmlTo<DocumentContainer>(aligner, documentContainer);
    parser.setContentHandler(validatorHandler);
    aligner.setContentHandler(xml2object);

    // start translating
    InputSource is = new InputSource(new StringReader(xml));
    parser.parse(is);
}

From source file:nl.nn.adapterframework.pipes.BytesOutputPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    Object result = null;//  w  w  w. j ava2  s. c  om
    Variant in = new Variant(input);

    try {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        FieldsContentHandler fieldsContentHandler = new FieldsContentHandler();
        parser.setContentHandler(fieldsContentHandler);
        parser.parse(in.asXmlInputSource());
        result = fieldsContentHandler.getResult();
    } catch (SAXException e) {
        throw new PipeRunException(this, "SAXException", e);
    } catch (IOException e) {
        throw new PipeRunException(this, "IOException", e);
    }
    return new PipeRunResult(getForward(), result);
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

static public void parseXml(ContentHandler handler, InputSource source) throws IOException, SAXException {
    XMLReader parser;
    parser = getParser();//w  w  w  . j  a v  a2 s .  c  o m
    parser.setContentHandler(handler);
    parser.parse(source);
}