Example usage for javax.xml.parsers SAXParser getXMLReader

List of usage examples for javax.xml.parsers SAXParser getXMLReader

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser getXMLReader.

Prototype


public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;

Source Link

Document

Returns the org.xml.sax.XMLReader that is encapsulated by the implementation of this class.

Usage

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;/*from w w w . j ava 2 s.c o  m*/
                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 + "/";
                        }//  ww  w .  j  a v a2  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:com.cloudhopper.sxmp.SxmpParser.java

/**
public Node parse(InputSource source) throws IOException, SAXException {
//        _dtd=null;/*from   www . j  a va  2 s. c  o  m*/
Handler handler = new Handler();
XMLReader reader = _parser.getXMLReader();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
reader.setEntityResolver(handler);
if (logger.isDebugEnabled())
    logger.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId());
_parser.parse(source, handler);
if (handler.error != null)
    throw handler.error;
Node root = (Node)handler.root;
handler.reset();
return root;
}
        
public synchronized Node parse(String xml) throws IOException, SAXException {
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
return parse(is);
}
        
public synchronized Node parse(File file) throws IOException, SAXException {
return parse(new InputSource(file.toURI().toURL().toString()));
}
        
public synchronized Node parse(InputStream in) throws IOException, SAXException {
//_dtd=null;
Handler handler = new Handler();
XMLReader reader = _parser.getXMLReader();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
reader.setEntityResolver(handler);
_parser.parse(new InputSource(in), handler);
if (handler.error != null)
    throw handler.error;
Node root = (Node)handler.root;
handler.reset();
return root;
}
 */

public Operation parse(InputStream in)
        throws SxmpParsingException, IOException, SAXException, ParserConfigurationException {
    // create a new SAX parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    //factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    SAXParser parser = factory.newSAXParser();
    //_parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating);
    parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
    parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    parser.getXMLReader().setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);

    //_dtd=null;
    Handler handler = new Handler();
    XMLReader reader = parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);
    reader.setEntityResolver(handler);

    // try parsing (may throw an SxmpParsingException in the handler)
    try {
        parser.parse(new InputSource(in), handler);
    } catch (com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException e) {
        throw new SxmpParsingException(SxmpErrorCode.INVALID_XML, "XML encoding mismatch", null);
    }

    // check if there was an error
    if (handler.error != null) {
        throw handler.error;
    }

    // check to see if an operation was actually parsed
    if (handler.getOperation() == null) {
        throw new SxmpParsingException(SxmpErrorCode.MISSING_REQUIRED_ELEMENT,
                "The operation type [" + handler.operationType.getValue() + "] requires a request element",
                new PartialOperation(handler.operationType));
    }

    // if we got here, an operation was parsed -- now we need to validate it
    // to make sure that it has all required elements
    try {
        handler.getOperation().validate();
    } catch (SxmpErrorException e) {
        throw new SxmpParsingException(e.getErrorCode(), e.getErrorMessage(), handler.getOperation());
    }

    return handler.getOperation();
}

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

public boolean setICSasMultiStatus(String stringMultiStatus) {
    boolean Result = false;
    String ics = "";
    MultiStatus multistatus;/*from   w ww.j ava2 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:ee.ria.xroad.common.message.SaxSoapParserImpl.java

private XRoadSoapHandler handleSoap(Writer writer, InputStream inputStream) throws Exception {
    try (BufferedWriter out = new BufferedWriter(writer)) {
        XRoadSoapHandler handler = new XRoadSoapHandler(out);
        SAXParser saxParser = PARSER_FACTORY.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, handler);
        // ensure both builtin entities and character entities are reported to the parser
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true);
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true);

        saxParser.parse(inputStream, handler);
        return handler;
    } catch (SAXException ex) {
        throw new SOAPException(ex);
    }// w ww  .j a va  2s  .com
}

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.
 *///ww  w  .  jav  a 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;
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //from   w  ww.  ja va 2 s  . c  om
 * getArtistArt
 * 
 *********************************/
private String getArtistArt(String artistName) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader;
        xmlReader = saxParser.getXMLReader();
        XMLArtistInfoHandler xmlHandler = new XMLArtistInfoHandler();
        xmlReader.setContentHandler(xmlHandler);
        /*
         * Get artist art from Last.FM
         */
        String artistNameFiltered = filterString(artistName);
        URL lastFmApiRequest = new URL(
                this.LAST_FM_ARTIST_GETINFO_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
        BufferedReader in = new BufferedReader(new InputStreamReader(lastFmApiRequest.openStream()));
        xmlReader.parse(new InputSource(in));

        if (xmlHandler.xlargeAlbumArt != null) {
            return xmlHandler.xlargeAlbumArt;
        } else if (xmlHandler.largeAlbumArt != null) {
            return xmlHandler.largeAlbumArt;
        } else if (xmlHandler.mediumAlbumArt != null) {
            return xmlHandler.mediumAlbumArt;
        }

        return null;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * /*from   www. j  av  a  2 s  .  c  o  m*/
 * getAlbumArtByAlbumName
 * 
 *********************************/
private String getAlbumArtByAlbumName(String albumName, String artistName) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader;
        xmlReader = saxParser.getXMLReader();
        XMLAlbumSearchHandler xmlHandler = new XMLAlbumSearchHandler();
        xmlReader.setContentHandler(xmlHandler);
        /*
         * Get artist art from Last.FM
         */
        String artistNameFiltered = filterString(artistName);
        String albumNameFiltered = filterString(albumName);
        URL lastFmApiRequest = new URL(
                this.LAST_FM_ALBUM_SEARCH_URL + "&album=" + URLEncoder.encode(albumNameFiltered));
        BufferedReader in = new BufferedReader(new InputStreamReader(lastFmApiRequest.openStream()));
        xmlReader.parse(new InputSource(in));

        for (int i = 0; i < xmlHandler.albumSearchList.size(); i++) {
            AlbumSearch albumSearch = xmlHandler.albumSearchList.get(i);
            if (artistNameIsSimilarEnough(filterString(albumSearch.artistName), artistNameFiltered)) {
                if (albumSearch.xlargeAlbumArt != null) {
                    return albumSearch.xlargeAlbumArt;
                } else if (albumSearch.largeAlbumArt != null) {
                    return albumSearch.largeAlbumArt;
                } else if (albumSearch.mediumAlbumArt != null) {
                    return albumSearch.mediumAlbumArt;
                }
            }
        }
        return null;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        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//from  w  w  w.ja v  a2  s .c om
        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: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  .j a  v a  2 s. com*/
            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;
    }
}