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:org.peterbaldwin.client.android.delicious.DeliciousApiRequest.java

/**
 * {@inheritDoc}/*from  w  ww .  j  a  v a  2 s.  c  om*/
 */
public void run() {
    Message msg = mHandler.obtainMessage();
    msg.arg1 = mRequestType;
    msg.arg2 = mRequestId;
    msg.what = HANDLE_ERROR;
    msg.obj = "unknown error";
    boolean cacheUpdated = false;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        ContentHandler handler = mResponseHandler.getContentHandler();
        reader.setContentHandler(handler);

        InputStream in = null;
        if (in == null && mUseCache && mCacheFile != null) {
            in = readFromCache();
        }
        if (in == null) {
            in = readFromNetwork();

            if (mUpdateCache && mCacheFile != null) {
                in = updateCache(in);
                cacheUpdated = true;
            }
        }
        try {
            InputSource input = new InputSource(in);
            long start = now();
            try {
                reader.parse(input);
            } finally {
                logTiming("parse", start);
            }
        } finally {
            in.close();
        }
        msg.what = HANDLE_DONE;
        msg.obj = mResponseHandler;
    } catch (ConnectionException e) {
        setError(msg, e);
        int statusCode = e.getStatusCode();
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            msg.what = HANDLE_AUTH_ERROR;
            msg.obj = "invalid username or password";
        } else {
            msg.what = HANDLE_ERROR;
            msg.obj = "unexpected response: " + statusCode;
        }
    } catch (IOException e) {
        setError(msg, e);
    } catch (ParserConfigurationException e) {
        setError(msg, e);
    } catch (SAXException e) {
        setError(msg, e);
    } catch (RuntimeException e) {
        setError(msg, e);
    } catch (Error e) {
        setError(msg, e);
    } finally {
        mHandler.sendMessage(msg);
    }

    if (msg.what != HANDLE_AUTH_ERROR && !cacheUpdated && mAlwaysUpdateCache && mCacheFile != null) {
        // If the authentication is valid, but the cache was not updated,
        // silently update the cache in the background after dispatching the
        // result to the handler.
        try {
            InputStream in = readFromNetwork();
            in = updateCache(in);
            in.close();
            Log.i(LOG_TAG, "cache file updated: " + mCacheFile);
        } catch (IOException e) {
            Log.e(LOG_TAG, "error updating cache", e);
        } catch (RuntimeException e) {
            Log.e(LOG_TAG, "error updating cache", e);
        } catch (Error e) {
            Log.e(LOG_TAG, "error updating cache", e);
        }
    }
}

From source file:net.ontopia.topicmaps.xml.TMXMLReader.java

@Override
public void importInto(TopicMapIF topicmap) throws IOException {
    // Check that store is ok
    TopicMapStoreIF store = topicmap.getStore();
    if (store == null)
        throw new IOException("Topic map not connected to a store.");

    XMLReader parser;
    try {/*from   w  w  w .  jav a  2  s .com*/
        parser = DefaultXMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        throw new IOException("Problems occurred when creating SAX2 XMLReader: " + e.getMessage());
    }

    // Register content handlers
    ContentHandler handler = new TMXMLContentHandler(topicmap, base_address);
    if (validate)
        handler = new ValidatingContentHandler(handler, getTMXMLSchema(), true);
    parser.setContentHandler(handler);

    // Parse input source
    try {
        parser.parse(source);
    } catch (SAXException e) {
        if (e.getException() instanceof IOException)
            throw (IOException) e.getException();
        throw new OntopiaRuntimeException(e);
        //throw new IOException("XML related problem: " + e.toString());
    }
}

From source file:self.philbrown.javaQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    //handle cached responses
    CachedResponse cachedResponse = URLresponses
            .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()));
    //handle ajax caching option
    if (cachedResponse != null) {
        if (options.cache()) {
            if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) {
                //return cached response
                Success s = new Success();
                s.obj = cachedResponse.response;
                s.reason = "cached response";
                s.headers = null;//  ww w.  jav a2 s. com
                return s;
            }
        }

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("javaQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    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()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    HttpClient client = new DefaultHttpClient(params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

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

        StatusLine statusLine = response.getStatusLine();

        Function function = options.statusCode().get(statusLine);
        if (function != null) {
            if (options.context() != null)
                function.invoke(new $(options.context()));
            else
                function.invoke(null);
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } else {
            //handle dataType
            String dataType = options.dataType();
            if (dataType == null)
                dataType = "text";
            Object parsedResponse = null;
            boolean success = true;
            try {
                if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                    parsedResponse = parseText(response);
                } else if (dataType.equalsIgnoreCase("xml")) {
                    if (options.customXMLParser() != null) {
                        InputStream is = response.getEntity().getContent();
                        if (options.SAXContentHandler() != null)
                            options.customXMLParser().parse(is, options.SAXContentHandler());
                        else
                            options.customXMLParser().parse(is, new DefaultHandler());
                        parsedResponse = "Response handled by custom SAX parser";
                    } else if (options.SAXContentHandler() != null) {
                        InputStream is = response.getEntity().getContent();

                        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(is));
                        parsedResponse = "Response handled by custom SAX content handler";
                    } else {
                        parsedResponse = parseXML(response);
                    }
                } else if (dataType.equalsIgnoreCase("json")) {
                    parsedResponse = parseJSON(response);
                } else if (dataType.equalsIgnoreCase("script")) {
                    parsedResponse = parseScript(response);
                } else if (dataType.equalsIgnoreCase("image")) {
                    parsedResponse = parseImage(response);
                }
            } catch (ClientProtocolException cpe) {
                if (options.debug())
                    cpe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            } catch (Exception ioe) {
                if (options.debug())
                    ioe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            }
            if (success) {
                //Handle cases where successful requests still return errors (these include
                //configurations in AjaxOptions and HTTP Headers
                String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType());
                CachedResponse cache = URLresponses.get(key);
                Date now = new Date();
                //handle ajax caching option
                if (cache != null) {
                    if (options.cache()) {
                        if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) {
                            parsedResponse = cache;
                        } else {
                            cache.response = parsedResponse;
                            cache.timestamp = now;
                            synchronized (URLresponses) {
                                URLresponses.put(key, cache);
                            }
                        }
                    }

                }
                //handle ajax ifModified option
                Header[] lastModifiedHeaders = response.getHeaders("last-modified");
                if (lastModifiedHeaders.length >= 1) {
                    try {
                        Header h = lastModifiedHeaders[0];
                        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                        Date lastModified = format.parse(h.getValue());
                        if (options.ifModified() && lastModified != null) {
                            if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) {
                                //request response has not been modified. 
                                //Causes an error instead of a success.
                                Error e = new Error();
                                AjaxError error = new AjaxError();
                                error.request = request;
                                error.options = options;
                                e.status = statusLine.getStatusCode();
                                e.reason = statusLine.getReasonPhrase();
                                error.status = e.status;
                                error.reason = e.reason;
                                e.headers = response.getAllHeaders();
                                e.error = error;
                                Function func = options.statusCode().get(304);
                                if (func != null) {
                                    if (options.context() != null)
                                        func.invoke(new $(options.context()));
                                    else
                                        func.invoke(null);
                                }
                                return e;
                            } else {
                                cache.lastModified = lastModified;
                                synchronized (URLresponses) {
                                    URLresponses.put(key, cache);
                                }
                            }
                        }
                    } catch (Throwable t) {
                        Log.e("Ajax", "Could not parse Last-Modified Header");
                    }

                }

                //Now handle a successful request

                Success s = new Success();
                s.obj = parsedResponse;
                s.reason = statusLine.getReasonPhrase();
                s.headers = response.getAllHeaders();
                return s;
            }
            //success
            Success s = new Success();
            s.obj = parsedResponse;
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            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 (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:com.entertailion.java.fling.FlingFrame.java

public void onBroadcastFound(final BroadcastAdvertisement advert) {
    if (advert.getLocation() != null) {
        new Thread(new Runnable() {
            public void run() {
                Log.d(LOG_TAG, "location=" + advert.getLocation());
                HttpResponse response = new HttpRequestHelper().sendHttpGet(advert.getLocation());
                if (response != null) {
                    String appsUrl = null;
                    Header header = response.getLastHeader(HEADER_APPLICATION_URL);
                    if (header != null) {
                        appsUrl = header.getValue();
                        if (!appsUrl.endsWith("/")) {
                            appsUrl = appsUrl + "/";
                        }// w ww  . j  a va2 s.c om
                        Log.d(LOG_TAG, "appsUrl=" + appsUrl);
                    }
                    try {
                        InputStream inputStream = response.getEntity().getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                        InputSource inStream = new org.xml.sax.InputSource();
                        inStream.setCharacterStream(reader);
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();
                        XMLReader xr = sp.getXMLReader();
                        BroadcastHandler broadcastHandler = new BroadcastHandler();
                        xr.setContentHandler(broadcastHandler);
                        xr.parse(inStream);
                        Log.d(LOG_TAG, "modelName=" + broadcastHandler.getDialServer().getModelName());
                        // Only handle ChromeCast devices; not other DIAL
                        // devices like ChromeCast devices
                        if (broadcastHandler.getDialServer().getModelName().equals(CHROME_CAST_MODEL_NAME)) {
                            Log.d(LOG_TAG,
                                    "ChromeCast device found: " + advert.getIpAddress().getHostAddress());
                            DialServer dialServer = new DialServer(advert.getLocation(), advert.getIpAddress(),
                                    advert.getPort(), appsUrl,
                                    broadcastHandler.getDialServer().getFriendlyName(),
                                    broadcastHandler.getDialServer().getUuid(),
                                    broadcastHandler.getDialServer().getManufacturer(),
                                    broadcastHandler.getDialServer().getModelName());
                            trackedServers.add(dialServer);
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "parse device description", e);
                    }
                }
            }
        }).start();
    }
}

From source file:Counter.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/*from   ww w  . ja va 2  s.  co  m*/
        System.exit(1);
    }

    // variables
    Counter counter = new Counter();
    PrintWriter out = new PrintWriter(System.out);
    XMLReader parser = null;
    int repetition = DEFAULT_REPETITION;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    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;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;
    boolean tagginess = DEFAULT_TAGGINESS;

    // 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.");
                    continue;
                }
                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.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                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("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.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equalsIgnoreCase("t")) {
                tagginess = option.equals("t");
                continue;
            }
            if (option.equals("-rem")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -# option.");
                    continue;
                }
                System.out.print("# ");
                System.out.println(argv[i]);
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            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(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 + ")");
        }

        // parse file
        parser.setContentHandler(counter);
        parser.setErrorHandler(counter);
        try {
            long timeBefore = System.currentTimeMillis();
            long memoryBefore = Runtime.getRuntime().freeMemory();
            for (int j = 0; j < repetition; j++) {
                parser.parse(arg);
            }
            long memoryAfter = Runtime.getRuntime().freeMemory();
            long timeAfter = System.currentTimeMillis();

            long time = timeAfter - timeBefore;
            long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE;
            counter.printResults(out, arg, time, memory, tagginess, repetition);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);

        }
    }

}

From source file:SAXTreeValidator.java

/**
 * <p>This handles building the Swing UI tree.</p>
 *
 * @param treeModel Swing component to build upon.
 * @param base tree node to build on./*w w  w . ja v a 2s .c  om*/
 * @param xmlURI URI to build XML document from.
 * @throws <code>IOException</code> - when reading the XML URI fails.
 * @throws <code>SAXException</code> - when errors in parsing occur.
 */
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI)
        throws IOException, SAXException {

    // Create instances needed for parsing
    XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass);
    ContentHandler jTreeContentHandler = new JValidatorContentHandler(treeModel, base);
    ErrorHandler jTreeErrorHandler = new JValidatorErrorHandler();

    // Register content handler
    reader.setContentHandler(jTreeContentHandler);

    // Register error handler
    reader.setErrorHandler(jTreeErrorHandler);

    // Turn on validation
    reader.setFeature("http://xml.org/sax/features/validation", true);
    reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    // Parse
    InputSource inputSource = new InputSource(xmlURI);
    reader.parse(inputSource);
}

From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

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

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

    this.stringIcs = ics;
    return Result;
}

From source file:de.suse.swamp.core.util.BugzillaTools.java

private synchronized void xmlToData(String url) throws Exception {

    HttpState initialState = new HttpState();

    String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME");
    String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD");

    if (authUsername != null && authUsername.length() != 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword);
        initialState.setCredentials(AuthScope.ANY, defaultcreds);
    } else {/*  w  ww.  j a va  2 s  .  c  om*/
        Cookie[] cookies = getCookies();
        for (int i = 0; i < cookies.length; i++) {
            initialState.addCookie(cookies[i]);
            Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log);
        }
    }
    HttpClient httpclient = new HttpClient();
    httpclient.setState(initialState);
    HttpMethod httpget = new GetMethod(url);
    try {
        httpclient.executeMethod(httpget);
    } catch (Exception e) {
        throw new Exception("Could not get URL " + url);
    }

    String content = httpget.getResponseBodyAsString();
    char[] chars = content.toCharArray();

    // removing illegal characters from bugzilla output.
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) {
            Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log);
            chars[i] = ' ';
        }
    }
    Logger.DEBUG(String.valueOf(chars), log);
    CharArrayReader reader = new CharArrayReader(chars);
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    parser.setFeature("http://xml.org/sax/features/validation", false);
    // disable parsing of external dtd
    parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
    parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    // get XML File
    BugzillaReader handler = new BugzillaReader();
    parser.setContentHandler(handler);
    InputSource source = new InputSource();
    source.setCharacterStream(reader);
    source.setEncoding("utf-8");
    try {
        parser.parse(source);
    } catch (SAXParseException spe) {
        spe.printStackTrace();
        throw spe;
    }
    httpget.releaseConnection();
    if (errormsg != null) {
        throw new Exception(errormsg);
    }
}

From source file:sundroid.code.SundroidActivity.java

/** Called when the activity is first created. ***/
@Override//w ww . jav a2  s  . c  om
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);
    Button cmd_submit = (Button) findViewById(R.id.cmd_submit);

    cmd_submit.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            try {

                ///////////////// Code to get weather conditions for entered place ///////////////////////////////////////////////////
                String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString();
                String queryString = "https://www.google.com/ig/api?weather=" + cityParamString;
                queryString = queryString.replace("#", "");

                /* Parsing the xml file*/
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();

                GoogleWeatherHandler gwh = new GoogleWeatherHandler();
                xr.setContentHandler(gwh);

                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(queryString.replace(" ", "%20"));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httpget, responseHandler);
                ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
                xr.parse(new InputSource(is));
                Log.d("Sundroid", "parse complete");

                WeatherSet ws = gwh.getWeatherSet();

                newupdateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition(),
                        " " + cityParamString, "");

                ///////////////// Code to get weather conditions for entered place ends /////////////////////////////////////////////////// 

                ///////////////// Code to get latitude and longitude using zipcode starts ///////////////////////////////////////////////////

                String latlng_querystring = "http://maps.googleapis.com/maps/api/geocode/xml?address="
                        + cityParamString.replace(" ", "%20") + "&sensor=false";
                URL url_latlng = new URL(latlng_querystring);
                spf = SAXParserFactory.newInstance();
                sp = spf.newSAXParser();

                xr = sp.getXMLReader();
                xmlhandler_latlong xll = new xmlhandler_latlong();
                xr.setContentHandler(xll);
                xr.parse(new InputSource(url_latlng.openStream()));

                Latitude_longitude ll = xll.getLatlng_resultset();
                double selectedLat = ll.getLat_lng_pair().getLat();
                double selectedLng = ll.getLat_lng_pair().getLon();

                ///////////////// Code to get latitude and longitude using zipcode ends ///////////////////////////////////////////////////

                ///////////////// Code to get miles from text box & convert to meters for passing into the api link////////////////////////
                EditText edt = (EditText) findViewById(R.id.edit_miles);
                float miles = Float.valueOf(edt.getText().toString());
                float meters = (float) (miles * 1609.344);

                ///////////////// Code to get miles from text box & convert to meters for passing into the api link ends /////////////////

                ///////////////// Code to pass lat,long and radius and get destinations from places api starts////////// /////////////////
                URL queryString_1 = new URL("https://maps.googleapis.com/maps/api/place/search/xml?location="
                        + Double.toString(selectedLat) + "," + Double.toString(selectedLng) + "&radius="
                        + Float.toString(meters)
                        + "&types=park|types=aquarium|types=point_of_interest|types=establishment|types=museum&sensor=false&key=AIzaSyDmP0SB1SDMkAJ1ebxowsOjpAyeyiwHKQU");
                spf = SAXParserFactory.newInstance();
                sp = spf.newSAXParser();
                xr = sp.getXMLReader();
                xmlhandler_places xhp = new xmlhandler_places();
                xr.setContentHandler(xhp);
                xr.parse(new InputSource(queryString_1.openStream()));
                int arraysize = xhp.getVicinity_List().size();
                String[] place = new String[25];
                String[] place_name = new String[25];
                Double[] lat_pt = new Double[25];
                Double[] lng_pt = new Double[25];
                int i;
                //Getting name and vicinity tags from the xml file//
                for (i = 0; i < arraysize; i++) {
                    place[i] = xhp.getVicinity_List().get(i);
                    place_name[i] = xhp.getPlacename_List().get(i);
                    lat_pt[i] = xhp.getLatlist().get(i);
                    lng_pt[i] = xhp.getLonglist().get(i);
                    System.out.println("long -" + lng_pt[i]);
                    place[i] = place[i].replace("#", "");

                }

                ///////////////// Code to pass lat,long and radius and get destinations from places api ends////////// /////////////////

                //////////////////////while loop for getting top 5 from the array////////////////////////////////////////////////

                int count = 0;
                int while_ctr = 0;
                String str_weathercondition;
                str_weathercondition = "";
                WeatherCurrentCondition reftemp;
                //Places to visit if none of places in the given radius are sunny/clear/partly cloudy
                String[] rainy_place = { "Indoor Mall", "Watch a Movie", "Go to a Restaurant", "Shopping!" };
                double theDistance = 0;
                String str_dist = "";
                while (count < 5) {
                    //Checking if xml vicinity value is empty
                    while (place[while_ctr] == null || place[while_ctr].length() < 2) {
                        while_ctr = while_ctr + 1;
                    }
                    //First search for places that are sunny or clear 
                    if (while_ctr < i - 1) {
                        queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr];
                        System.out.println("In while loop - " + queryString);
                        theDistance = (Math.sin(Math.toRadians(selectedLat))
                                * Math.sin(Math.toRadians(lat_pt[while_ctr]))
                                + Math.cos(Math.toRadians(selectedLat))
                                        * Math.cos(Math.toRadians(lat_pt[while_ctr]))
                                        * Math.cos(Math.toRadians(selectedLng - lng_pt[while_ctr])));
                        str_dist = new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue()
                                + " miles";
                        System.out.println(str_dist);
                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

                        xr = sp.getXMLReader();

                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);
                        httpclient = new DefaultHttpClient();
                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        if (gwh.isIn_error_information()) {
                            System.out.println("Error Info flag set");
                        } else {
                            ws = gwh.getWeatherSet();

                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            //         Check if the condition is sunny or partly cloudy
                            if (str_weathercondition.equals("Sunny")
                                    || str_weathercondition.equals("Mostly Sunny")
                                    || str_weathercondition.equals("Clear")) {
                                System.out.println("Sunny Loop");

                                //  Increment the count 
                                ++count;

                                //   Disply the place on the widget 
                                if (count == 1) {
                                    newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 2) {
                                    newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 3) {
                                    newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 4) {
                                    newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 5) {
                                    newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else {
                                }
                            }
                        }
                    }

                    //  If Five sunny places not found then search for partly cloudy places 

                    else if (while_ctr >= i && while_ctr < i * 2) {
                        queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr - i];
                        queryString = queryString.replace("  ", " ");

                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

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

                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);

                        // Use HTTPClient to deal with the URL  
                        httpclient = new DefaultHttpClient();
                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        Log.d(DEBUG_TAG, "parse complete");

                        if (gwh.isIn_error_information()) {
                        } else {
                            ws = gwh.getWeatherSet();
                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            //    Check if the condition is sunny or partly cloudy
                            if (str_weathercondition.equals("Partly Cloudy")) {

                                count = count + 1;

                                //  Display the place 
                                if (count == 1) {
                                    newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 2) {
                                    newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 3) {
                                    newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 4) {
                                    newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 5) {
                                    newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else {
                                }
                            }
                        }
                    }
                    ////////////////////////////////  Give suggestions for a rainy day 
                    else {
                        queryString = "https://www.google.com/ig/api?weather=" + cityParamString;
                        queryString = queryString.replace("#", "");

                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

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

                        httpclient = new DefaultHttpClient();

                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        // create a response handler 
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        if (gwh.isIn_error_information()) {
                        }

                        else {
                            ws = gwh.getWeatherSet();

                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            if (count == 0) {
                                newupdateWeatherInfoView(R.id.weather_1, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], "");
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 1) {
                                newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], "");
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[0], "");
                            } else if (count == 2) {
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 3) {
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 4) {
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else {
                            }
                            count = 5;
                        }
                        count = 5;
                    }
                    while_ctr++;
                }

                /////////////Closing the soft keypad////////////////
                InputMethodManager iMethodMgr = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                iMethodMgr.hideSoftInputFromWindow(edt.getWindowToken(), 0);

            } catch (Exception e) {
                resetWeatherInfoViews();
                Log.e(DEBUG_TAG, "WeatherQueryError", e);
            }
        }
    });
}