Example usage for java.net URLConnection setAllowUserInteraction

List of usage examples for java.net URLConnection setAllowUserInteraction

Introduction

In this page you can find the example usage for java.net URLConnection setAllowUserInteraction.

Prototype

public void setAllowUserInteraction(boolean allowuserinteraction) 

Source Link

Document

Set the value of the allowUserInteraction field of this URLConnection .

Usage

From source file:org.jlibrary.core.http.client.HTTPDelegate.java

/**
 * Excecutes a void request/*from   w  w  w .  j  a  v  a2 s.  c  o  m*/
 * 
 * @param methodName Name of the method to execute
 * @param params Method params
 * @param returnClass Class for the return object. If the class is InputStream this method will return 
 * the HTTP request input stream
 * @param inputStream Stream for reading contents that will be sent
 * 
 * @throws Exception If there is any problem running the request
 */
public Object doRequest(String methodName, Object[] params, Class returnClass, InputStream inputStream)
        throws Exception {

    try {
        logger.debug(servletURL.toString());
        logger.debug("opening connection");
        URLConnection conn = servletURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "text/plain");

        //write request and params:
        OutputStream stream = conn.getOutputStream();
        // write streaming header if necessary
        if (inputStream != null) {
            stream.write(ByteUtils.intToByteArray("stream-input".getBytes().length));
            stream.write("stream-input".getBytes());
            stream.flush();
        }
        if (returnClass == InputStream.class) {
            stream.write(ByteUtils.intToByteArray("stream-output".getBytes().length));
            stream.write("stream-output".getBytes());
            stream.flush();
        }

        // Write method
        stream.write(ByteUtils.intToByteArray(methodName.getBytes().length));
        stream.write(methodName.getBytes());
        //stream.flush();
        // Write parameters
        stream.write(ByteUtils.intToByteArray(params.length));
        for (int i = 0; i < params.length; i++) {
            byte[] content = SerializationUtils.serialize((Serializable) params[i]);
            stream.write(ByteUtils.intToByteArray(content.length));
            stream.write(content);
            stream.flush();
        }

        if (inputStream != null) {
            IOUtils.copy(inputStream, stream);
        }

        //stream.flush();
        //stream.close();

        //read response:
        InputStream input = conn.getInputStream();
        if (returnClass == InputStream.class) {
            // Contents will be read from outside
            return input;
        }
        ObjectInputStream objInput = new ObjectInputStream(input);
        Object o = objInput.readObject();
        if (o == null) {
            return null;
        }
        stream.close();
        if (o instanceof Exception) {
            throw (Exception) o;
        } else {
            if (returnClass == null) {
                return null;
            }
            // try to cast
            try {
                returnClass.cast(o);
            } catch (ClassCastException cce) {
                String msg = "Unexpected response from execution servlet: " + o;
                logger.error(msg);
                throw new Exception(msg);
            }
        }
        return o;
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    } catch (ClassCastException e) {
        throw new Exception(e);
    } catch (IOException e) {
        throw new Exception(e);
    }
}

From source file:org.infoglue.common.util.RemoteCacheUpdater.java

/**
 * This method post information to an URL and returns a string.It throws
 * an exception if anything goes wrong.//from   w w w . j a  va2s . co  m
 * (Works like most 'doPost' methods)
 * 
 * @param urlAddress The address of the URL you would like to post to.
 * @param inHash The parameters you would like to post to the URL.
 * @return The result of the postToUrl method as a string.
 * @exception java.lang.Exception
 */

private String postToUrl(String urlAddress, Hashtable inHash) throws Exception {
    URL url = new URL(urlAddress);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(3000);
    urlConn.setReadTimeout(3000);
    urlConn.setAllowUserInteraction(false);
    urlConn.setDoOutput(true);
    urlConn.setDoInput(true);
    urlConn.setUseCaches(false);
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true);
    String argString = "";
    if (inHash != null) {
        argString = toEncodedString(inHash);
    }
    printout.print(argString);
    printout.flush();
    printout.close();
    InputStream inStream = null;
    inStream = urlConn.getInputStream();
    InputStreamReader inStreamReader = new InputStreamReader(inStream);
    BufferedReader buffer = new BufferedReader(inStreamReader);
    StringBuffer strbuf = new StringBuffer();
    String line;
    while ((line = buffer.readLine()) != null) {
        strbuf.append(line);
    }
    String readData = strbuf.toString();
    buffer.close();
    return readData;
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

/**
 * Get the public facing hostname for this machine.  Uses AWS metadata service.
 *///from   w  w w .  jav a  2 s . c o  m
protected String getInstanceMetadata(String name, String defValue) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bout = null;
    String ret_val = null;
    InputStream is = null;

    try {
        URL url = new URL("http://169.254.169.254/latest/meta-data/" + name);

        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(5000);
        urlConn.setReadTimeout(15000);
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        is = new BufferedInputStream(urlConn.getInputStream());

        baos = new ByteArrayOutputStream();
        bout = new BufferedOutputStream(baos, 1024);

        int buffSize = 8 * 1024;
        byte data[] = new byte[buffSize];
        int count;

        while ((count = is.read(data, 0, buffSize)) >= 0) {
            baos.write(data, 0, count);
        }

        ret_val = baos.toString();
    } catch (Exception e) {
        // ignore
        //e.printStackTrace();
    } finally {
        try {
            bout.close();
            is.close();
        } catch (Exception e) {
            // ignore
        }
    }

    if (ret_val == null) {
        ret_val = defValue;
    }

    return ret_val;
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri,
        String servletPath, String proxyPath) throws ServletException, IOException {
    //System.out.println("LOAD "+uri); 
    //System.out.println("LOAD "+proxyPath);

    if ("CONNECT".equalsIgnoreCase(request.getMethod())) {
        handleConnect(request, response);

    } else {/*ww w .  j a  v  a  2 s  .c  o  m*/
        URL url = new URL(uri);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getHeader("Connection");
        if (connectionHdr != null) {
            connectionHdr = connectionHdr.toLowerCase();
            if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
                connectionHdr = null;
        }

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getHeaderNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
                continue;

            if ("content-type".equals(lhdr))
                hasContent = true;

            Enumeration vals = request.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getHeader("Cache-Control");
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IOUtils.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = 500;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code, http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.setHeader("Date", null);
        response.setHeader("Server", null);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = hdr != null ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) {
                if (hdr.equalsIgnoreCase("Location")) {
                    val = Rewriter.translateCleanUrl(val, servletPath, proxyPath);
                }
                response.addHeader(hdr, val);

            }

            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);

        }

        boolean isGzipped = connection.getContentEncoding() != null
                && connection.getContentEncoding().contains("gzip");
        response.addHeader("Via", "1.1 (jetty)");
        // boolean process = connection.getContentType() == null
        // || connection.getContentType().isEmpty()
        // || connection.getContentType().contains("html");
        boolean process = connection.getContentType() != null && connection.getContentType().contains("text");
        if (proxy_in != null) {
            if (!process) {
                IOUtils.copy(proxy_in, response.getOutputStream());
                proxy_in.close();
            } else {
                InputStream in;
                if (isGzipped && proxy_in != null && proxy_in.available() > 0) {
                    in = new GZIPInputStream(proxy_in);
                } else {
                    in = proxy_in;
                }
                ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
                IOUtils.copy(in, byteArrOS);
                in.close();
                if (in != proxy_in)
                    proxy_in.close();
                String charset = response.getCharacterEncoding();
                if (charset == null || charset.isEmpty()) {
                    charset = "ISO-8859-1";
                }
                String originalContent = new String(byteArrOS.toByteArray(), charset);
                byteArrOS.close();
                return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped);
            }
        }

    }
    return null;
}

From source file:org.apache.fop.apps.FOURIResolver.java

/**
 * Called by the processor through {@link FOUserAgent} when it encounters an
 * uri in an external-graphic element. (see also
 * {@link javax.xml.transform.URIResolver#resolve(String, String)} This
 * resolver will allow URLs without a scheme, i.e. it assumes 'file:' as the
 * default scheme. It also allows relative URLs with scheme, e.g.
 * file:../../abc.jpg which is not strictly RFC compliant as long as the
 * scheme is the same as the scheme of the base URL. If the base URL is null
 * a 'file:' URL referencing the current directory is used as the base URL.
 * If the method is successful it will return a Source of type
 * {@link javax.xml.transform.stream.StreamSource} with its SystemID set to
 * the resolved URL used to open the underlying InputStream.
 *
 * @param href//ww  w  .  j  a v a  2  s  .co m
 *            An href attribute, which may be relative or absolute.
 * @param base
 *            The base URI against which the first argument will be made
 *            absolute if the absolute URI is required.
 * @return A {@link javax.xml.transform.Source} object, or null if the href
 *         cannot be resolved.
 * @throws javax.xml.transform.TransformerException
 *             Never thrown by this implementation.
 * @see javax.xml.transform.URIResolver#resolve(String, String)
 */
public Source resolve(String href, String base) throws TransformerException {
    Source source = null;

    // data URLs can be quite long so evaluate early and don't try to build a File
    // (can lead to problems)
    source = commonURIResolver.resolve(href, base);

    // Custom uri resolution
    if (source == null && uriResolver != null) {
        source = uriResolver.resolve(href, base);
    }

    // Fallback to default resolution mechanism
    if (source == null) {
        URL absoluteURL = null;
        int hashPos = href.indexOf('#');
        String fileURL;
        String fragment;
        if (hashPos >= 0) {
            fileURL = href.substring(0, hashPos);
            fragment = href.substring(hashPos);
        } else {
            fileURL = href;
            fragment = null;
        }
        File file = new File(fileURL);
        if (file.canRead() && file.isFile()) {
            try {
                if (fragment != null) {
                    absoluteURL = new URL(file.toURI().toURL().toExternalForm() + fragment);
                } else {
                    absoluteURL = file.toURI().toURL();
                }
            } catch (MalformedURLException mfue) {
                handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions);
            }
        } else {
            // no base provided
            if (base == null) {
                // We don't have a valid file protocol based URL
                try {
                    absoluteURL = new URL(href);
                } catch (MalformedURLException mue) {
                    try {
                        // the above failed, we give it another go in case
                        // the href contains only a path then file: is
                        // assumed
                        absoluteURL = new URL("file:" + href);
                    } catch (MalformedURLException mfue) {
                        handleException(mfue, "Error with URL '" + href + "'", throwExceptions);
                    }
                }

                // try and resolve from context of base
            } else {
                URL baseURL = null;
                try {
                    baseURL = new URL(base);
                } catch (MalformedURLException mfue) {
                    handleException(mfue, "Error with base URL '" + base + "'", throwExceptions);
                }

                /*
                 * This piece of code is based on the following statement in
                 * RFC2396 section 5.2:
                 *
                 * 3) If the scheme component is defined, indicating that
                 * the reference starts with a scheme name, then the
                 * reference is interpreted as an absolute URI and we are
                 * done. Otherwise, the reference URI's scheme is inherited
                 * from the base URI's scheme component.
                 *
                 * Due to a loophole in prior specifications [RFC1630], some
                 * parsers allow the scheme name to be present in a relative
                 * URI if it is the same as the base URI scheme.
                 * Unfortunately, this can conflict with the correct parsing
                 * of non-hierarchical URI. For backwards compatibility, an
                 * implementation may work around such references by
                 * removing the scheme if it matches that of the base URI
                 * and the scheme is known to always use the <hier_part>
                 * syntax.
                 *
                 * The URL class does not implement this work around, so we
                 * do.
                 */
                assert (baseURL != null);
                String scheme = baseURL.getProtocol() + ":";
                if (href.startsWith(scheme) && "file:".equals(scheme)) {
                    href = href.substring(scheme.length());
                    int colonPos = href.indexOf(':');
                    int slashPos = href.indexOf('/');
                    if (slashPos >= 0 && colonPos >= 0 && colonPos < slashPos) {
                        href = "/" + href; // Absolute file URL doesn't
                        // have a leading slash
                    }
                }
                try {
                    absoluteURL = new URL(baseURL, href);
                } catch (MalformedURLException mfue) {
                    handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'",
                            throwExceptions);
                }
            }
        }

        if (absoluteURL != null) {
            String effURL = absoluteURL.toExternalForm();
            try {
                URLConnection connection = absoluteURL.openConnection();
                connection.setAllowUserInteraction(false);
                connection.setDoInput(true);
                updateURLConnection(connection, href);
                connection.connect();
                return new StreamSource(connection.getInputStream(), effURL);
            } catch (FileNotFoundException fnfe) {
                // Note: This is on "debug" level since the caller is
                // supposed to handle this
                log.debug("File not found: " + effURL);
            } catch (java.io.IOException ioe) {
                log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage());
            }
        }
    }
    return source;
}

From source file:WebCrawler.java

public void run() {
    String strURL = textURL.getText();
    String strTargetType = choiceType.getSelectedItem();
    int numberSearched = 0;
    int numberFound = 0;

    if (strURL.length() == 0) {
        setStatus("ERROR: must enter a starting URL");
        return;//from  w  ww  .  j  av a 2  s. c  o  m
    }

    // initialize search data structures
    vectorToSearch.removeAllElements();
    vectorSearched.removeAllElements();
    vectorMatches.removeAllElements();
    listMatches.removeAll();

    vectorToSearch.addElement(strURL);

    while ((vectorToSearch.size() > 0) && (Thread.currentThread() == searchThread)) {
        // get the first element from the to be searched list
        strURL = (String) vectorToSearch.elementAt(0);

        setStatus("searching " + strURL);

        URL url;
        try {
            url = new URL(strURL);
        } catch (MalformedURLException e) {
            setStatus("ERROR: invalid URL " + strURL);
            break;
        }

        // mark the URL as searched (we want this one way or the other)
        vectorToSearch.removeElementAt(0);
        vectorSearched.addElement(strURL);

        // can only search http: protocol URLs
        if (url.getProtocol().compareTo("http") != 0)
            break;

        // test to make sure it is before searching
        if (!robotSafe(url))
            break;

        try {
            // try opening the URL
            URLConnection urlConnection = url.openConnection();

            urlConnection.setAllowUserInteraction(false);

            InputStream urlStream = url.openStream();
            String type = urlConnection.guessContentTypeFromStream(urlStream);
            if (type == null)
                break;
            if (type.compareTo("text/html") != 0)
                break;

            // search the input stream for links
            // first, read in the entire URL
            byte b[] = new byte[1000];
            int numRead = urlStream.read(b);
            String content = new String(b, 0, numRead);
            while (numRead != -1) {
                if (Thread.currentThread() != searchThread)
                    break;
                numRead = urlStream.read(b);
                if (numRead != -1) {
                    String newContent = new String(b, 0, numRead);
                    content += newContent;
                }
            }
            urlStream.close();

            if (Thread.currentThread() != searchThread)
                break;

            String lowerCaseContent = content.toLowerCase();

            int index = 0;
            while ((index = lowerCaseContent.indexOf("<a", index)) != -1) {
                if ((index = lowerCaseContent.indexOf("href", index)) == -1)
                    break;
                if ((index = lowerCaseContent.indexOf("=", index)) == -1)
                    break;

                if (Thread.currentThread() != searchThread)
                    break;

                index++;
                String remaining = content.substring(index);

                StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\">#");
                String strLink = st.nextToken();

                URL urlLink;
                try {
                    urlLink = new URL(url, strLink);
                    strLink = urlLink.toString();
                } catch (MalformedURLException e) {
                    setStatus("ERROR: bad URL " + strLink);
                    continue;
                }

                // only look at http links
                if (urlLink.getProtocol().compareTo("http") != 0)
                    break;

                if (Thread.currentThread() != searchThread)
                    break;

                try {
                    // try opening the URL
                    URLConnection urlLinkConnection = urlLink.openConnection();
                    urlLinkConnection.setAllowUserInteraction(false);
                    InputStream linkStream = urlLink.openStream();
                    String strType = urlLinkConnection.guessContentTypeFromStream(linkStream);
                    linkStream.close();

                    // if another page, add to the end of search list
                    if (strType == null)
                        break;
                    if (strType.compareTo("text/html") == 0) {
                        // check to see if this URL has already been 
                        // searched or is going to be searched
                        if ((!vectorSearched.contains(strLink)) && (!vectorToSearch.contains(strLink))) {

                            // test to make sure it is robot-safe!
                            if (robotSafe(urlLink))
                                vectorToSearch.addElement(strLink);
                        }
                    }

                    // if the proper type, add it to the results list
                    // unless we have already seen it
                    if (strType.compareTo(strTargetType) == 0) {
                        if (vectorMatches.contains(strLink) == false) {
                            listMatches.add(strLink);
                            vectorMatches.addElement(strLink);
                            numberFound++;
                            if (numberFound >= SEARCH_LIMIT)
                                break;
                        }
                    }
                } catch (IOException e) {
                    setStatus("ERROR: couldn't open URL " + strLink);
                    continue;
                }
            }
        } catch (IOException e) {
            setStatus("ERROR: couldn't open URL " + strURL);
            break;
        }

        numberSearched++;
        if (numberSearched >= SEARCH_LIMIT)
            break;
    }

    if (numberSearched >= SEARCH_LIMIT || numberFound >= SEARCH_LIMIT)
        setStatus("reached search limit of " + SEARCH_LIMIT);
    else
        setStatus("done");
    searchThread = null;
    // searchThread.stop();
}

From source file:com.liferay.ide.server.remote.RemoteLogStream.java

protected static InputStream openInputStream(IServerManagerConnection remote, URL url) throws IOException {
    String username = remote.getUsername();
    String password = remote.getPassword();

    String authString = username + ":" + password; //$NON-NLS-1$
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    final IProxyService proxyService = LiferayCore.getProxyService();
    URLConnection conn = null;

    try {//from  ww w. j  a v a  2s .com
        URI uri = new URI("HTTP://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        IProxyData[] proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("http.proxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("http.proxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }

        uri = new URI("SOCKS://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("socksProxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("socksProxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }
    } catch (URISyntaxException e) {
        LiferayServerCore.logError("Could not read proxy data", e); //$NON-NLS-1$
    }

    conn = url.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$ //$NON-NLS-2$
    Authenticator.setDefault(null);
    conn.setAllowUserInteraction(false);

    return conn.getInputStream();
}

From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java

private void listen() {
    String errorMessage;/*from  w  w w.j  a  v  a2s.  c  o  m*/
    boolean error;
    errorMessage = "";
    error = false;
    try {
        Logger.logConsole("Starting listen thread");
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setReadTimeout(0);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(false);
        if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) {
            Logger.logConsole("User has no access to the CMS - closing connection");
            throw new AccessControlException("User has no access to the CMS - closing connection");
        }
        String boundary = urlConn.getHeaderField("boundary");
        DataInputStream input = new DataInputStream(urlConn.getInputStream());
        StringBuffer buf = new StringBuffer();
        if (listener != null)
            listener.onConnection(url);
        String str = null;
        while ((str = input.readLine()) != null) {
            if (str.indexOf("XMLNotificationWriter.ping") == -1) {
                if (str.equals(boundary)) {
                    String message = buf.toString();

                    // By checking there is more in the String than the XML declaration we assume the message is valid
                    if (message != null
                            && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) {
                        if (listener != null)
                            listener.recieveDocument(buf.toString());
                        else
                            Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString())
                                    .append("\r\n").toString());
                    }
                    buf = new StringBuffer();
                } else {
                    buf.append(str);
                }
            }
        }
        input.close();
    } catch (MalformedURLException me) {
        error = true;
        errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString();
        if (listener != null)
            listener.onException(me);
        else
            System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (IOException ioe) {
        error = true;
        errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state.";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString());
        if (listener != null)
            listener.onException(ioe);
        else
            Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: "))
                    .append(url.toExternalForm()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (AccessControlException ace) {
        error = true;
        errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString());
        if (listener != null)
            listener.onException(ace);
        else
            Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Exception exception) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Throwable e) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e2) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    URI uri = request.getURI();// w  w w  . j a va 2s. c  om

    // Is this a CONNECT request?
    if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) {
        response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
        handleConnect(pathInContext, pathParams, request, response);
        return;
    }

    try {
        // Do we proxy this?
        URL url = isProxied(uri);
        if (url == null) {
            if (isForbidden(uri))
                sendForbid(request, response, uri);
            return;
        }

        if (log.isDebugEnabled())
            log.debug("PROXY URL=" + url);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getField(HttpFields.__Connection);
        if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive)
                || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
            connectionHdr = null;

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getFieldNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();

            if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                continue;

            if (HttpFields.__ContentType.equals(hdr))
                hasContent = true;

            Enumeration vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        if (!_anonymous)
            connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getField(HttpFields.__CacheControl);
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection
        customizeConnection(pathInContext, pathParams, request, connection);

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IO.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = HttpResponse.__500_Internal_Server_Error;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code);
            response.setReason(http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.removeField(HttpFields.__Date);
        response.removeField(HttpFields.__Server);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)
                    && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                response.addField(hdr, val);
            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);
        }
        if (!_anonymous)
            response.setField("Via", "1.1 (jetty)");

        // Handled
        request.setHandled(true);
        if (proxy_in != null)
            IO.copy(proxy_in, response.getOutputStream());

    } catch (Exception e) {
        log.warn(e.toString());
        LogSupport.ignore(log, e);
        if (!response.isCommitted())
            response.sendError(HttpResponse.__400_Bad_Request);
    }
}

From source file:org.apache.xmlrpc.applet.SimpleXmlRpcClient.java

/**
 * Generate an XML-RPC request and send it to the server. Parse the result
 * and return the corresponding Java object.
 *
 * @exception XmlRpcException If the remote host returned a fault message.
 * @exception IOException If the call could not be made for lower level
 *          problems.// w w w. j  a  v a 2 s.c  om
 */
public Object execute(String method, Vector arguments) throws XmlRpcException, IOException {
    fault = false;
    long now = System.currentTimeMillis();
    try {
        StringBuffer strbuf = new StringBuffer();
        XmlWriter writer = new XmlWriter(strbuf);
        writeRequest(writer, method, arguments);
        byte[] request = strbuf.toString().getBytes();
        URLConnection con = url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setAllowUserInteraction(false);
        con.setRequestProperty("Content-Length", Integer.toString(request.length));
        con.setRequestProperty("Content-Type", "text/xml");
        // con.connect ();
        OutputStream out = con.getOutputStream();
        out.write(request);
        out.flush();
        InputStream in = con.getInputStream();
        parse(in);
        System.out.println("result = " + result);
    } catch (Exception x) {
        x.printStackTrace();
        throw new IOException(x.getMessage());
    }
    if (fault) {
        // generate an XmlRpcException
        XmlRpcException exception = null;
        try {
            Hashtable f = (Hashtable) result;
            String faultString = (String) f.get("faultString");
            int faultCode = Integer.parseInt(f.get("faultCode").toString());
            exception = new XmlRpcException(faultCode, faultString.trim());
        } catch (Exception x) {
            throw new XmlRpcException(0, "Invalid fault response");
        }
        throw exception;
    }
    System.out.println("Spent " + (System.currentTimeMillis() - now) + " in request");
    return result;
}