Example usage for javax.xml.parsers SAXParserFactory setFeature

List of usage examples for javax.xml.parsers SAXParserFactory setFeature

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory setFeature.

Prototype

public abstract void setFeature(String name, boolean value)
        throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException;

Source Link

Document

Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader.

Usage

From source file:com.sun.faban.harness.webclient.CLIServlet.java

private void sendLogs(String[] reqC, HttpServletResponse response) throws ServletException, IOException {
    if (reqC.length < 2) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId.");
        return;/*ww  w  .  j a va 2  s.co m*/
    }
    RunId runId = new RunId(reqC[1]);
    boolean[] options = new boolean[2];
    options[TAIL] = false;
    options[FOLLOW] = false;
    for (int i = 2; i < reqC.length; i++) {
        if ("tail".equals(reqC[i])) {
            options[TAIL] = true;
        } else if ("follow".equals(reqC[i])) {
            options[FOLLOW] = true;
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid option \"" + reqC[i] + "\".");
            ;
            return;
        }
    }
    File logFile = new File(Config.OUT_DIR + runId, "log.xml");
    String status = null;
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    while (!logFile.exists()) {
        String[] pending = RunQ.listPending();
        if (pending == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found");
            return;
        }
        boolean queued = false;
        for (String run : pending) {
            if (run.equals(runId.toString())) {
                if (status == null) {
                    status = "QUEUED";
                    out.println(status);
                    response.flushBuffer();
                }
                queued = true;
                try {
                    Thread.sleep(1000); // Check back in one sec.
                } catch (InterruptedException e) {
                    //Noop, just look it up again.
                }
                break;
            }
        }
        if (!queued) { // Either never queued or deleted from queue.
            // Check for 10x, 100ms each to allow for start time.
            for (int i = 0; i < 10; i++) {
                if (logFile.exists()) {
                    status = "STARTED";
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    logger.log(Level.WARNING, "Interrupted checking existence of log file.");
                }
            }

            if (!"STARTED".equals(status)) {
                if ("QUEUED".equals(status)) { // was queued before
                    status = "DELETED";
                    out.println(status);
                    out.flush();
                    out.close();
                    return;
                } else { // Never queued or just removed.
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found");
                    return;
                }
            }
        }
    }

    LogOutputHandler handler = new LogOutputHandler(response, options);
    InputStream logInput;
    if (options[FOLLOW]) {
        // The XMLInputStream reads streaming XML and does not EOF.
        XMLInputStream input = new XMLInputStream(logFile);
        input.addEOFListener(handler);
        logInput = input;
    } else {
        logInput = new FileInputStream(logFile);
    }
    try {
        SAXParserFactory sFact = SAXParserFactory.newInstance();
        sFact.setFeature("http://xml.org/sax/features/validation", false);
        sFact.setFeature("http://apache.org/xml/features/" + "allow-java-encodings", true);
        sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-dtd-grammar", false);
        sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-external-dtd", false);
        SAXParser parser = sFact.newSAXParser();
        parser.parse(logInput, handler);
        handler.xmlComplete = true; // If we get here, the XML is good.
    } catch (ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (SAXParseException e) {
        Throwable t = e.getCause();
        // If it is caused by an IOException, we'll just throw it.
        if (t != null) {
            if (t instanceof IOException)
                throw (IOException) t;
            else if (options[FOLLOW])
                throw new ServletException(t);
        } else if (options[FOLLOW]) {
            throw new ServletException(e);
        }
    } catch (SAXException e) {
        throw new ServletException(e);
    } finally {
        if (options[TAIL] && !options[FOLLOW]) // tail not yet printed
            handler.eof();
    }
}

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;/* w w  w  .  j  a v  a 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.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.j ava2  s. c  o  m*/
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });
    if (xmlFiles != null && xmlFiles.length > 0) {
        try {
            SAXParserFactory saxfactory = SAXParserFactory.newInstance();
            saxfactory.setValidating(false);
            saxfactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            saxfactory.setFeature("http://xml.org/sax/features/validation", false);

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

From source file: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  w  ww. j av 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(Ajax.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(Ajax.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

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

    }

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

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

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

    }

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

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

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

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

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

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

        Certificate ca = options.trustedCertificate();

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

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

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

    try {

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

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

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

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

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

            });

        }

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

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

                    SAXParser parser = factory.newSAXParser();

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

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

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

            }

            //Now handle a successful request

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

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

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file/* ww  w .  j  a v  a  2 s  . c  o  m*/
 * @param digiSigStream opened stream with Signature data
 * The user must open and close it.
 * @return signed document object if successfully parsed
 */
public Signature readSignature(InputStream digiSigStream) throws DigiDocException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(digiSigStream, this);
    } catch (SAXDigiDocException ex) {
        throw ex.getDigiDocException();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_PARSE_XML);
    }
    if (m_sig == null)
        throw new DigiDocException(DigiDocException.ERR_DIGIDOC_FORMAT,
                "This document is not in signature format", null);
    return m_sig;
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file.This method reads only data in digidoc format. Not BDOC!
 * @param digiDocStream opened stream with DigiDoc data
 * The user must open and close it.// w  w  w.  j a  v a 2 s  .  c  o  m
 * @return signed document object if successfully parsed
 */
public SignedDoc readDigiDocFromStream(InputStream digiDocStream) throws DigiDocException {
    DigiDocVerifyFactory.initProvider();
    if (m_logger.isDebugEnabled())
        m_logger.debug("Start reading ddoc/bdoc");
    try {
        if (m_logger.isDebugEnabled())
            m_logger.debug("Reading ddoc");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(digiDocStream, this);
    } catch (SAXDigiDocException ex) {
        throw ex.getDigiDocException();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_PARSE_XML);
    }
    if (m_doc == null)
        throw new DigiDocException(DigiDocException.ERR_DIGIDOC_FORMAT, "This document is not in digidoc",
                null);
    return m_doc;
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in only one <Signature>// ww  w.  jav a 2s .c o m
 * @param sdoc SignedDoc to add this signature to
 * @param sigStream opened stream with Signature data
 * The user must open and close it.
 * @return signed document object if successfully parsed
 */
public Signature readSignature(SignedDoc sdoc, InputStream sigStream) throws DigiDocException {
    m_doc = sdoc;
    m_nCollectMode = 0;
    try {
        // prepare validator to receive signature from xml file as root element
        if (sdoc != null && sdoc.getFormat() != null) {
            XmlElemInfo e = null;
            // for BDOC
            if (SignedDoc.FORMAT_BDOC.equals(sdoc.getFormat())) {
                e = new XmlElemInfo("XAdESSignatures", null, null);
            } else if (SignedDoc.FORMAT_DIGIDOC_XML.equals(sdoc.getFormat())) {
                e = new XmlElemInfo("SignedDoc", null, null);
            }
            if (e != null)
                m_elemRoot = m_elemCurrent = e;
        }
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(sigStream, this);
    } catch (SAXDigiDocException ex) {
        throw ex.getDigiDocException();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_PARSE_XML);
    }
    if (m_doc.getLastSignature() == null)
        throw new DigiDocException(DigiDocException.ERR_DIGIDOC_FORMAT,
                "This document is not in Signature format", null);
    return m_doc.getLastSignature();
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file. One of fname or isSdoc must be given.
 * @param fname signed doc filename/*  ww w. ja va 2  s  .c o m*/
 * @param isSdoc opened stream with DigiDoc data
 * The user must open and close it.
 * @param errs list of errors to fill with parsing errors. If given
 * then attempt is made to continue parsing on errors and return them in this list.
 * If not given (null) then the first error found will be thrown.
 * @return signed document object if successfully parsed
 */
private SignedDoc readSignedDocOfType(String fname, InputStream isSdoc, boolean isBdoc, List errs)
        throws DigiDocException {
    // Use an instance of ourselves as the SAX event handler
    SAXDigiDocFactory handler = this;
    m_errs = errs;
    DigiDocVerifyFactory.initProvider();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    if (m_logger.isDebugEnabled())
        m_logger.debug("Start reading ddoc/bdoc " + ((fname != null) ? "from file: " + fname : "from stream")
                + " bdoc: " + isBdoc);
    if (fname == null && isSdoc == null) {
        throw new DigiDocException(DigiDocException.ERR_READ_FILE, "No input file", null);
    }
    if (fname != null) {
        File inFile = new File(fname);
        if (!inFile.canRead() || inFile.length() == 0) {
            throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Empty or unreadable input file", null);
        }
    }
    ZipFile zf = null;
    ZipArchiveInputStream zis = null;
    ZipArchiveEntry ze = null;
    InputStream isEntry = null;
    File fTmp = null;
    try {
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        if (isBdoc) { // bdoc parsing
            // must be a bdoc document ?
            m_doc = new SignedDoc();
            m_doc.setVersion(SignedDoc.BDOC_VERSION_1_0);
            m_doc.setFormat(SignedDoc.FORMAT_BDOC);
            Enumeration eFiles = null;
            if (fname != null) {
                zf = new ZipFile(fname, "UTF-8");
                eFiles = zf.getEntries();
            } else if (isSdoc != null) {
                zis = new ZipArchiveInputStream(isSdoc, "UTF-8", true, true);
            }
            ArrayList lSigFnames = new ArrayList();
            ArrayList lDataFnames = new ArrayList();
            // read all entries
            boolean bHasMimetype = false, bManifest1 = false;
            int nFil = 0;
            while ((zf != null && eFiles.hasMoreElements())
                    || (zis != null && ((ze = zis.getNextZipEntry()) != null))) {
                nFil++;

                // read entry
                if (zf != null) { // ZipFile
                    ze = (ZipArchiveEntry) eFiles.nextElement();
                    isEntry = zf.getInputStream(ze);
                } else { // ZipArchiveInputStream
                    int n = 0, nTot = 0;
                    if ((ze.getName().equals(FILE_MIMETYPE) || ze.getName().equals(FILE_MANIFEST)
                            || (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")))
                            || (nMaxBdocFilCached <= 0
                                    || (ze.getSize() < nMaxBdocFilCached && ze.getSize() >= 0))) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] data = new byte[2048];
                        while ((n = zis.read(data)) > 0) {
                            bos.write(data, 0, n);
                            nTot += n;
                        }
                        if (m_logger.isDebugEnabled())
                            m_logger.debug("Read: " + nTot + " bytes from zip");
                        data = bos.toByteArray();
                        bos = null;
                        isEntry = new ByteArrayInputStream(data);
                    } else {
                        File fCacheDir = new File(ConfigManager.instance().getStringProperty(
                                "DIGIDOC_DF_CACHE_DIR", System.getProperty("java.io.tmpdir")));
                        fTmp = File.createTempFile("bdoc-data", ".tmp", fCacheDir);
                        FileOutputStream fos = new FileOutputStream(fTmp);
                        byte[] data = new byte[2048];
                        while ((n = zis.read(data)) > 0) {
                            fos.write(data, 0, n);
                            nTot += n;
                        }
                        if (m_logger.isDebugEnabled())
                            m_logger.debug("Read: " + nTot + " bytes from zip to: " + fTmp.getAbsolutePath());
                        fos.close();
                        isEntry = new FileInputStream(fTmp);
                    }
                }
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Entry: " + ze.getName() + " nlen: " + ze.getName().length() + " size: "
                            + ze.getSize() + " dir: " + ze.isDirectory() + " comp-size: "
                            + ze.getCompressedSize());
                // mimetype file
                if (ze.getName().equals(FILE_MIMETYPE)) {
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Check mimetype!");
                    checkBdocMimetype(isEntry);
                    bHasMimetype = true;
                    m_doc.setComment(ze.getComment());
                    if (nFil != 1) {
                        m_logger.error("mimetype file is " + nFil + " file but must be first");
                        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                "mimetype file is not first zip entry", null));
                    }
                } else if (ze.getName().equals(FILE_MANIFEST)) { // manifest.xml file
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Read manifest");
                    if (!bManifest1 && isEntry != null) {
                        bManifest1 = true;
                        BdocManifestParser mfparser = new BdocManifestParser(m_doc);
                        mfparser.readManifest(isEntry);
                    } else {
                        m_logger.error("Found multiple manifest.xml files!");
                        throw new DigiDocException(DigiDocException.ERR_MULTIPLE_MANIFEST_FILES,
                                "Found multiple manifest.xml files!", null);
                    }
                } else if (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")) { // some signature
                    m_fileName = ze.getName();
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Reading bdoc siganture: " + m_fileName);
                    boolean bExists = false;
                    for (int j = 0; j < lSigFnames.size(); j++) {
                        String s1 = (String) lSigFnames.get(j);
                        if (s1.equals(m_fileName))
                            bExists = true;
                    }
                    if (bExists) {
                        m_logger.error("Duplicate signature filename: " + m_fileName);
                        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                "Duplicate signature filename: " + m_fileName, null));
                    } else
                        lSigFnames.add(m_fileName);
                    SAXParser saxParser = factory.newSAXParser();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    int n = 0;
                    byte[] data = new byte[2048];
                    while ((n = isEntry.read(data)) > 0)
                        bos.write(data, 0, n);
                    data = bos.toByteArray();
                    bos = null;
                    if (m_logger.isDebugEnabled())
                        m_logger.debug(
                                "Parsing bdoc: " + m_fileName + " size: " + ((data != null) ? data.length : 0));
                    saxParser.parse(new SignatureInputStream(new ByteArrayInputStream(data)), this);
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Parsed bdoc: " + m_fileName);
                    Signature sig1 = m_doc.getLastSignature();
                    m_sigComment = ze.getComment();
                    if (sig1 != null) {
                        sig1.setPath(m_fileName);
                        sig1.setComment(ze.getComment());
                    }
                } else { // probably a data file
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Read data file: " + ze.getName());
                    if (!ze.isDirectory()) {
                        boolean bExists = false;
                        for (int j = 0; j < lDataFnames.size(); j++) {
                            String s1 = (String) lDataFnames.get(j);
                            if (s1.equals(ze.getName()))
                                bExists = true;
                        }
                        if (bExists) {
                            m_logger.error("Duplicate datafile filename: " + ze.getName());
                            handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                    "Duplicate datafile filename: " + ze.getName(), null));
                        } else
                            lDataFnames.add(ze.getName());
                        DataFile df = m_doc.findDataFileById(ze.getName());
                        if (df != null) {
                            if (ze.getSize() > 0)
                                df.setSize(ze.getSize());
                            df.setContentType(DataFile.CONTENT_BINARY);
                            df.setFileName(ze.getName());
                        } else {
                            df = new DataFile(ze.getName(), DataFile.CONTENT_BINARY, ze.getName(),
                                    "application/binary", m_doc);
                            if (m_doc.getDataFiles() == null)
                                m_doc.setDataFiles(new ArrayList());
                            m_doc.getDataFiles().add(df);
                            //m_doc.addDataFile(df); // this does some intiailization work unnecessary here
                        }
                        // enable caching if requested
                        if (isEntry != null)
                            df.setOrCacheBodyAndCalcHashes(isEntry);
                        df.setComment(ze.getComment());
                        df.setLastModDt(new Date(ze.getTime()));
                        // fix mime type according to DataObjectFormat
                        Signature sig1 = m_doc.getLastSignature();
                        if (sig1 != null) {
                            Reference dRef = sig1.getSignedInfo().getReferenceForDataFile(df);
                            if (dRef != null) {
                                DataObjectFormat dof = sig1.getSignedInfo()
                                        .getDataObjectFormatForReference(dRef);
                                if (dof != null) {
                                    df.setMimeType(dof.getMimeType());
                                }
                            }
                        }
                    }
                }
                if (fTmp != null) {
                    fTmp.delete();
                    fTmp = null;
                }
            } // while zip entries
            if (!bHasMimetype) {
                m_logger.error("No mimetype file");
                handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                        "Not a BDOC format file! No mimetype file!", null));
            }
            // if no signatures exist then copy mime-type from manifest.xml to DataFile -s
            if (m_doc.countSignatures() == 0) {
                for (int i = 0; i < m_doc.countDataFiles(); i++) {
                    DataFile df = m_doc.getDataFile(i);
                    if (m_doc.getManifest() != null) {
                        for (int j = 0; j < m_doc.getManifest().getNumFileEntries(); j++) {
                            ManifestFileEntry mfe = m_doc.getManifest().getFileEntry(j);
                            if (mfe.getFullPath() != null && mfe.getFullPath().equals(df.getFileName())) {
                                df.setMimeType(mfe.getMediaType());
                            } // if fullpath
                        } // for
                    } // if
                } // for i
            }
        } else { // ddoc parsing
            if (m_logger.isDebugEnabled())
                m_logger.debug("Reading ddoc: " + fname + " file: " + m_fileName);
            m_fileName = fname;
            SAXParser saxParser = factory.newSAXParser();
            if (fname != null)
                saxParser.parse(new SignatureInputStream(new FileInputStream(fname)), this);
            else if (isSdoc != null)
                saxParser.parse(isSdoc, this);
        }
    } catch (org.xml.sax.SAXParseException ex) {
        m_logger.error("SAX Error: " + ex);
        handleError(ex);

    } catch (Exception ex) {
        m_logger.error("Error reading3: " + ex);
        ex.printStackTrace();
        /*if(ex instanceof DigiDocException){
           DigiDocException dex = (DigiDocException)ex;
           m_logger.error("Dex: " + ex);
           if(dex.getNestedException() != null) {
              dex.getNestedException().printStackTrace();
              m_logger.error("Trace: "); 
           }
        }*/
        handleError(ex);
    } finally { // cleanup
        try {
            if (isEntry != null) {
                isEntry.close();
                isEntry = null;
            }
            if (zis != null)
                zis.close();
            if (zf != null)
                zf.close();
            if (fTmp != null) {
                fTmp.delete();
                fTmp = null;
            }
        } catch (Exception ex) {
            m_logger.error("Error closing streams and files: " + ex);
        }
    }
    // compare Manifest and DataFiles
    boolean bErrList = (errs != null);
    if (errs == null)
        errs = new ArrayList();
    boolean bOk = DigiDocVerifyFactory.verifyManifestEntries(m_doc, errs);
    if (m_doc == null) {
        m_logger.error("Error reading4: doc == null");
        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                "This document is not in ddoc or bdoc format", null));
    }
    if (!bErrList && errs.size() > 0) { // if error list was not used then we have to throw exception. So we will throw the first one since we can only do it once
        DigiDocException ex = (DigiDocException) errs.get(0);
        throw ex;
    }
    return m_doc;
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

@Override
public XMLReader createValidatingParser(IPipeLineSession session, ValidationContext context)
        throws XmlValidatorException, PipeRunException {
    SAXParser parser;/*from w ww .jav a 2 s  . co m*/
    try {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(true);
        parserFactory.setFeature(PARSING_FEATURE_SECURE, true);
        //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_GENERAL_ENTITIES, false);
        //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_PARAMETER_ENTITIES, false);
        //parserFactory.setFeature(PARSING_FEATURE_DISALLOW_INLINE_DOCTYPE, true);

        Schema schema = getSchemaObject(context.getSchemasId(), schemasProvider.getSchemas(session));
        parserFactory.setSchema(schema);

        parser = parserFactory.newSAXParser();
        return parser.getXMLReader();
    } catch (ParserConfigurationException e) {
        throw new XmlValidatorException(logPrefix + "cannot configure parser", e);
    } catch (ConfigurationException e) {
        throw new XmlValidatorException(logPrefix + "cannot configure parser", e);
    } catch (SAXException e) {
        throw new XmlValidatorException(logPrefix + "cannot create parser", e);
    }
}