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:net.sf.golly.HelpActivity.java

private String downloadURL(String urlstring, String filepath) {
    // download given url and save data in given file
    try {/*  w  w w  .j  a v  a  2 s  .c o m*/
        File outfile = new File(filepath);
        final int BUFFSIZE = 8192;
        FileOutputStream outstream = null;
        try {
            outstream = new FileOutputStream(outfile);
        } catch (FileNotFoundException e) {
            return "File not found: " + filepath;
        }

        long starttime = System.nanoTime();

        // Log.i("downloadURL: ", urlstring);
        URL url = new URL(urlstring);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setAllowUserInteraction(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("GET");
        connection.connect();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            outstream.close();
            return "No HTTP_OK response.";
        }

        // init info for progress bar
        int filesize = connection.getContentLength();
        int downloaded = 0;
        int percent;
        int lastpercent = 0;

        // stream the data to given file
        InputStream instream = connection.getInputStream();
        byte[] buffer = new byte[BUFFSIZE];
        int bufflen = 0;
        while ((bufflen = instream.read(buffer, 0, BUFFSIZE)) > 0) {
            outstream.write(buffer, 0, bufflen);
            downloaded += bufflen;
            percent = (int) ((downloaded / (float) filesize) * 100);
            if (percent > lastpercent) {
                progbar.setProgress(percent);
                lastpercent = percent;
            }
            // show proglayout only if download takes more than 1 second
            if (System.nanoTime() - starttime > 1000000000L) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        proglayout.setVisibility(LinearLayout.VISIBLE);
                    }
                });
                starttime = Long.MAX_VALUE; // only show it once
            }
            if (cancelled)
                break;
        }
        outstream.close();
        connection.disconnect();
        if (cancelled)
            return "Cancelled.";

    } catch (MalformedURLException e) {
        return "Bad URL string: " + urlstring;
    } catch (IOException e) {
        return "Could not connect to URL: " + urlstring;
    }
    return ""; // success
}

From source file:org.overlord.rtgov.activity.server.rest.client.RESTActivityServer.java

/**
 * {@inheritDoc}/*from  w w w.j a  v a  2 s  .c  o m*/
 */
public List<ActivityType> query(QuerySpec query) throws Exception {
    List<ActivityType> ret = null;

    URL queryUrl = new URL(_serverURL + QUERY);

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer[" + queryUrl + "] query: " + query);
    }

    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    initAuth(connection);

    connection.setRequestMethod("POST");

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/json");

    java.io.OutputStream os = connection.getOutputStream();

    byte[] b = ActivityUtil.serializeQuerySpec(query);
    os.write(b);

    os.flush();
    os.close();

    java.io.InputStream is = connection.getInputStream();

    b = new byte[is.available()];
    is.read(b);

    ret = ActivityUtil.deserializeActivityTypeList(b);

    is.close();

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer result: " + ret);
    }

    return (ret);
}

From source file:org.getobjects.appserver.core.WOHTTPConnection.java

/**
 * (GETobjects extension):/*from ww  w .  j  av  a 2  s .com*/
 * Called, whenever a new urlConnection is setup.
 *
 * Subclasses may override or extend the steps taken.
 */
protected void setupHttpURLConnection(HttpURLConnection _conn) {
    // According to WO53 documentation, this is indeed the first sendTimeout
    _conn.setConnectTimeout(this.sendTimeout);
    _conn.setAllowUserInteraction(false);
    _conn.setDoInput(true);
}

From source file:org.eurekastreams.server.service.opensocial.gadgets.spec.GadgetMetaDataHttpFetcher.java

/**
 * Retrieve the gadget metadata for the gadget definitions passed into the class.
 *
 * @param gadgetDefs/*from w w w  . ja  va 2s .c om*/
 *            Map of gadget definitions with the string key as the gadget def url.
 * @return List of GadgetMetaData objects that contain the metadata for the Gadget definitions passed in.
 * @throws Exception
 *             Error occurs on retrieving gadget metadata.
 */
public List<GadgetMetaDataDTO> getGadgetsMetaData(final Map<String, GeneralGadgetDefinition> gadgetDefs)
        throws Exception {
    if (gadgetDefs.isEmpty()) {
        return Collections.EMPTY_LIST;
    }

    try {
        // Make the http request here.
        StringWriter output = new StringWriter();
        URL endpoint = new URL(currentAppContextBaseUrl + "/gadgets/metadata");
        logger.debug("Target url for metadata request " + endpoint.toString());
        HttpURLConnection urlConnection = null;
        try {
            // Open the HttpConnection and make the POST.
            urlConnection = (HttpURLConnection) endpoint.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setAllowUserInteraction(false);
            urlConnection.setRequestProperty("Content-type", "application/json");
            OutputStream out = urlConnection.getOutputStream();
            try {
                Writer writer = new OutputStreamWriter(out, "UTF-8");
                pipe(new StringReader(assembleMetaDataRequestContext(gadgetDefs)), writer);
                writer.close();
            } catch (IOException e) {
                String ioErrorMsg = "IOException occurred writing params to outputstream.";
                logger.error(ioErrorMsg, e);
                throw new Exception(ioErrorMsg);
            } finally {
                if (out != null) {
                    out.close();
                }
            }

            // Retrieve the response.
            InputStream in = urlConnection.getInputStream();
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException iox) {
                String ioErrorMsg = "IOException occurred reading response from request";
                logger.error(ioErrorMsg, iox);
                throw iox;
            } finally {
                if (in != null) {
                    in.close();
                }
            }

            logger.debug("This is the output of the MetaData request: " + output.toString());
        } catch (IOException ioex) {
            throw ioex;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        return mapGadgetMetaDataJSONToObject(output.toString(), gadgetDefs);
    } catch (Exception ex) {
        String msg = "Error occurred retrieving gadget metadata " + ex;
        logger.error(msg, ex);
        throw ex;
    }
}

From source file:com.wareninja.android.opensource.mongolab_sdk.common.WebService.java

public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;/* ww w . ja v a  2s  .c  om*/
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        mHttpResponseCode = response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception e) {
        throw new IOException("Error connecting");
    } // end try-catch

    return in;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {/*from w w  w .j  a v  a  2s. c  o  m*/
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java

public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml,
        String soapAction) throws IOException, SOAPException {
    URI serviceLocation;/*  w  ww  . j a v  a  2s. c o  m*/
    try {
        serviceLocation = new URI(location);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid uri for artifact resolve: " + location);
    }
    if (log.isDebugEnabled())
        log.debug("serviceLocation..:" + serviceLocation);
    if (log.isDebugEnabled())
        log.debug("SOAP Request: " + xml);

    HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection();
    if (c instanceof HttpsURLConnection) {
        HttpsURLConnection sc = (HttpsURLConnection) c;

        if (ignoreCertPath) {
            sc.setSSLSocketFactory(new DummySSLSocketFactory());
            sc.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }
    c.setAllowUserInteraction(false);
    c.setDoInput(true);
    c.setDoOutput(true);
    c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length);
    c.setRequestMethod("POST");
    c.setReadTimeout(20000);
    c.setConnectTimeout(30000);

    addContentTypeHeader(xml, c);
    c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\"");

    if (username != null && password != null) {
        c.addRequestProperty("Authorization",
                "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES));
    }
    OutputStream outputStream = c.getOutputStream();
    IOUtils.write(xml, outputStream, "UTF-8");
    outputStream.flush();
    outputStream.close();

    if (c.getResponseCode() == 200) {
        InputStream inputStream = c.getInputStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();

        if (log.isDebugEnabled())
            log.debug("Server SOAP response: " + result);
        XMLObject res = SAMLUtil.unmarshallElementFromString(result);

        Envelope envelope = (Envelope) res;
        if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) {
            log.warn(
                    "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server");
            throw new SOAPException(c.getResponseCode(), result);
        }
        return envelope;
    } else {
        log.debug("Response code: " + c.getResponseCode());

        InputStream inputStream = c.getErrorStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();
        if (log.isDebugEnabled())
            log.debug("Server SOAP fault: " + result);

        throw new SOAPException(c.getResponseCode(), result);
    }
}

From source file:com.dawg6.d3api.server.D3IO.java

private <T> T readValue(ObjectMapper mapper, URL url, Class<T> clazz, int retries)
        throws JsonParseException, JsonMappingException, IOException {

    //      log.info("URL " + url);

    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);/*from  w  w w  .  j a v  a2 s.  co  m*/
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(connectTimeout);
    c.setReadTimeout(readTimeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
    case 200:
    case 201:
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        try {
            mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            return mapper.readValue(sb.toString(), clazz);
        } catch (Exception e) {
            log.severe("JSON = " + sb.toString());
            log.log(Level.SEVERE, e.getMessage());

            return null;
        }

    case 408:
    case 504:
        log.info("HTTP Response: " + status + ", retries = " + retries + ", URL: " + url);
        errors++;
        onError(status);

        if (retries > 0) {
            retryAttempts++;
            onRetry();
            return readValue(mapper, url, clazz, retries - 1);
        } else
            return null;

    default:
        log.severe("HTTP Response: " + status + ", URL: " + url);
        return null;
    }
}

From source file:org.codehaus.mojo.tomcat.TomcatManager.java

/**
 * Invokes Tomcat manager with the specified command and content data.
 * /*from w w  w  . ja  v a2 s . c om*/
 * @param path the Tomcat manager command to invoke
 * @param data an input stream to the content data
 * @return the Tomcat manager response
 * @throws TomcatManagerException if the Tomcat manager request fails
 * @throws IOException if an i/o error occurs
 */
protected String invoke(String path, InputStream data) throws TomcatManagerException, IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url + path).openConnection();
    connection.setAllowUserInteraction(false);
    connection.setDoInput(true);
    connection.setUseCaches(false);

    if (data == null) {
        connection.setDoOutput(false);
        connection.setRequestMethod("GET");
    } else {
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/octet-stream");
    }

    if (userAgent != null) {
        connection.setRequestProperty("User-Agent", userAgent);
    }
    connection.setRequestProperty("Authorization", toAuthorization(username, password));

    connection.connect();

    if (data != null) {
        pipe(data, connection.getOutputStream());
    }

    String response = toString(connection.getInputStream(), MANAGER_CHARSET);

    if (!response.startsWith("OK -")) {
        throw new TomcatManagerException(response);
    }

    return response;
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public String uploadFile(File pLocalFile, String pURL)
        throws IOException, LoginException, NoSuchAlgorithmException {
    InputStream in = null;/*from w w w  . j  a  v a2 s  .c  o m*/
    OutputStream out = null;
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        URL url = new URL(pURL);
        System.out.println("Uploading file: " + pLocalFile.getName() + " to " + url.getHost());
        performHeadHTTPMethod(url);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        byte[] encoded = Base64.encodeBase64((login + ":" + password).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(), BUFFER_CAPACITY);
        out.write(header);

        byte[] data = new byte[CHUNK_SIZE];
        int length;
        MessageDigest md = MessageDigest.getInstance("MD5");
        in = new ConsoleProgressMonitorInputStream(pLocalFile.length(), new DigestInputStream(
                new BufferedInputStream(new FileInputStream(pLocalFile), BUFFER_CAPACITY), md));
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

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

        manageHTTPCode(conn);

        byte[] digest = md.digest();
        return Base64.encodeBase64String(digest);
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (conn != null)
            conn.disconnect();
    }
}