Example usage for org.xml.sax.helpers DefaultHandler DefaultHandler

List of usage examples for org.xml.sax.helpers DefaultHandler DefaultHandler

Introduction

In this page you can find the example usage for org.xml.sax.helpers DefaultHandler DefaultHandler.

Prototype

DefaultHandler

Source Link

Usage

From source file:org.sakaiproject.calendar.impl.RecurrenceRuleBase.java

public ContentHandler getContentHandler(final Map<String, Object> services) {
    return new DefaultHandler() {
        /*//  w w w .jav  a  2  s  . c  o  m
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            // read the interval
            try {
                setInterval(Integer.parseInt(attributes.getValue("interval")));
            } catch (Exception any) {
            }

            // read the count
            try {
                setCount(Integer.parseInt(attributes.getValue("count")));
                //               M_log.debug("Set count to "+attributes.getValue("count"));
            } catch (Exception any) {
            }

            // read the until
            try {
                setUntil(((org.sakaiproject.time.api.TimeService) services.get("timeservice"))
                        .newTimeGmt(attributes.getValue("until")));
                //               M_log.debug("Set until to "+attributes.getValue("until"));
            } catch (Exception any) {
            }

        }
    };
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.SAXSerializableCollectionAccess.java

/**
 * @param xml//from w w w. j  a v  a  2s  .  co  m
 */
public void parse(String xml) throws Exception {
    Reader r = new StringReader(xml);
    InputSource ss = new InputSource(r);

    SAXParser p = null;
    if (parserFactory == null) {
        parserFactory = SAXParserFactory.newInstance();
        parserFactory.setNamespaceAware(false);
        parserFactory.setValidating(false);
    }
    try {
        p = parserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new SAXException("Failed to get a parser ", e);
    }
    final Map<String, Object> props = new HashMap<String, Object>();
    saxSerializableProperties.setSerializableProperties(props);
    p.parse(ss, new DefaultHandler() {

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {

            if ("property".equals(qName)) {

                String name = attributes.getValue("name");
                String enc = StringUtils.trimToNull(attributes.getValue("enc"));
                String value = null;
                if ("BASE64".equalsIgnoreCase(enc)) {
                    String charset = StringUtils.trimToNull(attributes.getValue("charset"));
                    if (charset == null)
                        charset = "UTF-8";

                    value = Xml.decode(charset, attributes.getValue("value"));
                } else {
                    value = attributes.getValue("value");
                }

                // deal with multiple valued lists
                if ("list".equals(attributes.getValue("list"))) {
                    // accumulate multiple values in a list
                    Object current = props.get(name);

                    // if we don't have a value yet, make a list to
                    // hold
                    // this one
                    if (current == null) {
                        List values = new Vector();
                        props.put(name, values);
                        values.add(value);
                    }

                    // if we do and it's a list, add this one
                    else if (current instanceof List) {
                        ((List) current).add(value);
                    }

                    // if it's not a list, it's wrong!
                    else {
                        log.warn("construct(el): value set not a list: " + name);
                    }
                } else {
                    props.put(name, value);
                }
            } else if ("collection".equals(qName)) {
                id = attributes.getValue("id");
                resourceType = ResourceType.TYPE_FOLDER;

                // extract access
                accessMode = AccessMode.INHERITED;
                String access_mode = attributes.getValue("sakai:access_mode");
                if (access_mode != null && !access_mode.trim().equals("")) {
                    accessMode = AccessMode.fromString(access_mode);
                }

                if (accessMode == null || AccessMode.SITE == accessMode) {
                    accessMode = AccessMode.INHERITED;
                }

                // extract release date
                // m_releaseDate = TimeService.newTime(0);
                String date0 = attributes.getValue("sakai:release_date");
                if (date0 != null && !date0.trim().equals("")) {
                    releaseDate = conversionTimeService.newTimeGmt(date0);
                    if (releaseDate.getTime() <= START_OF_TIME) {
                        releaseDate = null;
                    }
                }

                // extract retract date
                // m_retractDate = TimeService.newTimeGmt(9999,12,
                // 31, 23, 59, 59, 999);
                String date1 = attributes.getValue("sakai:retract_date");
                if (date1 != null && !date1.trim().equals("")) {
                    retractDate = conversionTimeService.newTimeGmt(date1);
                    if (retractDate.getTime() >= END_OF_TIME) {
                        retractDate = null;
                    }
                }

                String shidden = attributes.getValue("sakai:hidden");
                hidden = shidden != null && !shidden.trim().equals("")
                        && !Boolean.FALSE.toString().equalsIgnoreCase(shidden);
            } else if ("sakai:authzGroup".equals(qName)) {
                String groupRef = attributes.getValue("sakai:group_name");
                if (groupRef != null) {
                    group.add(groupRef);
                }
            } else if ("rightsAssignment".equals(qName)) {

            } else if ("properties".equals(qName)) {

            }

            else {
                log.warn("Unexpected Element " + qName);
            }

        }
    });
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.SAXSerializableResourceAccess.java

/**
 * @param xml//  w  ww.  j  av a2  s .  c o m
 * @throws EntityParseException
 */
public void parse(String xml) throws Exception {
    Reader r = new StringReader(xml);
    InputSource ss = new InputSource(r);

    SAXParser p = null;
    if (parserFactory == null) {
        parserFactory = SAXParserFactory.newInstance();
        parserFactory.setNamespaceAware(false);
        parserFactory.setValidating(false);
    }
    try {
        p = parserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new SAXException("Failed to get a parser ", e);
    }
    final Map<String, Object> props = new HashMap<String, Object>();
    saxSerializableProperties.setSerializableProperties(props);
    p.parse(ss, new DefaultHandler() {

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (qName == null) {
                // will be ignored
            } else {
                qName = qName.trim();
            }
            if ("property".equalsIgnoreCase(qName)) {

                String name = attributes.getValue("name");
                String enc = StringUtils.trimToNull(attributes.getValue("enc"));
                String value = null;
                if ("BASE64".equalsIgnoreCase(enc)) {
                    String charset = StringUtils.trimToNull(attributes.getValue("charset"));
                    if (charset == null)
                        charset = "UTF-8";

                    value = Xml.decode(charset, attributes.getValue("value"));
                } else {
                    value = attributes.getValue("value");
                }

                // deal with multiple valued lists
                if ("list".equals(attributes.getValue("list"))) {
                    // accumulate multiple values in a list
                    Object current = props.get(name);

                    // if we don't have a value yet, make a list to
                    // hold
                    // this one
                    if (current == null) {
                        List values = new Vector();
                        props.put(name, values);
                        values.add(value);
                    }

                    // if we do and it's a list, add this one
                    else if (current instanceof List) {
                        ((List) current).add(value);
                    }

                    // if it's not a list, it's wrong!
                    else {
                        log.warn("construct(el): value set not a list: " + name);
                    }
                } else {
                    props.put(name, value);
                }
            } else if ("resource".equalsIgnoreCase(qName)) {
                id = attributes.getValue("id");
                contentType = StringUtils.trimToNull(attributes.getValue("content-type"));
                contentLength = 0;
                try {
                    contentLength = Integer.parseInt(attributes.getValue("content-length"));
                } catch (Exception ignore) {
                }
                resourceType = StringUtils.trimToNull(attributes.getValue("resource-type"));

                if (resourceType == null) {
                    resourceType = ResourceType.TYPE_UPLOAD;
                }

                String enc = StringUtils.trimToNull(attributes.getValue("body"));
                if (enc != null) {
                    byte[] decoded = null;
                    try {
                        decoded = Base64.decodeBase64(enc.getBytes("UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        log.error(e);
                    }
                    body = new byte[(int) contentLength];
                    System.arraycopy(decoded, 0, body, 0, (int) contentLength);
                }

                filePath = StringUtils.trimToNull(attributes.getValue("filePath"));
                accessMode = AccessMode.INHERITED;
                String access_mode = attributes.getValue("sakai:access_mode");
                if (access_mode != null && !access_mode.trim().equals("")) {
                    accessMode = AccessMode.fromString(access_mode);
                }
                if (accessMode == null || AccessMode.SITE == accessMode) {
                    accessMode = AccessMode.INHERITED;
                }

                String shidden = attributes.getValue("sakai:hidden");
                hidden = shidden != null && !shidden.trim().equals("")
                        && !Boolean.FALSE.toString().equalsIgnoreCase(shidden);

                if (hidden) {
                    releaseDate = null;
                    retractDate = null;
                } else {
                    // extract release date
                    String date0 = attributes.getValue("sakai:release_date");
                    if (date0 != null && !date0.trim().equals("")) {
                        releaseDate = conversionTimeService.newTimeGmt(date0);
                        if (releaseDate.getTime() <= START_OF_TIME) {
                            releaseDate = null;
                        }
                    }

                    // extract retract date
                    String date1 = attributes.getValue("sakai:retract_date");
                    if (date1 != null && !date1.trim().equals("")) {
                        retractDate = conversionTimeService.newTimeGmt(date1);
                        if (retractDate.getTime() >= END_OF_TIME) {
                            retractDate = null;
                        }
                    }
                }
            } else if ("sakai:authzGroup".equalsIgnoreCase(qName)) {
                if (group == null) {
                    group = new ArrayList<String>();
                }
                group.add(attributes.getValue("sakai:group_name"));
            } else if ("properties".equalsIgnoreCase(qName)) {

            } else if ("members".equalsIgnoreCase(qName)) {
                // ignore
            } else if ("member".equalsIgnoreCase(qName)) {
                // ignore
            } else {
                log.warn("Unexpected Element \"" + qName + "\"");
            }

        }
    });
}

From source file:org.sakaiproject.util.BaseResourceProperties.java

public ContentHandler getContentHander() {
    return new DefaultHandler() {

        /*// w  w  w. j  a v  a2 s  .  co m
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {

            if ("property".equals(qName)) {

                String name = attributes.getValue("name");
                String enc = StringUtils.trimToNull(attributes.getValue("enc"));
                String value = null;
                if ("BASE64".equalsIgnoreCase(enc)) {
                    String charset = StringUtils.trimToNull(attributes.getValue("charset"));
                    if (charset == null)
                        charset = "UTF-8";

                    value = Xml.decode(charset, attributes.getValue("value"));
                } else {
                    value = attributes.getValue("value");
                }

                // deal with multiple valued lists
                if ("list".equals(attributes.getValue("list"))) {
                    // accumulate multiple values in a list
                    Object current = m_props.get(name);

                    // if we don't have a value yet, make a list to hold
                    // this one
                    if (current == null) {
                        List values = new Vector();
                        m_props.put(name, values);
                        values.add(value);
                    }

                    // if we do and it's a list, add this one
                    else if (current instanceof List) {
                        ((List) current).add(value);
                    }

                    // if it's not a list, it's wrong!
                    else {
                        M_log.warn("construct(el): value set not a list: " + name);
                    }
                } else {
                    m_props.put(name, value);
                }
            }
        }

    };
}

From source file:org.shaman.rpg.editor.objects.ui.properties.XMLPropertyFilterSupport.java

private boolean isFileValid(URL file, final XMLPropertyFilter filter) throws IOException {
    try (InputStream in = file.openStream()) {
        final boolean[] result = new boolean[1];
        result[0] = false;//from   w w w  . j a v a2 s  .  c o m
        try {
            parser.parse(in, new DefaultHandler() {

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes)
                        throws SAXException {
                    if (!filter.rootElement().isEmpty() && !filter.rootElement().equals(qName)) {
                        throw new SAXException();
                    }
                    String xmlns = attributes.getValue("xmlns");
                    if (!filter.namespace().isEmpty() && !filter.namespace().equals(xmlns)) {
                        throw new SAXException(); //break out
                    }
                    result[0] = true; //is true
                    throw new SAXException();
                }

            });
        } catch (SAXException ex) {
            //do nothing
        }
        return result[0];
    }
}

From source file:org.wso2.carbon.registry.indexing.indexer.XMLIndexer.java

public IndexDocument getIndexedDocument(File2Index fileData) throws SolrException, RegistryException {
    // we register both the content as it is and only text content
    String xmlAsStr = RegistryUtils.decodeBytes(fileData.data);

    final StringBuffer contentOnly = new StringBuffer();
    ByteArrayInputStream inData = new ByteArrayInputStream(fileData.data);

    // this will handle text content
    DefaultHandler handler = new DefaultHandler() {
        public void characters(char ch[], int start, int length) throws SAXException {
            contentOnly.append(new String(ch, start, length)).append(" ");
        }/*from  www .j  av  a2 s  .  c o  m*/
    };
    //         SAXParserFactory factory = SAXParserFactory.newInstance();
    //         SAXParser saxParser = factory.newSAXParser();
    //         saxParser.parse(inData, handler);

    IndexDocument indexDocument = new IndexDocument(fileData.path, xmlAsStr, contentOnly.toString());
    Map<String, List<String>> attributes = new HashMap<String, List<String>>();
    if (fileData.mediaType != null) {
        attributes.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList(fileData.mediaType));
    }
    if (fileData.lcState != null) {
        attributes.put(IndexingConstants.FIELD_LC_STATE, Arrays.asList(fileData.lcState));
    }
    if (fileData.lcName != null) {
        attributes.put(IndexingConstants.FIELD_LC_NAME, Arrays.asList(fileData.lcName));
    }
    indexDocument.setFields(attributes);
    return indexDocument;

}

From source file:org.wso2.carbon.transport.http.netty.internal.NettyTransportActivator.java

/**
 * Parse the  netty-transports.xml config file & create the Netty transport instances
 * @return Netty transport instances// www .ja v a 2  s . co  m
 */
private Set<NettyListener> createNettyServices() {
    final Set<NettyListener> listeners = new HashSet<>();
    DefaultHandler handler = new DefaultHandler() {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            if (qName.equals("listener")) {
                String id = attributes.getValue("id");
                String host = attributes.getValue("host");
                String port = attributes.getValue("port");
                String bossThreadPoolSize = attributes.getValue("bossThreadPoolSize");
                String workerThreadPoolSize = attributes.getValue("workerThreadPoolSize");
                String execHandlerThreadPoolSize = attributes.getValue("execHandlerThreadPoolSize");

                String scheme = attributes.getValue("scheme");
                String keystoreFile = attributes.getValue("keystoreFile");
                String keystorePass = attributes.getValue("keystorePass");
                String certPass = attributes.getValue("certPass");
                String trustStoreFile = attributes.getValue("trustStoreFile");
                String trustStorePass = attributes.getValue("trustStorePass");

                NettyListener.Config nettyConfig = new NettyListener.Config(id);
                if (host != null) {
                    nettyConfig.setHost(host);
                }
                if (port != null) {
                    nettyConfig.setPort(Integer.parseInt(port));
                }
                if (bossThreadPoolSize != null) {
                    nettyConfig.setBossThreads(Integer.parseInt(bossThreadPoolSize));
                }
                if (workerThreadPoolSize != null) {
                    nettyConfig.setWorkerThreads(Integer.parseInt(workerThreadPoolSize));
                }
                if (execHandlerThreadPoolSize != null) {
                    nettyConfig.setExecThreads(Integer.parseInt(execHandlerThreadPoolSize));
                }

                if (scheme != null && scheme.equalsIgnoreCase("https")) {
                    if (certPass == null) {
                        certPass = keystorePass;
                    }
                    if (keystoreFile == null || keystorePass == null) {
                        throw new IllegalArgumentException(
                                "keyStoreFile or keyStorePass not defined for HTTPS scheme");
                    }
                    File keyStore = new File(keystoreFile);
                    if (!keyStore.exists()) {
                        throw new IllegalArgumentException("KeyStore File " + keystoreFile + " not found");
                    }
                    SSLConfig sslConfig = new SSLConfig(keyStore, keystorePass).setCertPass(certPass);
                    if (trustStoreFile != null) {
                        File trustStore = new File(trustStoreFile);
                        if (!trustStore.exists()) {
                            throw new IllegalArgumentException(
                                    "trustStore File " + trustStoreFile + " not found");
                        }
                        if (trustStorePass == null) {
                            throw new IllegalArgumentException(
                                    "trustStorePass is not defined for HTTPS scheme");
                        }
                        sslConfig.setTrustStore(trustStore).setTrustStorePass(trustStorePass);
                    }
                    nettyConfig.enableSsl(sslConfig);
                }
                listeners.add(new NettyListener(nettyConfig));
            }
        }
    };

    String nettyTransportsXML = "repository" + File.separator + "conf" + File.separator + "transports"
            + File.separator + "netty-transports.xml";
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(nettyTransportsXML, handler);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("Cannot parse " + nettyTransportsXML, e);
    }
    return listeners;
}

From source file:org.zaproxy.zap.utils.ZapXmlConfiguration.java

@Override
protected DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = XmlUtils.newXxeDisabledDocumentBuilderFactory();

    // Same behaviour as base method:
    if (isValidating()) {
        factory.setValidating(true);/*from   www. ja v  a  2s  .  c  om*/
        if (isSchemaValidation()) {
            factory.setNamespaceAware(true);
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
        }
    }

    DocumentBuilder result = factory.newDocumentBuilder();
    result.setEntityResolver(getEntityResolver());

    if (isValidating()) {
        result.setErrorHandler(new DefaultHandler() {

            @Override
            public void error(SAXParseException ex) throws SAXException {
                throw ex;
            }
        });
    }
    return result;
}

From source file:pt.iflow.api.licensing.FileBasedLicenseService.java

private void parseXMLSnapshot(byte[] xml) throws SAXException, IOException, ParserConfigurationException {
    DefaultHandler handler = new DefaultHandler() {
        LicenseEntry currOrg;//from  w  w w  .  j a v a  2s. com

        public void startDocument() throws SAXException {
            licenseEntries.clear();
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if ("org".equals(qName)) {
                currOrg = new LicenseEntry();
                currOrg.available = Long.parseLong(attributes.getValue("available"));
                currOrg.consumed = Long.parseLong(attributes.getValue("consumed"));
                licenseEntries.put(attributes.getValue("id"), currOrg);
            } else if ("flow".equals(qName)) {
                currOrg.flowBased.put(new Integer(attributes.getValue("id")),
                        new Long(attributes.getValue("consumed")));
            }
        }

    };

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    SAXParser parser = factory.newSAXParser();
    parser.parse(new ByteArrayInputStream(xml), handler);

}

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

@Override
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 {// ww  w  .j  a v  a 2 s. c om
            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(AjaxTask.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(AjaxTask.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.headers = null;
        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("droidQuery.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());
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (options.trustAllSSLCertificates()) {
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier(hostnameVerifier);
        schemeRegistry.register(new Scheme("https", socketFactory, 443));
        Log.w("Ajax", "Warning: All SSL Certificates have been trusted!");
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry);
    HttpClient client = new DefaultHttpClient(mgr, 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($.with(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        final StatusLine statusLine = response.getStatusLine();

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

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

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                parsedResponse = parseText(response);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing 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")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(response);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(response);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                parsedResponse = parseImage(response);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(response);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            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;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            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;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        }

        if (statusLine.getStatusCode() >= 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 = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.headers = response.getAllHeaders();
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //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", Locale.US);
                    Date lastModified = format.parse(h.getValue());
                    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.request = request;
                            error.options = options;
                            e.status = statusLine.getStatusCode();
                            e.reason = statusLine.getReasonPhrase();
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.headers = response.getAllHeaders();
                            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 = 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(null);
            AjaxError error = new AjaxError();
            error.request = request;
            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 (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}