Example usage for java.net HttpURLConnection setAllowUserInteraction

List of usage examples for java.net HttpURLConnection setAllowUserInteraction

Introduction

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

Prototype

public void setAllowUserInteraction(boolean allowuserinteraction) 

Source Link

Document

Set the value of the allowUserInteraction field of this URLConnection .

Usage

From source file:com.docdoku.client.actions.MainController.java

private void performHeadHTTPMethod(String pURL) throws MalformedURLException, IOException {
    MainModel model = MainModel.getInstance();
    URL url = new URL(pURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(false);/* w w w.  j  a v a  2s .  c  om*/
    conn.setAllowUserInteraction(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    byte[] encoded = org.apache.commons.codec.binary.Base64
            .encodeBase64((model.getLogin() + ":" + model.getPassword()).getBytes("ISO-8859-1"));
    conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
    conn.setRequestMethod("HEAD");
    conn.connect();
    int code = conn.getResponseCode();
    System.out.println("Head HTTP response code: " + code);
}

From source file:org.jboss.tools.ws.ui.utils.JAXRSTester.java

/**
 * Call a JAX-RS service//from  w w w.java 2s .c  om
 * @param address
 * @param parameters
 * @param headers
 * @param methodType
 * @param requestBody
 * @param proxy
 * @param port
 * @throws Exception
 */
public void doTest(String address, Map<String, String> parameters, Map<String, String> headers,
        String methodType, String requestBody, String proxy, int port, String uid, String pwd)
        throws Exception {

    // handle the proxy
    Proxy proxyObject = null;
    if (proxy != null && proxy.length() > 0 && port > 0) {
        InetSocketAddress proxyAddress = new InetSocketAddress(proxy, port);
        proxyObject = new Proxy(Proxy.Type.HTTP, proxyAddress);
    }

    // clear the returned results
    resultBody = EMPTY_STRING;

    // get the parms string
    String query = buildWebQuery(parameters);

    // Clear the address of any leading/trailing spaces
    address = address.trim();

    // build the complete URL
    URL url = null;
    if (query != null && query.trim().length() > 0) {
        // add the ? if there are parameters
        if (!address.endsWith("?") && !address.contains("?")) {//$NON-NLS-1$ //$NON-NLS-2$

            // if we're a "GET" - add the ? by default
            if (methodType.equalsIgnoreCase("GET")) { //$NON-NLS-1$
                address = address + "?"; //$NON-NLS-1$

                // if we're a PUT or POST, check if we have parms
                // and add the ? if we do
            } else if (methodType.equalsIgnoreCase("POST")//$NON-NLS-1$ 
                    || methodType.equalsIgnoreCase("PUT") //$NON-NLS-1$
                    || methodType.equalsIgnoreCase("DELETE")) { //$NON-NLS-1$
                if (query.trim().length() > 0) {
                    address = address + "?"; //$NON-NLS-1$
                }
            }
        } else if (address.contains("?")) { //$NON-NLS-1$
            address = address + "&"; //$NON-NLS-1$
        }
        // add parms to the url if we have some
        url = new URL(address + query);
    } else {
        url = new URL(address);
    }

    // make connection
    HttpURLConnection httpurlc = null;
    if (proxyObject == null) {
        httpurlc = (HttpURLConnection) url.openConnection();
    } else {
        // if have proxy, pass it along
        httpurlc = (HttpURLConnection) url.openConnection(proxyObject);
    }

    // since we are expecting output back, set to true
    httpurlc.setDoOutput(true);

    // not sure what this does - may be used for authentication?
    httpurlc.setAllowUserInteraction(false);

    // set whether this is a GET or POST
    httpurlc.setRequestMethod(methodType);

    // if we have headers to add
    if (headers != null && !headers.isEmpty()) {
        Iterator<?> iter = headers.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) iter.next();
            if (entry.getKey() != null && entry.getKey() instanceof String)
                httpurlc.addRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }

    // if we have basic authentication to add, add it!
    if (uid != null && pwd != null) {
        String authStr = uid + ':' + pwd;
        byte[] authEncByte = Base64.encodeBase64(authStr.getBytes());
        String authStringEnc = new String(authEncByte);
        httpurlc.addRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$//$NON-NLS-2$
    }

    requestHeaders = httpurlc.getRequestProperties();

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // CONNECT!
    httpurlc.connect();

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // If we are doing a POST and we have some request body to pass along, do it
    if (requestBody != null && (methodType.equalsIgnoreCase("POST") //$NON-NLS-1$
            || methodType.equalsIgnoreCase("PUT"))) { //$NON-NLS-1$
        requestBody = WSTestUtils.stripNLsFromXML(requestBody);
        OutputStreamWriter out = new OutputStreamWriter(httpurlc.getOutputStream());
        String stripped = stripCRLF(requestBody);
        out.write(stripped);
        out.close();
    }

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // if we have headers to pass to user, copy them
    if (httpurlc.getHeaderFields() != null) {
        resultHeaders = httpurlc.getHeaderFields();
    }

    // retrieve result and put string results into the response
    InputStream is = null;
    try {
        is = httpurlc.getInputStream();
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");//$NON-NLS-1$
        }
        br.close();
        resultBody = sb.toString();
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    } catch (IOException ie) {
        try {
            is = httpurlc.getErrorStream();

            // is possible that we're getting nothing back in the error stream
            if (is != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");//$NON-NLS-1$
                }
                br.close();
                resultBody = sb.toString();
            }
        } catch (IOException ie2) {
            resultBody = ie2.getLocalizedMessage();
        }
    }

    // as a last resort, if we still have nothing to report,
    // show an error message to the user
    if (resultBody == null || resultBody.trim().isEmpty()) {
        resultBody = JBossWSUIMessages.JAXRSRSTestView_Message_Unsuccessful_Test;
    }

    // disconnect explicitly (may not be necessary)
    httpurlc.disconnect();
}

From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java

protected HttpURLConnection createConnection(URL url, String userAgent, String acceptedVersion,
        String acceptedMediaType, ISSLCertificateCallback callback, int timeout) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (isHttps(url)) {
        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
        SSLContext sslContext = setSSLCallback(sslAuthorizationCallback, url, httpsConnection);
        setFilteredCiphers(excludedSSLCipherRegex, sslContext, httpsConnection);
    }//from ww  w.  j a v  a2 s  .c  om
    setAuthorization(connection);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setAllowUserInteraction(false);
    setConnectTimeout(NO_TIMEOUT, connection);
    setReadTimeout(timeout, connection);
    // wont work when switching http->https
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4620571
    connection.setInstanceFollowRedirects(true);
    setUserAgent(userAgent, connection);
    setAcceptHeader(acceptedVersion, acceptedMediaType, connection);

    return connection;
}

From source file:com.edgenius.wiki.service.impl.NotificationServiceImpl.java

public void doVersionCheck() {
    HttpURLConnection conn = null;
    try {/*from  ww w . j av a  2s .  c  o m*/
        log.info("Version check starting");
        int currVer = (int) (NumberUtils.toFloat(Version.VERSION, 0f) * 1000);
        //hard code
        URL url = new URL("http://product.edgenius.com/versioncheck/" + SharedConstants.APP_NAME + "/"
                + Installation.INSTANCE_ID + "/" + currVer);
        //         Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy url", 80));
        //         conn = (HttpURLConnection) url.openConnection(proxy);
        conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        //         conn.addRequestProperty("Authorization", "Basic "+encrytString(username+":" + password));

        conn.setReadTimeout(20000);
        InputStream in = conn.getInputStream();
        StringBuffer sb = new StringBuffer();
        byte[] b = new byte[1024 * 10];
        int len;
        while ((len = in.read(b)) != -1) {
            sb.append(new String(b, 0, len));

        }
        String content = sb.toString();
        //         String content = "<version>3.01</version>";
        int start = content.indexOf("<version>");
        int end = content.indexOf("</version>");
        if (start != -1 && end != -1 && start < end) {
            String verStr = content.substring(start + 9, end);
            int version = (int) (NumberUtils.toFloat(verStr, 0f) * 1000);

            if (version > 0 && currVer > 0) {
                if (version > currVer) {
                    //check if this new version is already send notification to user, if so, silence.

                    List<ActivityLog> activities = activityLog.getByTarget(
                            ActivityType.Type.SYSTEM_EVENT.getCode(),
                            ActivityType.SubType.VERSION_PING.getCode(), version, "VERSION_CHECK"); //hardcode
                    if (activities == null || activities.size() == 0) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("newVer", verStr);
                        map.put("currVer", Version.VERSION);
                        mailService.sendPlainToSystemAdmins(WikiConstants.MAIL_TEMPL_VERSION_CHECK, map);
                        log.info("New version {} found and notified to system administrators.", version);

                        //log activity
                        ActivityLog activity = new ActivityLog();
                        activity.setType(ActivityType.Type.SYSTEM_EVENT.getCode());
                        activity.setSubType(ActivityType.SubType.VERSION_PING.getCode());
                        activity.setTgtResourceType(version);
                        activity.setTgtResourceName("VERSION_CHECK");//hardcode
                        activity.setExtroInfo(verStr);
                        activity.setCreatedDate(new Date());
                        activityLog.save(activity);
                    } else {
                        log.info(
                                "New version {} found, but this version is already notified so no action takes",
                                2000);
                    }
                }
            } else {
                log.info("Wrong version number returned:{}", content);
            }
        }
        log.info("Version check is done");

    } catch (Exception e) {
        log.warn("Version check not success. This probably because of your network connection");
    } finally {
        try {
            if (conn != null)
                conn.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:MegaHandler.java

private String api_request(String data) {
    HttpURLConnection connection = null;
    try {/*from  w ww.j  a va  2s. c  o m*/
        String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number;
        if (sid != null)
            urlString += "&sid=" + sid;

        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //use post method
        connection.setDoOutput(true); //we will send stuff
        connection.setDoInput(true); //we want feedback
        connection.setUseCaches(false); //no caches
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Content-Type", "text/xml");

        OutputStream out = connection.getOutputStream();
        try {
            OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write("[" + data + "]"); //data is JSON object containing the api commands
            wr.flush();
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the output stream
            if (out != null)
                out.close();
        }

        InputStream in = connection.getInputStream();
        StringBuffer response = new StringBuffer();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = rd.readLine()) != null) {
                response.append(line);
            }
            rd.close(); //close the reader
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the input stream
            if (in != null)
                in.close();
        }

        return response.toString().substring(1, response.toString().length() - 1);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.docdoku.client.data.MainModel.java

private void performHeadHTTPMethod(String pURL) throws MalformedURLException, IOException {
    URL url = new URL(pURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(false);//from   www .ja va2 s  . c  o m
    conn.setAllowUserInteraction(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    byte[] encoded = org.apache.commons.codec.binary.Base64
            .encodeBase64((getLogin() + ":" + getPassword()).getBytes("ISO-8859-1"));
    conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
    conn.setRequestMethod("HEAD");
    conn.connect();
    int code = conn.getResponseCode();
    System.out.println("Head HTTP response code: " + code);
}

From source file:org.codehaus.wadi.web.impl.StandardHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest req = context.getHreq();
    HttpServletResponse res = context.getHres();

    String requestURI = getRequestURI(req);
    String qs = req.getQueryString();
    if (qs != null) {
        requestURI = new StringBuffer(requestURI).append("?").append(qs).toString();
    }//w w  w. j av  a2s.  co m

    URL url = null;
    try {
        url = new URL("http", uri.getHost(), uri.getPort(), requestURI);
        if (_log.isTraceEnabled())
            _log.trace("proxying to: " + url);
    } catch (MalformedURLException e) {
        if (_log.isWarnEnabled())
            _log.warn("bad proxy url: " + url, e);
        throw new IrrecoverableException("bad proxy url", e);
    }

    long startTime = System.currentTimeMillis();

    HttpURLConnection huc = null;
    String m = req.getMethod();
    try {
        huc = (HttpURLConnection) url.openConnection(); // IOException
        huc.setRequestMethod(m); // ProtocolException
    } catch (ProtocolException e) {
        if (_log.isWarnEnabled())
            _log.warn("unsupported http method: " + m, e);
        throw new IrrecoverableException("unsupported HTTP method: " + m, e);
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy IO problem", e);
        throw new RecoverableException("could not open proxy connection", e);
    }

    huc.setAllowUserInteraction(false);
    huc.setInstanceFollowRedirects(false);

    // check connection header
    // TODO - this might need some more time: see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    String connectionHdr = req.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers - inefficient, but we are constrained by servlet API
    {
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String hdr = (String) e.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) // what is going on here ?
                continue;
            // HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. Connection options are signaled by the presence of a connection-token in the Connection header field, not by any corresponding additional header field(s), since the additional header field may not be sent if there are no parameters associated with that connection option
            if (_WADI_IsSecure.equals(hdr)) // don't worry about case - we should be the only one messing with this header...
                continue; // strip this out - we may be being spoofed

            for (Enumeration f = req.getHeaders(hdr); f.hasMoreElements();) {
                String val = (String) f.nextElement();
                if (val != null) {
                    huc.addRequestProperty(hdr, val);
                }
            }
        }
    }

    // content ?
    boolean hasContent = false;
    {
        int contentLength = 0;
        String tmp = huc.getRequestProperty("Content-Length");
        if (tmp != null) {
            try {
                contentLength = Integer.parseInt(tmp);
            } catch (NumberFormatException ignore) {
                // ignore
            }
        }

        if (contentLength > 0)
            hasContent = true;
        else
            hasContent = (huc.getRequestProperty("Content-Type") != null);
    }

    // proxy
    {
        huc.addRequestProperty("Via", "1.1 " + req.getLocalName() + ":" + req.getLocalPort() + " \"WADI\""); // TODO - should we be giving out personal details ?
        huc.addRequestProperty("X-Forwarded-For", req.getRemoteAddr()); // adds last link in request chain...
        // String tmp=uc.getRequestProperty("Max-Forwards"); // TODO - do we really need to bother with this ?
    }

    // cache-control
    {
        String cacheControl = huc.getRequestProperty("Cache-Control");
        if (cacheControl != null
                && (cacheControl.indexOf("no-cache") >= 0 || cacheControl.indexOf("no-store") >= 0))
            huc.setUseCaches(false);
    }

    // confidentiality
    {
        if (req.isSecure()) {
            huc.addRequestProperty(_WADI_IsSecure, req.getLocalAddr().toString());
        }

        // at the other end, if this header is present we must :

        // wrap the request so that req.isSecure()=true, before processing...
        // mask the header - so it is never seen by the app.

        // the code for the other end should live in this class.

        // this code should also confirm that it not being spoofed by confirming that req.getRemoteAddress() is a cluster member...
    }
    // customize Connection
    huc.setDoInput(true);

    // client->server
    int client2ServerTotal = 0;
    {
        if (hasContent) {
            huc.setDoOutput(true);

            OutputStream toServer = null;
            try {
                InputStream fromClient = req.getInputStream(); // IOException
                toServer = huc.getOutputStream(); // IOException
                client2ServerTotal = copy(fromClient, toServer, 8192);
            } catch (IOException e) {
                new IrrecoverableException("problem proxying client request to server", e);
            } finally {
                if (toServer != null) {
                    try {
                        toServer.close(); // IOException
                    } catch (IOException e) {
                        _log.warn("problem closing server request stream", e);
                    }
                }
            }
        }
    }

    // Connect
    try {
        huc.connect(); // IOException
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy connection problem: " + url, e);
        throw new RecoverableException("could not connect to proxy target", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 0;
    if (huc == null) {
        try {
            fromServer = huc.getInputStream(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring client output", e);
        }
    } else {
        code = 502;
        //         String message="Bad Gateway: could not read server response code or message";
        try {
            code = huc.getResponseCode(); // IOException
            //            message=huc.getResponseMessage(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring http server response code/message", e);
        } finally {
            //            res.setStatus(code, message); - deprecated
            res.setStatus(code);
        }

        if (code < 400) {
            // 1XX:continue, 2XX:successful, 3XX:multiple-choices...
            try {
                fromServer = huc.getInputStream(); // IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem acquiring http client output", e);
            }
        } else {
            // 4XX:client, 5XX:server error...
            fromServer = huc.getErrorStream(); // why does this not throw IOException ?
            // TODO - do we need to use sendError()?
        }
    }

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

    // set response headers
    if (false) {
        int h = 0;
        String hdr = huc.getHeaderFieldKey(h);
        String val = huc.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = (hdr != null) ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr))
                res.addHeader(hdr, val);

            // if (_log.isDebugEnabled()) _log.debug("res " + hdr + ": " + val);

            h++;
            hdr = huc.getHeaderFieldKey(h);
            val = huc.getHeaderField(h);
        }
    } else {
        // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
        // Try this inside Tomcat...
        String key;
        for (int i = 1; (key = huc.getHeaderFieldKey(i)) != null; i++) {
            key = key.toLowerCase();
            String val = huc.getHeaderField(i);
            if (val != null && !_DontProxyHeaders.contains(key)) {
                res.addHeader(key, val);
            }
        }
    }

    // do we need another Via header in the response...

    // server->client
    int server2ClientTotal = 0;
    {
        if (fromServer != null) {
            try {
                OutputStream toClient = res.getOutputStream();// IOException
                server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem proxying server response back to client", e);
            } finally {
                try {
                    fromServer.close();
                } catch (IOException e) {
                    // well - we did our best...
                    _log.warn("problem closing server response stream", e);
                }
            }
        }
    }

    huc.disconnect();

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled())
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", url:" + url);
}

From source file:compiler.downloader.MegaHandler.java

private String api_request(String data) {
    HttpURLConnection connection = null;
    try {/*from   w  w w  . ja v  a  2  s.  co m*/
        String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number;
        if (sid != null) {
            urlString += "&sid=" + sid;
        }

        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //use post method
        connection.setDoOutput(true); //we will send stuff
        connection.setDoInput(true); //we want feedback
        connection.setUseCaches(false); //no caches
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Content-Type", "text/xml");

        OutputStream out = connection.getOutputStream();
        try {
            OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write("[" + data + "]"); //data is JSON object containing the api commands
            wr.flush();
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the output stream
            if (out != null) {
                out.close();
            }
        }

        InputStream in = connection.getInputStream();
        StringBuffer response = new StringBuffer();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
            }
            rd.close(); //close the reader
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the input stream
            if (in != null) {
                in.close();
            }
        }

        return response.toString().substring(1, response.toString().length() - 1);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.docdoku.client.actions.MainController.java

private void uploadFileWithServlet(final Component pParent, File pLocalFile, String pURL) throws IOException {
    System.out.println("Uploading file with servlet");
    InputStream in = null;//from   w w  w.j  a v a  2s. c o m
    OutputStream out = null;
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        performHeadHTTPMethod(pURL);

        MainModel model = MainModel.getInstance();
        URL url = new URL(pURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        byte[] encoded = org.apache.commons.codec.binary.Base64
                .encodeBase64((model.getLogin() + ":" + model.getPassword()).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
        byte[] header = (twoHyphens + boundary + lineEnd + "Content-Disposition: form-data; name=\"upload\";"
                + " filename=\"" + pLocalFile + "\"" + lineEnd + lineEnd).getBytes("ISO-8859-1");
        byte[] footer = (lineEnd + twoHyphens + boundary + twoHyphens + lineEnd).getBytes("ISO-8859-1");

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //conn.setRequestProperty("Content-Length",len + "");
        long len = header.length + pLocalFile.length() + footer.length;
        conn.setFixedLengthStreamingMode((int) len);
        out = new BufferedOutputStream(conn.getOutputStream(), Config.BUFFER_CAPACITY);
        out.write(header);

        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        in = new ProgressMonitorInputStream(pParent,
                I18N.BUNDLE.getString("UploadMsg_part1") + " " + pLocalFile.getName() + " ("
                        + (int) (pLocalFile.length() / 1024) + I18N.BUNDLE.getString("UploadMsg_part2"),
                new BufferedInputStream(new FileInputStream(pLocalFile), Config.BUFFER_CAPACITY));
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

        out.write(footer);
        out.flush();

        int code = conn.getResponseCode();
        System.out.println("Upload HTTP response code: " + code);
        if (code != 200) {
            //TODO create a more suitable exception
            throw new IOException();
        }
        out.close();
    } catch (InterruptedIOException pEx) {
        throw pEx;
    } catch (IOException pEx) {
        out.close();
        throw pEx;
    } finally {
        in.close();
        conn.disconnect();
    }
}

From source file:com.odoko.solrcli.actions.CrawlPostAction.java

/**
 * Reads data from the data stream and posts it to solr,
 * writes to the response to output/*from w ww. j a va2 s. c  om*/
 * @return true if success
 */
public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) {
  boolean success = true;
  if(type == null)
    type = DEFAULT_CONTENT_TYPE;
  HttpURLConnection urlc = null;
  try {
    try {
      urlc = (HttpURLConnection) url.openConnection();
      try {
        urlc.setRequestMethod("POST");
      } catch (ProtocolException e) {
        fatal("Shouldn't happen: HttpURLConnection doesn't support POST??"+e);
      }
      urlc.setDoOutput(true);
      urlc.setDoInput(true);
      urlc.setUseCaches(false);
      urlc.setAllowUserInteraction(false);
      urlc.setRequestProperty("Content-type", type);

      if (null != length) urlc.setFixedLengthStreamingMode(length);

    } catch (IOException e) {
      fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
      success = false;
    }
        
    OutputStream out = null;
    try {
      out = urlc.getOutputStream();
      pipe(data, out);
    } catch (IOException e) {
      fatal("IOException while posting data: " + e);
      success = false;
    } finally {
      try { if(out!=null) out.close(); } catch (IOException x) { /*NOOP*/ }
    }
        
    InputStream in = null;
    try {
      if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) {
        warn("Solr returned an error #" + urlc.getResponseCode() + 
              " " + urlc.getResponseMessage());
        success = false;
      }

      in = urlc.getInputStream();
      pipe(in, output);
    } catch (IOException e) {
      warn("IOException while reading response: " + e);
      success = false;
    } finally {
      try { if(in!=null) in.close(); } catch (IOException x) { /*NOOP*/ }
    }
        
  } finally {
    if(urlc!=null) urlc.disconnect();
  }
  return success;
}