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.entertailion.java.caster.RampClient.java

private void parseXml(Reader reader) {
    try {/*from  w w  w .j  a v  a2  s. com*/
        InputSource inStream = new org.xml.sax.InputSource();
        inStream.setCharacterStream(reader);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        AppHandler appHandler = new AppHandler();
        xr.setContentHandler(appHandler);
        xr.parse(inStream);

        connectionServiceUrl = appHandler.getConnectionServiceUrl();
        state = appHandler.getState();
        protocol = appHandler.getProtocol();
    } catch (Exception e) {
        Log.e(LOG_TAG, "parse device description", e);
    }
}

From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java

/**
 * Completes the two-part operation started by startPut(), by
 * collecting status of the PUT operation and converting the
 * WebDAV URI of the newly-created resource back to a Handle,
 * which it returns.//  w  w w . j  a v a  2s. co m
 * <p>
 * Any failure results in an exception.
 *
 * @return Handle of the newly-created DSpace resource.
 */
public String finishPut() throws InterruptedException, IOException, SAXException, SAXNotRecognizedException,
        ParserConfigurationException {
    if (lastPutThread != null) {
        lastPutThread.join();
        lastPutThread = null;
    }

    Header loc = lastPut.getResponseHeader("Location");
    lastStatus = lastPut.getStatusCode();
    if (lastStatus < 100 || lastStatus >= 400)
        throw new IOException("PUT returned status = " + lastStatus + "; text=" + lastPut.getStatusText());

    lastPut = null;
    if (loc != null) {
        String newURL = loc.getValue();

        // do a quick PROPFIND to get the handle
        PropfindMethod pf = new PropfindMethod(newURL, propfindBody);
        pf.setDoAuthentication(true);
        client.executeMethod(pf);

        int pfStatus = pf.getStatusCode();
        if (pfStatus < 200 || pfStatus >= 300)
            throw new IOException(
                    "finishPut.propfind got status = " + pfStatus + "; text=" + pf.getStatusText());

        // Maybe move all this crap to within Propfind class??
        // so it can get the inputstream directly?
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        PropfindHandler handler = new PropfindHandler();

        // XXX FIXME: should turn off validation here explicitly, but
        //  it seems to be off by default.
        xr.setFeature("http://xml.org/sax/features/namespaces", true);
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(pf.getResponseBodyAsStream()));

        return handler.handle;
    } else
        throw new IOException("PUT response was missing a Location: header.");
}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {//from w  w  w . j  a v  a 2 s  .com
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:edu.lternet.pasta.dml.dataquery.DataquerySpecification.java

/**
 * construct an instance of the QuerySpecification class
 *
 * @param queryspec/*from  w w  w.j  ava2 s.  c o  m*/
 *            the XML representation of the query (should conform to
 *            dataquery.xsd) as a Reader
 * @param parserName
 *            the fully qualified name of a Java Class implementing the
 *            org.xml.sax.Parser interface
 */
public DataquerySpecification(Reader queryspec, String parserName,
        DatabaseConnectionPoolInterface connectionPool, EcogridEndPointInterface ecogridEndPoint)
        throws IOException {
    super();

    //for the DataManager
    this.connectionPool = connectionPool;
    this.ecogridEndPoint = ecogridEndPoint;

    // Initialize the class variables
    this.parserName = parserName;

    // Initialize the parser and read the queryspec
    XMLReader parser = initializeParser();
    if (parser == null) {
        log.error("SAX parser not instantiated properly.");
    }
    try {
        parser.parse(new InputSource(queryspec));
    } catch (SAXException e) {
        log.error("error parsing data in " + "DataquerySpecification.DataquerySpecification");
        log.error(e.getMessage());
    }
}

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

/**
 * Parses an XML response from a GetCapabilities request and stores available Layers
 * and options in the local SQLite database.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a GetCapabilities request.
 *//*from w  ww . j  a  v a 2 s  . c  o m*/
protected boolean parseXMLResponse(BufferedReader xmlResponse) {
    Log.d(TAG, "parseXMLResponse(Reader) called.");

    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, "XML parsing error: " + e.toString() + " - " + e.getMessage());
        return false;
    }
    return true;
}

From source file:DocumentTracer.java

/** Main. */
public static void main(String[] argv) throws Exception {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from w w  w  .  j  a v a2  s  . com
        System.exit(1);
    }

    // variables
    DocumentTracer tracer = new DocumentTracer();
    PrintWriter out = new PrintWriter(System.out);
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // set handlers
        parser.setDTDHandler(tracer);
        parser.setErrorHandler(tracer);
        if (parser instanceof XMLReader) {
            parser.setContentHandler(tracer);
            try {
                parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer);
            } catch (SAXException e) {
                e.printStackTrace(System.err);
            }
            try {
                parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer);
            } catch (SAXException e) {
                e.printStackTrace(System.err);
            }
        } else {
            ((Parser) parser).setDocumentHandler(tracer);
        }

        // parse file
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

From source file:com.commonsware.android.EMusicDownloader.SingleBook.java

private void getInfoFromXML() {

    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);//from   w  w w  .j a  v  a  2s. com

            try {

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleBook myXMLHandler = new XMLHandlerSingleBook();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                genre = myXMLHandler.genre;
                publisher = myXMLHandler.publisher;
                narrator = myXMLHandler.narrator;
                edition = myXMLHandler.edition;
                artist = myXMLHandler.author;
                authorId = myXMLHandler.authorId;
                if (edition == null) {
                    edition = "";
                }
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                sampleURL = myXMLHandler.sampleURL;
                imageURL = myXMLHandler.imageURL;

                statuscode = myXMLHandler.statuscode;

                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                blurb = myXMLHandler.blurb;
                blurb = blurb.replace("<br> ", "<br>");
                blurbSource = myXMLHandler.blurbSource;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {

                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_book_info);
                    }
                });
                dialog.dismiss();

            }

            handlerDoneLoading.sendEmptyMessage(0);

        }
    };
    t3.start();
}

From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java

/**
 * Converts XML file//from   ww w .j av a  2s  . c om
 * @param xmlSchema XML schema
 * @param outStream OutputStream
 * @throws Exception If an error occurs.
 */
protected void doConversion(String xmlSchema, OutputStream outStream) throws Exception {
    String instanceUrl = DataDictUtil.getInstanceUrl(xmlSchema);

    DD_XMLInstance instance = new DD_XMLInstance(instanceUrl);
    DD_XMLInstanceHandler handler = new DD_XMLInstanceHandler(instance);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    factory.setValidating(false);
    factory.setNamespaceAware(true);
    reader.setFeature("http://xml.org/sax/features/validation", false);
    reader.setFeature("http://apache.org/xml/features/validation/schema", false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);

    reader.setContentHandler(handler);
    reader.parse(instanceUrl);

    if (Utils.isNullStr(instance.getEncoding())) {
        String enc_url = Utils.getEncodingFromStream(instanceUrl);
        if (!Utils.isNullStr(enc_url)) {
            instance.setEncoding(enc_url);
        }
    }
    importSheetSchemas(sourcefile, instance, xmlSchema);
    instance.startWritingXml(outStream);
    sourcefile.writeContentToInstance(instance);
    instance.flushXml();
}

From source file:cm.aptoide.pt.RemoteInTab.java

private void xmlPass(String srv, boolean type) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*w ww  .  j av a  2  s  .  c  om*/
        File xml_file = null;
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        if (type) {
            RssHandler handler = new RssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(XML_PATH);
        } else {
            ExtrasRssHandler handler = new ExtrasRssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(EXTRAS_XML_PATH);
        }

        InputStreamReader isr = new FileReader(xml_file);
        InputSource is = new InputSource(isr);
        xr.parse(is);
        xml_file.delete();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}