Example usage for java.net URLConnection setConnectTimeout

List of usage examples for java.net URLConnection setConnectTimeout

Introduction

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

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:com.tc.util.io.ServerURL.java

private HttpURLConnection createSecureConnection(PwProvider pwProvider) {
    if (securityInfo.isSecure()) {
        Assert.assertNotNull("Secured URL '" + theURL + "', yet PwProvider instance", pwProvider);
    }//from   w w w  .  j  av  a2  s .co m

    URLConnection urlConnection;
    try {
        urlConnection = theURL.openConnection();
        String uri = null;

        if (securityInfo.isSecure()) {
            if (securityInfo.getUsername() != null) {
                String encodedUsername = URLEncoder.encode(securityInfo.getUsername(), "UTF-8").replace("+",
                        "%20");
                uri = "tc://" + encodedUsername + "@" + theURL.getHost() + ":" + theURL.getPort();
                final char[] passwordTo;
                try {
                    final URI theURI = new URI(uri);
                    passwordTo = pwProvider.getPasswordFor(theURI);
                } catch (URISyntaxException e) {
                    throw new TCRuntimeException("Couldn't create URI to connect to " + uri, e);
                }
                Assert.assertNotNull("No password for " + theURL + " found!", passwordTo);
                urlConnection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder()
                        .encode((securityInfo.getUsername() + ":" + new String(passwordTo)).getBytes()));
            }

            if (DISABLE_HOSTNAME_VERIFIER || TRUST_ALL_CERTS) {
                tweakSecureConnectionSettings(urlConnection);
            }
        }
    } catch (IOException e1) {
        throw new IllegalStateException(e1);
    }

    if (timeout > -1) {
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
    }
    return (HttpURLConnection) urlConnection;
}

From source file:com.hichinaschool.flashcards.async.Connection.java

private Payload doInBackgroundDownloadSharedDeck(Payload data) {
    String url = (String) data.data[0];
    String colFilename = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpImportFile.apkg";
    URL fileUrl;//w ww .  j  a v  a  2 s  .c  o  m
    URLConnection conn;
    InputStream cont = null;
    try {
        fileUrl = new URL(url);
        if (url.startsWith("https")) {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
            HttpsURLConnection httpsConn = (HttpsURLConnection) fileUrl.openConnection();
            httpsConn.setSSLSocketFactory(context.getSocketFactory());
            conn = httpsConn;
        } else {
            conn = (HttpURLConnection) fileUrl.openConnection();
        }
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        cont = conn.getInputStream();
    } catch (MalformedURLException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (NoSuchAlgorithmException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (KeyStoreException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        return data;
    } catch (KeyManagementException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    }
    if (cont == null) {
        data.success = false;
        return data;
    }
    File file = new File(colFilename);
    OutputStream output = null;
    try {
        file.createNewFile();
        output = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[Utils.CHUNK_SIZE];
        int len;
        int count = 0;
        while ((len = cont.read(buf)) >= 0) {
            output.write(buf, 0, len);
            count += len;
            publishProgress(new Object[] { count / 1024 });
        }
        output.close();
    } catch (IOException e) {
        try {
            output.close();
        } catch (IOException e1) {
            // do nothing
        }
        // no write access or sd card full
        file.delete();
        data.success = false;
        return data;
    }
    data.success = true;
    data.result = colFilename;
    return data;
}

From source file:uk.ac.ebi.intact.editor.controller.curate.publication.PublicationController.java

public boolean isCitexploreOnline() {
    if (isCitexploreActive) {
        return true;
    }/*from w w w. ja  va  2  s  .co m*/
    if (log.isDebugEnabled())
        log.debug("Checking Europe Pubmed Central status");
    try {
        URL url = new URL("http://www.ebi.ac.uk/webservices/citexplore/v3.0.1/service?wsdl");
        final URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(1000);
        urlConnection.setReadTimeout(1000);
        urlConnection.connect();
    } catch (Exception e) {
        log.debug("\tEurope Pubmed Central is not reachable");

        isCitexploreActive = false;
        return false;
    }

    isCitexploreActive = true;
    return true;
}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Returns a URLCOnnection for given URL. If the URL is https one , then URLConnectin is a
 * HttpsURLCOnnection and it is configured with KeyStores given in the synapse.properties file
 *
 * @param url URL//from   w ww.j  av  a  2s . c o m
 * @return URLConnection for given URL
 */
public static URLConnection getURLConnection(URL url) {

    try {
        if (url == null) {
            if (log.isDebugEnabled()) {
                log.debug("Provided URL is null");
            }
            return null;
        }

        URLConnection connection;
        if (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")) {

            Properties synapseProperties = SynapsePropertiesLoader.loadSynapseProperties();

            String proxyHost = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_HOST);
            String proxyPort = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PORT);

            // get the list of excluded hosts for proxy
            List<String> excludedHosts = getExcludedHostsForProxy(synapseProperties);

            if (proxyHost != null && proxyPort != null && !excludedHosts.contains(proxyHost)) {
                SocketAddress sockaddr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort));
                Proxy proxy = new Proxy(Proxy.Type.HTTP, sockaddr);

                if (url.getProtocol().equalsIgnoreCase("https")) {
                    connection = getHttpsURLConnection(url, synapseProperties, proxy);
                } else {
                    connection = url.openConnection(proxy);
                }
            } else {
                if (url.getProtocol().equalsIgnoreCase("https")) {
                    connection = getHttpsURLConnection(url, synapseProperties, null);
                } else {
                    connection = url.openConnection();
                }
            }

            // try to see weather authentication is required
            String userName = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_USER);
            String password = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PASSWORD);
            if (userName != null && password != null) {
                String header = userName + ":" + password;
                byte[] encodedHeaderBytes = new Base64().encode(header.getBytes());
                String encodedHeader = new String(encodedHeaderBytes);

                connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedHeader);
            }
        } else {
            connection = url.openConnection();
        }

        connection.setReadTimeout(getReadTimeout());
        connection.setConnectTimeout(getConnectTimeout());
        connection.setRequestProperty("Connection", "close"); // if http is being used
        return connection;
    } catch (IOException e) {
        handleException("Error reading at URI ' " + url + " ' ", e);
    }
    return null;
}

From source file:com.mobiletin.inputmethod.indic.LatinIME.java

public boolean downloadFile(final String path) {
    try {//from ww w .ja v a2s .co m
        URL url = new URL(path);

        URLConnection ucon = url.openConnection();
        ucon.setReadTimeout(5000);
        ucon.setConnectTimeout(10000);

        /* ucon.setReadTimeout(1000);
         ucon.setConnectTimeout(1000);*/

        InputStream is = ucon.getInputStream();
        BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

        File file = new File(LatinIME.this.getDir("filesdir", Context.MODE_PRIVATE) + "/text.txt");

        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();

        FileOutputStream outStream = new FileOutputStream(file);
        byte[] buff = new byte[5 * 1024];

        int len;
        while ((len = inStream.read(buff)) != -1) {
            outStream.write(buff, 0, len);
        }

        outStream.flush();
        outStream.close();
        inStream.close();

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("exce", e.toString());
        return false;
    }

    return true;
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Download a path to a temporary file, returning a {@link File} instance with the path
 * contents./*from w  w  w . j  av  a  2  s  . c  o  m*/
 */
protected File downloadFile(String path) throws IOException {
    File target = getLocalPath(path + "_new");

    URL targetURL = null;
    try {
        targetURL = getRemoteURL(path);
    } catch (Exception e) {
        log.warning("Requested to download invalid control file", "appbase", _vappbase, "path", path, "error",
                e);
        throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
    }

    log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");

    // stream the URL into our temporary file
    InputStream fin = null;
    FileOutputStream fout = null;
    try {
        URLConnection uconn = ConnectionUtil.open(targetURL);
        // we have to tell Java not to use caches here, otherwise it will cache any request for
        // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
        // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
        // about it; turning off caches is not a performance concern, because when Getdown asks
        // to download a file, it expects it to come over the wire, not from a cache
        uconn.setUseCaches(false);
        // configure a connect timeout if requested
        int ctimeout = SysProps.connectTimeout();
        if (ctimeout > 0) {
            uconn.setConnectTimeout(ctimeout * 1000);
        }
        fin = uconn.getInputStream();
        fout = new FileOutputStream(target);
        StreamUtil.copy(fin, fout);
    } finally {
        StreamUtil.close(fin);
        StreamUtil.close(fout);
    }

    return target;
}

From source file:cm.aptoide.pt.MainActivity.java

private void getUpdateParameters() {
    try {/* w  w  w .j  a  v  a  2 s. c  om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        URLConnection url = new URL(LATEST_VERSION_CODE_URI).openConnection();
        url.setReadTimeout(3000);
        url.setConnectTimeout(3000);

        InputStream a = new BufferedInputStream(url.getInputStream());
        Document dom = builder.parse(new InputSource(a));
        dom.getDocumentElement().normalize();

        NodeList items = dom.getElementsByTagName("versionCode");
        if (items.getLength() > 0) {
            Node item = items.item(0);
            Log.d("Aptoide-XmlElement Name", item.getNodeName());
            Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim());
            updateParams.put("versionCode", item.getFirstChild().getNodeValue().trim());
        }

        items = dom.getElementsByTagName("uri");
        if (items.getLength() > 0) {
            Node item = items.item(0);
            Log.d("Aptoide-XmlElement Name", item.getNodeName());
            Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim());
            updateParams.put("uri", item.getFirstChild().getNodeValue().trim());
        }

        items = dom.getElementsByTagName("md5");
        if (items.getLength() > 0) {
            Node item = items.item(0);
            Log.d("Aptoide-XmlElement Name", item.getNodeName());
            Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim());
            updateParams.put("md5", item.getFirstChild().getNodeValue().trim());
        }

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

}

From source file:com.jp.miaulavirtual.DisplayMessageActivity.java

public int downloadFile(String request) {
    URL url2;/*from   ww  w.  j  a v a2 s  .  c o  m*/
    URLConnection conn;
    int lastSlash;
    Long fileSize = null;
    BufferedInputStream inStream;
    BufferedOutputStream outStream;
    FileOutputStream fileStream;
    String cookies = cookieFormat(scookie); // format cookie for URL setRequestProperty
    final int BUFFER_SIZE = 23 * 1024;
    int id = 1;

    File file = null;

    Log.d("Document", "2 respueesta");
    try {
        // Just resources
        lastSlash = url.toString().lastIndexOf('/');

        // Directory creation
        String root = Environment.getExternalStorageDirectory().toString();
        Boolean isSDPresent = android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        // check if is there external storage
        if (!isSDPresent) {
            task_status = false;
            id = 9;
        } else {
            String folder;
            if (comunidades) {
                folder = onData.get(2)[1];
            } else {
                folder = onData.get(1)[1];
            }
            folder = folder.replaceAll(
                    "\\d{4}-\\d{4}\\s|\\d{4}-\\d{2}\\s|Documentos\\sde\\s?|Gr\\..+?\\s|\\(.+?\\)", "");
            folder = folder.toString().trim();
            Log.d("Folder", folder);
            File myDir = new File(root + "/Android/data/com.jp.miaulavirtual/files/" + folder);
            myDir.mkdirs();

            // Document creation
            String name = url.toString().substring(lastSlash + 1);
            file = new File(myDir, name);
            Log.d("Document", name);
            fileSize = (long) file.length();

            // Check if we have already downloaded the whole file
            if (file.exists()) {
                dialog.setProgress(100); // full progress if file already donwloaded
            } else {
                // Start the connection with COOKIES (we already verified that the cookies aren't expired and we can use them)
                url2 = new URL(request);
                conn = url2.openConnection();
                conn.setUseCaches(false);
                conn.setRequestProperty("Cookie", cookies);
                conn.setConnectTimeout(10 * 1000);
                conn.setReadTimeout(20 * 1000);
                fileSize = (long) conn.getContentLength();

                // Check if we have necesary space
                if (fileSize >= myDir.getUsableSpace()) {
                    task_status = false;
                    id = 2;
                } else {

                    // Start downloading
                    inStream = new BufferedInputStream(conn.getInputStream());
                    fileStream = new FileOutputStream(file);
                    outStream = new BufferedOutputStream(fileStream, BUFFER_SIZE);
                    byte[] data = new byte[BUFFER_SIZE];
                    int bytesRead = 0;
                    int setMax = (conn.getContentLength() / 1024);
                    dialog.setMax(setMax);

                    while (task_status && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
                        outStream.write(data, 0, bytesRead);
                        // update progress bar
                        dialog.incrementProgressBy((int) (bytesRead / 1024));
                    }

                    // Close stream
                    outStream.close();
                    fileStream.close();
                    inStream.close();

                    // Delete file if Cancel button
                    if (!task_status) {
                        file.delete();
                        if (myDir.listFiles().length <= 0)
                            myDir.delete();
                        id = 0;
                    }
                }
            }
            Log.d("Status", String.valueOf(task_status));
            // Open file
            if (task_status) {
                Log.d("Type", "Hola2");
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);

                MimeTypeMap mime = MimeTypeMap.getSingleton();
                // Get extension file
                String file_s = file.toString();
                String extension = "";

                int i = file_s.lastIndexOf('.');
                int p = Math.max(file_s.lastIndexOf('/'), file_s.lastIndexOf('\\'));

                if (i > p) {
                    extension = file_s.substring(i + 1);
                }

                // Get extension reference
                String doc_type = mime.getMimeTypeFromExtension(extension);

                Log.d("Type", extension);

                intent.setDataAndType(Uri.fromFile(file), doc_type);
                startActivity(intent);
            }
        }
    } catch (MalformedURLException e) // Invalid URL
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 3;
    } catch (FileNotFoundException e) // FIle not found
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 4;
    } catch (SocketTimeoutException e) // time out
    {
        Log.d("Timeout", "Timeout");
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 7;
    } catch (Exception e) // General error
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 8;
    }
    Log.d("Type", String.valueOf(id));
    Log.d("StartOk3", "Como he llegado hasta aqu?");
    // notify completion
    Log.d("ID", String.valueOf(id));
    return id;

}

From source file:org.openymsg.network.Session.java

private String[] yahooAuth16Stage2(final String token, final String seed)
        throws LoginRefusedException, IOException, NoSuchAlgorithmException {
    String loginLink = "https://" + this.yahooLoginHost + "/config/pwtoken_login?src=ymsgr&ts=&token=" + token;

    URL u = new URL(loginLink);
    URLConnection uc = u.openConnection();
    uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT);

    if (uc instanceof HttpsURLConnection) {
        trustEveryone();//  w w w.  j av  a 2s  .  c o  m
        HttpsURLConnection httpUc = (HttpsURLConnection) uc;

        if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM))
            httpUc.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    return true;
                }
            });

        int responseCode = httpUc.getResponseCode();
        this.setSessionStatus(SessionState.STAGE2);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = uc.getInputStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = -1;
            byte[] buff = new byte[256];
            while ((read = in.read(buff)) != -1)
                out.write(buff, 0, read);

            int responseNo = -1;
            String crumb = null;
            String cookieY = null;
            String cookieT = null;

            StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n");
            if (toks.countTokens() <= 0)
                // errrorrrr
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage());

            try {
                responseNo = Integer.valueOf(toks.nextToken());
            } catch (NumberFormatException e) {
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage());
            }

            if (responseNo != 0 || !toks.hasMoreTokens())
                throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);

            while (toks.hasMoreTokens()) {
                String t = toks.nextToken();
                if (t.startsWith("crumb="))
                    crumb = t.replaceAll("crumb=", "");
                else if (t.startsWith("Y="))
                    cookieY = t.replaceAll("Y=", "");
                else if (t.startsWith("T="))
                    cookieT = t.replaceAll("T=", "");
            }

            if (crumb == null || cookieT == null || cookieY == null)
                throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);

            // Iterator<String> iter =
            // ((HttpURLConnection) uc).getHeaderFields().get("Set-Cookie").iterator();
            // while (iter.hasNext())
            // {
            // String string = iter.next();
            // System.out.println("\t" + string);
            // }
            this.cookieY = cookieY;
            this.cookieT = cookieT;
            return yahooAuth16Stage3(crumb + seed, cookieY, cookieT);
        }
    }

    throw new LoginRefusedException("Login Failed, unable to retrieve stage 2 url");
}