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:de.mpg.mpdl.inge.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./*from  w  w  w. j  a  va  2s.c om*/
 * 
 * @throws Exception
 */
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.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//from   w ww. j  a va  2s .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:com.binomed.showtime.android.util.CineShowtimeRequestManage.java

public static void completeMovieDetail(Context context, MovieBean movie, String near) throws Exception {
    URLBuilder andShowtimeUriBuilder = new URLBuilder(CineShowTimeEncodingUtil.convertLocaleToEncoding());
    andShowtimeUriBuilder.setProtocol(HttpParamsCst.BINOMED_APP_PROTOCOL);
    andShowtimeUriBuilder.setAdress(getAppEngineUrl(context));
    andShowtimeUriBuilder.completePath(HttpParamsCst.IMDB_GET_METHODE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LANG, Locale.getDefault().getLanguage());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OUTPUT, HttpParamsCst.VALUE_XML);
    // andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_ZIP, HttpParamsCst.VALUE_TRUE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_IE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MOVIE_ID, movie.getId());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_TRAILER, String.valueOf(true));
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MOVIE_NAME, movie.getEnglishMovieName());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MOVIE_CUR_LANG_NAME, movie.getMovieName());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, URLEncoder
            .encode((near != null) ? near : SpecialChars.EMPTY, CineShowTimeEncodingUtil.getEncoding()));

    String uri = andShowtimeUriBuilder.toUri();
    Log.i(TAG, "send request : " + uri); //$NON-NLS-1$
    HttpGet getMethod = CineShowtimeFactory.getHttpGet();
    getMethod.setURI(new URI(uri));
    HttpResponse res = CineShowtimeFactory.getHttpClient().execute(getMethod);

    XMLReader reader = CineShowtimeFactory.getXmlReader();
    ParserImdbResultXml parser = CineShowtimeFactory.getParserImdbResultXml();

    reader.setContentHandler(parser);
    InputSource inputSource = CineShowtimeFactory.getInputSource();
    // inputSource.setByteStream(new GZIPInputStream(res.getEntity().getContent()));
    inputSource.setByteStream(res.getEntity().getContent());

    reader.parse(inputSource);// w  ww. jav  a  2s. co m

    MovieBean movieResult = parser.getMovieBean();

    movie.setImdbDesrciption(movieResult.isImdbDesrciption());
    movie.setDescription(movieResult.getDescription());
    movie.setUrlImg(movieResult.getUrlImg());
    movie.setUrlWikipedia(movieResult.getUrlWikipedia());
    movie.setImdbId(movieResult.getImdbId());
    movie.setRate(movieResult.getRate());
    movie.setStyle(movieResult.getStyle());
    movie.setDirectorList(movieResult.getDirectorList());
    movie.setActorList(movieResult.getActorList());
    movie.setReviews(movieResult.getReviews());
    movie.setYoutubeVideos(movieResult.getYoutubeVideos());

}

From source file:com.binomed.showtime.android.util.CineShowtimeRequestManage.java

private static String getAppEngineUrl(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String appEngineUrl = prefs.getString(CineShowtimeCst.PREF_KEY_APP_ENGINE, null);
    if (appEngineUrl == null) {
        try {/*from   w  w w .ja v  a 2  s .  com*/
            URLBuilder andShowtimeUriBuilder = new URLBuilder(
                    CineShowTimeEncodingUtil.convertLocaleToEncoding());
            andShowtimeUriBuilder.setProtocol(HttpParamsCst.BINOMED_APP_PROTOCOL);
            andShowtimeUriBuilder.setAdress(HttpParamsCst.BINOMED_APP_URL);
            andShowtimeUriBuilder.completePath(HttpParamsCst.BINOMED_APP_PATH);
            andShowtimeUriBuilder.completePath(HttpParamsCst.SEVER_GET_METHODE);
            String uri = andShowtimeUriBuilder.toUri();
            Log.i(TAG, "send request : " + uri); //$NON-NLS-1$
            HttpGet getMethod = CineShowtimeFactory.getHttpGet();
            getMethod.setURI(new URI(uri));
            HttpResponse res = CineShowtimeFactory.getHttpClient().execute(getMethod);
            XMLReader reader = CineShowtimeFactory.getXmlReader();
            ParserSimpleResultXml parser = CineShowtimeFactory.getParserSimpleResultXml();
            reader.setContentHandler(parser);
            InputSource inputSource = CineShowtimeFactory.getInputSource();
            inputSource.setByteStream(res.getEntity().getContent());

            reader.parse(inputSource);

            appEngineUrl = parser.getUrl();
            if ((appEngineUrl == null) || (appEngineUrl.length() == 0)) {
                appEngineUrl = HttpParamsCst.BINOMED_APP_URL;
            }

            try {
                Editor editor = prefs.edit();
                editor.putString(CineShowtimeCst.PREF_KEY_APP_ENGINE, appEngineUrl);
                editor.commit();
            } catch (Exception e) {
            }
        } catch (Exception e) {
            appEngineUrl = HttpParamsCst.BINOMED_APP_URL;
        }
        Log.i(TAG, "result : " + appEngineUrl); //$NON-NLS-1$
    }

    return appEngineUrl;

}

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  ww  w  .  j  av  a 2  s  .c  om*/
    ;

    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:com.binomed.showtime.android.util.CineShowtimeRequestManage.java

public static NearResp searchTheatersOrMovies(Context context, Double latitude, Double longitude,
        String cityName, String movieName, String theaterId, int day, int start, String origin,
        String hourLocalized, String minutesLocalized) throws Exception {

    URLBuilder andShowtimeUriBuilder = new URLBuilder(CineShowTimeEncodingUtil.convertLocaleToEncoding());
    andShowtimeUriBuilder.setProtocol(HttpParamsCst.BINOMED_APP_PROTOCOL);
    andShowtimeUriBuilder.setAdress(getAppEngineUrl(context));
    andShowtimeUriBuilder.completePath(HttpParamsCst.BINOMED_APP_PATH);
    andShowtimeUriBuilder//w ww.j av a2 s  . c  o m
            .completePath(((movieName != null) && (movieName.length() > 0)) ? HttpParamsCst.MOVIE_GET_METHODE
                    : HttpParamsCst.NEAR_GET_METHODE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LANG, Locale.getDefault().getLanguage());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OUTPUT, HttpParamsCst.VALUE_XML);
    // andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_ZIP, HttpParamsCst.VALUE_TRUE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_IE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_CURENT_TIME,
            String.valueOf(Calendar.getInstance().getTimeInMillis()));
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_TIME_ZONE, TimeZone.getDefault().getID());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_HOUR_LOCALIZE, hourLocalized);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MIN_LOCALIZE, minutesLocalized);

    if (theaterId != null) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_THEATER_ID //
                , theaterId);
    }
    if (day > 0) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_DAY //
                , String.valueOf(day));
    }
    if (start > 0) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_START //
                , String.valueOf(start));
    }
    String countryCode = Locale.getDefault().getCountry();

    Geocoder geocoder = CineShowtimeFactory.getGeocoder();
    Location originalPlace = null;
    if (geocoder != null) {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocationName(cityName, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching cityName :" + cityName, e);
            }
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                // if (addressList.get(0).getLocality() != null &&
                // addressList.get(0).getPostalCode() != null) {
                // cityName += " " + addressList.get(0).getPostalCode();
                // }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }

                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());

                countryCode = addressList.get(0).getCountryCode();
            }
            if (cityName != null) {
                andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
            }
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching latitude, longitude :" + latitude + "," + longitude, e);
            }
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getPostalCode() != null)) {
                    cityName += " " + addressList.get(0).getPostalCode();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }
                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());

                countryCode = addressList.get(0).getCountryCode();
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
            if (cityName != null) {
                andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
            }
        }
    } else {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
        }
    }
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_COUNTRY_CODE, countryCode);

    if (movieName != null) {
        try {
            movieName = URLDecoder.decode(movieName, CineShowTimeEncodingUtil.getEncoding());
        } catch (Exception e) {
            Log.e(TAG, "error during decoding", e);
        }
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MOVIE_NAME, movieName);
    }

    String uri = andShowtimeUriBuilder.toUri();
    Log.i(TAG, "send request : " + uri); //$NON-NLS-1$
    HttpGet getMethod = CineShowtimeFactory.getHttpGet();
    getMethod.setURI(new URI(uri));
    HttpResponse res = CineShowtimeFactory.getHttpClient().execute(getMethod);

    XMLReader reader = CineShowtimeFactory.getXmlReader();
    ParserNearResultXml parser = CineShowtimeFactory.getParserNearResultXml();
    reader.setContentHandler(parser);
    InputSource inputSource = CineShowtimeFactory.getInputSource();
    // inputSource.setByteStream(new GZIPInputStream(res.getEntity().getContent()));
    inputSource.setByteStream(res.getEntity().getContent());

    reader.parse(inputSource);

    NearResp resultBean = parser.getNearRespBean();
    resultBean.setCityName(cityName);

    return resultBean;
}

From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java

private static XMLReader createXMLReader(DefaultHandler handler)
        throws SAXException, ParserConfigurationException {
    XMLReader reader = spf.newSAXParser().getXMLReader();
    reader.setContentHandler(handler);
    return reader;
}

From source file:Examples.java

/**
 * Show the Transformer as a SAX2 XMLReader.  An XMLFilter obtained 
 * from newXMLFilter should act as a transforming XMLReader if setParent is not
 * called.  Internally, an XMLReader is created as the parent for the XMLFilter.
 *///from  w  w  w . jav a2s.c o m
public static void exampleXMLReader(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException // , ParserConfigurationException
{
    TransformerFactory tfactory = TransformerFactory.newInstance();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        XMLReader reader = ((SAXTransformerFactory) tfactory).newXMLFilter(new StreamSource(xslID));

        reader.setContentHandler(new ExampleContentHandler());

        reader.parse(new InputSource(sourceID));
    } else
        System.out.println("tfactory does not support SAX features!");
}

From source file:de.zib.scalaris.examples.wikipedia.data.xml.Main.java

/**
 * @param handler// ww w. jav  a 2s . c  o  m
 * @param file
 * @throws SAXException
 * @throws IOException
 */
private static void runXmlHandler(WikiDumpHandler handler, InputSource[] files)
        throws SAXException, IOException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    handler.setUp();
    ReportAtShutDown shutdownHook = handler.new ReportAtShutDown();
    Runtime.getRuntime().addShutdownHook(shutdownHook);
    reader.setContentHandler(handler);
    for (InputSource file : files) {
        reader.parse(file);
    }
    handler.tearDown();
    shutdownHook.reportAtEnd();
    Runtime.getRuntime().removeShutdownHook(shutdownHook);
    exitCheckHandler(handler);
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an XML input stream to a JSON stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param XMLStream The XML stream to convert to JSON
 * @param JSONStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws SAXException Thrown if a parse error occurs.
 * @throws IOException Thrown if an IO error occurs.
 *///from w ww  .j av  a2 s.c o  m
public static void toJson(InputStream XMLStream, OutputStream JSONStream, boolean verbose)
        throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toJson(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform",
                    "Fetching a SAX parser for use with JSONSAXHandler");
        }

        try {
            /**
             * Get a parser.
             */
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser sParser = factory.newSAXParser();
            XMLReader parser = sParser.getXMLReader();
            JSONSAXHandler jsonHandler = new JSONSAXHandler(JSONStream, verbose);
            parser.setContentHandler(jsonHandler);
            parser.setErrorHandler(jsonHandler);
            InputSource source = new InputSource(new BufferedInputStream(XMLStream));

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the XML content to JSON");
            }

            /** 
             * Parse it.
             */
            source.setEncoding("UTF-8");
            parser.parse(source);
            jsonHandler.flushBuffer();
        } catch (javax.xml.parsers.ParserConfigurationException pce) {
            throw new SAXException("Could not get a parser: " + pce.toString());
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, OutputStream)");
    }
}