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:eionet.cr.util.xml.XmlAnalysis.java

/**
 *
 * @param inputStream//from  www . j av  a  2 s  .c  o  m
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws GDEMException
 * @throws SAXException
 * @throws IOException
 */
public void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {

    // set up the parser and reader
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    // turn off validation against schema or dtd (we only need the document to be well-formed XML)
    parserFactory.setValidating(false);
    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);

    // turn on dtd handling
    doctypeReader = new SAXDoctypeReader();
    try {
        parser.setProperty("http://xml.org/sax/properties/lexical-handler", doctypeReader);
    } catch (SAXNotRecognizedException e) {
        logger.warn("Installed XML parser does not provide lexical events", e);
    } catch (SAXNotSupportedException e) {
        logger.warn("Cannot turn on comment processing here", e);
    }

    // set the handler and do the parsing
    handler = new Handler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(inputStream));
    } catch (SAXException e) {
        Exception ee = e.getException();
        if (ee == null || !(ee instanceof CRException))
            throw e;
    }
}

From source file:com.farmafene.commons.cas.ValidateTGT.java

/**
 * Retrieve the text for a specific element (when we know there is only
 * one)./*from   ww w. j a va2  s. com*/
 * 
 * @param xmlAsString
 *            the xml response
 * @param element
 *            the element to look for
 * @return the text value of the element.
 */
private String getTextForElement(final String xmlAsString, final String element) {
    final XMLReader reader = getXmlReader();
    final StringBuffer buffer = new StringBuffer();

    final DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        public void startElement(final String uri, final String localName, final String qName,
                final Attributes attributes) throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = true;
            }
        }

        public void endElement(final String uri, final String localName, final String qName)
                throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = false;
            }
        }

        public void characters(char[] ch, int start, int length) throws SAXException {
            if (this.foundElement) {
                buffer.append(ch, start, length);
            }
        }
    };

    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);

    try {
        reader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (final Exception e) {
        logger.error("", e);
        return null;
    }

    return buffer.toString();
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {//from   w  w  w .  jav  a 2s  . c o m
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

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

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

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

/**
 * Parses the <code>InputSource</code>
 * @param input A <code>InputSource</code> object.
 * @throws SAXException//from   w w  w .  j a  v  a 2 s  . co  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:self.philbrown.droidQuery.Ajax.java

protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled)
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {/*from   ww  w.jav a 2s.  c  o  m*/
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(Ajax.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(Ajax.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.allHeaders = null;
        return s;

    }

    if (connection == null) {
        try {
            String type = options.type();
            URL url = new URL(options.url());
            if (type == null) {
                type = "GET";
            }
            if (type.equalsIgnoreCase("CUSTOM")) {

                try {
                    connection = options.customConnection();
                } catch (Exception e) {
                    connection = null;
                }

                if (connection == null) {
                    Log.w("droidQuery.ajax",
                            "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                }
            } else {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod(type);
                if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) {
                    connection.setDoOutput(true);
                }
            }
        } catch (Throwable t) {
            if (options.debug())
                t.printStackTrace();
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = 0;
            e.reason = "Bad Configuration";
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = new Headers();
            e.error = error;
            return e;
        }

    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", null);
    args.put("connection", connection);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            OutputStream os = connection.getOutputStream();
            os.write(options.data().toString().getBytes());
            os.close();
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    if (options.timeout() != 0) {
        connection.setConnectTimeout(options.timeout());
        connection.setReadTimeout(options.timeout());
    }

    if (options.trustedCertificate() != null) {

        Certificate ca = options.trustedCertificate();

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
        } catch (KeyStoreException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (CertificateException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (IOException e) {
            if (options.debug())
                e.printStackTrace();
        }

        if (keyStore == null) {
            Log.w("Ajax", "Could not configure trusted certificate");
        } else {
            try {
                //Create a TrustManager that trusts the CAs in our KeyStore
                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                tmf.init(keyStore);

                //Create an SSLContext that uses our TrustManager
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tmf.getTrustManagers(), null);
                ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            } catch (KeyManagementException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (KeyStoreException e) {
                if (options.debug())
                    e.printStackTrace();
            }
        }
    }

    try {

        if (options.cookies() != null) {
            CookieManager cm = new CookieManager();
            CookieStore cookies = cm.getCookieStore();
            URI uri = URI.create(options.url());
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue());
                cookies.add(uri, cookie);
            }
            connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies()));
        }

        connection.connect();
        final int statusCode = connection.getResponseCode();
        final String message = connection.getResponseMessage();

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), connection, options.dataType());
            else
                options.dataFilter().invoke(null, connection, options.dataType());
        }

        final Function function = options.statusCode().get(statusCode);
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusCode, options.clone());
                    else
                        function.invoke(null, statusCode, options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        InputStream stream = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseText(stream);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(stream, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(stream, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(stream));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(connection);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(connection);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(connection);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseImage(stream);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(connection);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } finally {
            connection.disconnect();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
            }
        }

        if (statusCode >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = e.status;
            e.reason = e.reason;
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified");
            if (lastModifiedHeaders.size() >= 1) {
                try {
                    String h = lastModifiedHeaders.get(0);
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h);
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.connection = connection;
                            error.options = options;
                            e.status = e.status;
                            e.reason = e.reason;
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = message;
            s.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (connection != null)
                e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            else
                e.allHeaders = new Headers();
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:com.g2inc.scap.library.domain.SCAPContentManager.java

public List<File> getOvalFiles(File dir) {
    ArrayList<File> ovalFileList = new ArrayList<File>();
    // get list of all xml files in dir
    File[] xmlFiles = dir.listFiles(new FilenameFilter() {
        @Override/*w w  w. j  a v  a  2  s .co  m*/
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });
    if (xmlFiles != null && xmlFiles.length > 0) {
        try {
            SAXParserFactory saxfactory = SAXParserFactory.newInstance();
            saxfactory.setValidating(false);
            saxfactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            saxfactory.setFeature("http://xml.org/sax/features/validation", false);

            for (int i = 0; i < xmlFiles.length; i++) {
                SAXParser saxparser = saxfactory.newSAXParser();
                XMLReader xmlReader = saxparser.getXMLReader();
                OvalParser ovalParser = new OvalParser();
                xmlReader.setContentHandler(ovalParser);
                FileInputStream inStream = new FileInputStream(xmlFiles[i]);
                xmlReader.parse(new InputSource(inStream));
                if (ovalParser.isOval()) {
                    ovalFileList.add(xmlFiles[i]);
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Caught an error trying list oval files in directory " + dir.getAbsolutePath(), e);
        }
    }
    return ovalFileList;
}

From source file:edwardawebb.queueman.classes.NetFlix.java

/**
 * //from   w w w.j  a  va2s.  c o m
 * @param queueType
 * @param maxResults
 * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions
 */
public int getHomeTitles() {
    URL QueueUrl = null;
    int result = NF_ERROR_BAD_DEFAULT;

    String expanders = "?expand=synopsis,formats";
    InputStream xml = null;
    try {

        if (!NetFlix.homeQueue.isEmpty())
            return 200;
        QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/at_home" + expanders);
        HomeQueueHandler myHandler = new HomeQueueHandler();
        Log.d("NetFlix", "" + QueueUrl.toString());

        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();
        result = request.getResponseCode();
        xml = request.getInputStream();

        /*BufferedReader in = new BufferedReader(new
        InputStreamReader(xml)); String linein = null; while ((linein =
        in.readLine()) != null) { Log.d("NetFlixQueue", "" +
        linein); }*/

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

    } catch (ParserConfigurationException e) {

        reportError(e, lastResponseMessage);
    } catch (SAXException e) {

        reportError(e, lastResponseMessage);
    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    return result;
}

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

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

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

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

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

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

From source file:edwardawebb.queueman.classes.NetFlix.java

/**
 * /*w  ww.j ava2  s .co  m*/
 * @param queueType
 * @param maxResults
 * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions
 */
public int getRecommendations(int startIndex, String maxResults) {
    times[0] = System.currentTimeMillis();
    URL QueueUrl = null;
    int result = NF_ERROR_BAD_DEFAULT;
    if (maxResults.equals(QueueMan.ALL_TITLES_STRING)) {
        maxResults = "500";
    }

    String expanders = "?expand=synopsis,formats&start_index=" + startIndex + "&max_results=" + maxResults;
    InputStream xml = null;
    try {
        // we're either rotating/task jumping OR we're starting/paging
        /*if (!NetFlix.recomemendedQueue.isEmpty() && startIndex == recomemendedQueue.getStartIndex()){
           return 200;
        }else if(recomemendedQueue.getTotalTitles() < startIndex){
           return NF_ERROR_NO_MORE;
        }else{
           recomemendedQueue.purge();
        }*/

        QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/recommendations" + expanders);
        RecommendationsHandler myHandler = new RecommendationsHandler(this);
        Log.d("NetFlix", "" + QueueUrl.toString());

        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();
        result = request.getResponseCode();
        xml = request.getInputStream();

        /*   BufferedReader in = new BufferedReader(new
               InputStreamReader(xml)); String linein = null; while ((linein =
               in.readLine()) != null) { Log.d("NetFlixQueue", "" +
               linein); }*/

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

    } catch (ParserConfigurationException e) {

        reportError(e, lastResponseMessage);
    } catch (SAXException e) {

        reportError(e, lastResponseMessage);
    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    times[1] = System.currentTimeMillis();
    return result;
}

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.
 */// www  .ja  va  2  s .c o  m
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;
}