Example usage for java.net URLConnection setReadTimeout

List of usage examples for java.net URLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:org.wso2.carbon.cloud.gateway.agent.CGAgentUtils.java

private static URLConnection getURLConnection(URL url) throws CGException {
    URLConnection connection;
    if (url.getProtocol().equalsIgnoreCase("https")) {
        String msg = "Connecting through doesn't support";
        log.error(msg);// w  ww. ja  va2 s.  c om
        throw new CGException(msg);
    } else {
        try {
            connection = url.openConnection();
        } catch (IOException e) {
            throw new CGException("Could not open the URL connection", e);
        }
    }
    connection.setReadTimeout(getReadTimeout());
    connection.setConnectTimeout(getConnectTimeout());
    connection.setRequestProperty("Connection", "close"); // if http is being used
    return connection;
}

From source file:mas.MAS_VLDB.java

/**
 * @param args the command line arguments
 *//*from ww  w. java 2 s.c o m*/
public static String getData_old(String url_org, int start) {
    try {
        String complete_url = url_org + "&$skip=" + start;
        //            String url_str = generateURL(url_org, prop);
        URL url = new URL(complete_url);
        URLConnection yc = url.openConnection();
        yc.setConnectTimeout(25 * 1000);
        yc.setReadTimeout(25 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        StringBuffer result = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            //                System.out.println(inputLine);
            result.append(inputLine);
        }
        in.close();
        return result.toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * /*from  ww  w . ja v a2  s .  c  om*/
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static URLConnection getConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        // Trust all certificates
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
        SSLSocketFactory socketFactory = context.getSocketFactory();
        ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);

        // Allow all hostnames
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);

    }
    conn.setConnectTimeout(SOCKET_TIMEOUT);
    conn.setReadTimeout(SOCKET_TIMEOUT);
    return conn;
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static HashMap<String, Minecraft> getMinecraftVersions() throws RestfulAPIException {
    InputStream stream = null;//from   ww w. j av a2  s  .c o  m
    try {
        URLConnection conn = new URL(getMinecraftVersionURL()).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        HashMap<String, Minecraft> versions = mapper.readValue(stream,
                new TypeReference<Map<String, Minecraft>>() {
                });

        for (Minecraft result : versions.values()) {
            if (result.hasError()) {
                throw new RestfulAPIException("Error in json response: " + result.getError());
            }
        }

        return versions;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + getMinecraftVersionURL() + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + getMinecraftVersionURL() + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static List<Article> getNews() throws RestfulAPIException {
    InputStream stream = null;//from w ww  .j  av a  2s .c om
    try {
        URLConnection conn = new URL(getPlatformAPI() + "news/").openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        List<Article> versions = mapper.readValue(stream, new TypeReference<List<Article>>() {
        });

        for (Article result : versions) {
            if (result.hasError()) {
                throw new RestfulAPIException("Error in json response: " + result.getError());
            }
        }

        return versions;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + getMinecraftVersionURL() + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + getMinecraftVersionURL() + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.asimba.util.saml2.metadata.provider.MetadataProviderUtil.java

/**
 * Create a new HTTP Metadata Provider from the provided URL and HTTP settings<br/>
 * An exception is thrown when the provider could not be initiated.
 * //from w  w  w. jav a  2  s.  c om
 * @param sMetadataURL
 * @param sMetadataTimeout
 * @param oParserPool
 * @param oMPM
 * @return
 * @throws OAException
 */
public static MetadataProvider newHTTPMetadataProvider(String sId, String sMetadataURL, int iTimeout,
        ParserPool oParserPool, IMetadataProviderManager oMPM) throws OAException {
    MetadataProvider oProvider = null;

    // Check URL format
    URL oURLTarget = null;
    try {
        oURLTarget = new URL(sMetadataURL);
    } catch (MalformedURLException e) {
        _oLogger.error("Invalid url for metadata: " + sMetadataURL, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    // Check valid and existing destination (with configured timeout settings)
    try {
        URLConnection oURLConnection = oURLTarget.openConnection();
        if (iTimeout <= 0) {
            oURLConnection.setConnectTimeout(3000);
            oURLConnection.setReadTimeout(3000);
        } else {
            oURLConnection.setConnectTimeout(iTimeout);
            oURLConnection.setReadTimeout(iTimeout);
        }

        oURLConnection.connect();
    } catch (IOException e) {
        _oLogger.warn("Could not connect to metadata url: " + sMetadataURL + "(using timout "
                + (iTimeout == 0 ? "3000" : iTimeout) + "ms)", e);
    }

    // Establish dedicated refresh timer:
    String sTimername = "Metadata_HTTP-" + (oMPM == null ? "" : oMPM.getId() + "-") + sId + "-Timer";
    Timer oRefreshTimer = new Timer(sTimername, true);

    // Establish HttpClient
    HttpClient oHttpClient = new HttpClient();

    if (iTimeout > 0) {
        // Set configured Timeout settings
        oHttpClient.getParams().setSoTimeout(iTimeout);
    }

    oProvider = MetadataProviderUtil.createProviderForURL(sMetadataURL, oParserPool, oRefreshTimer,
            oHttpClient);

    if (oProvider != null) {
        // Start managing it:
        if (oMPM != null) {
            oMPM.setProviderFor(sId, oProvider, oRefreshTimer);
        }
    } else {
        // Unsuccessful creation; clean up created Timer
        oRefreshTimer.cancel();
    }

    return oProvider;
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

/**
 * download file url and save it//from w  ww .j  a  v  a2 s.  com
 *
 * @param url
 */
public static String downloadFile(String url) {
    int BYTE_ARRAY_SIZE = 1024;
    int CONNECTION_TIMEOUT = 30000;
    int READ_TIMEOUT = 30000;

    // downloading cover image and saving it into file
    try {
        URL imageUrl = new URL(URLDecoder.decode(url));
        URLConnection conn = imageUrl.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

        File resFile = new File(cachePath + File.separator + Utils.md5(url));
        if (!resFile.exists()) {
            resFile.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(resFile);
        int current = 0;
        byte[] buf = new byte[BYTE_ARRAY_SIZE];
        Arrays.fill(buf, (byte) 0);
        while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) {
            fos.write(buf, 0, current);
            Arrays.fill(buf, (byte) 0);
        }

        bis.close();
        fos.flush();
        fos.close();
        Log.d("", "");
        return resFile.getAbsolutePath();
    } catch (SocketTimeoutException e) {
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:fr.free.movierenamer.utils.URIRequest.java

private static URLConnection openConnection(URI uri, RequestProperty... properties) throws IOException {
    boolean isHttpRequest = Proxy.Type.HTTP.name().equalsIgnoreCase(uri.getScheme());
    URLConnection connection;
    if (isHttpRequest && Settings.getInstance().isProxyIsOn()) {
        Settings settings = Settings.getInstance();
        Proxy proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(settings.getProxyUrl(), settings.getProxyPort()));
        connection = uri.toURL().openConnection(proxy);
    } else {//from  w w  w. ja v a2  s .c o m
        connection = uri.toURL().openConnection();
    }

    if (isHttpRequest) {
        Settings settings = Settings.getInstance();
        connection.setReadTimeout(settings.getHttpRequestTimeOut() * 1000); // in ms
        //fake user agent ;)
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
        connection.addRequestProperty("From", "googlebot(at)googlebot.com");
        connection.addRequestProperty("Accept", "*/*");
        String customUserAgent = settings.getHttpCustomUserAgent();
        if (customUserAgent != null && customUserAgent.length() > 0) {
            connection.addRequestProperty("User-Agent", customUserAgent);
        }
    }

    connection.addRequestProperty("Accept-Encoding", "gzip,deflate");
    connection.addRequestProperty("Accept-Charset", UTF + "," + ISO); // important for accents !

    if (properties != null) {
        for (RequestProperty property : properties) {
            connection.addRequestProperty(property.getKey(), property.getValue());
        }
    }

    return connection;
}

From source file:com.varaneckas.hawkscope.Version.java

/**
 * Asynchroniously checks if a newer version of Hawkscope is available
 * //from w  ww  .ja  v  a  2  s  .  c om
 * @return
 */
public static void checkForUpdate() {
    if (!cfg.checkForUpdates()) {
        return;
    }
    try {
        log.debug("Checking for updates...");
        URLConnection conn = null;
        final URL versionCheckUrl = new URL(VERSION_CHECK_URL);
        Proxy proxy = null;
        if (cfg.isHttpProxyInUse()) {
            proxy = new Proxy(Type.HTTP,
                    InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort()));
            conn = versionCheckUrl.openConnection(proxy);
        } else {
            conn = versionCheckUrl.openConnection();
        }
        conn.setConnectTimeout(Constants.CONNECTION_TIMOUT);
        conn.setReadTimeout(Constants.CONNECTION_TIMOUT);
        final InputStream io = conn.getInputStream();
        int c = 0;
        final StringBuilder version = new StringBuilder();
        while ((c = io.read()) != -1) {
            version.append((char) c);
        }
        if (log.isDebugEnabled()) {
            log.debug("Check complete. Latest " + OSUtils.CURRENT_OS + " version: " + version.toString());
        }
        if (VERSION_NUMBER.compareTo(version.toString()) < 0) {
            log.info("Newer " + OSUtils.CURRENT_OS + " version available (" + version.toString()
                    + "). You should update Hawkscope!");
            isUpdateAvailable = true;
            updateVersion = version.toString();
        } else {
            log.info("You have the latest available version of Hawkscope: " + VERSION_NUMBER);
            isUpdateAvailable = false;
        }
        PluginManager.getInstance().checkPluginUpdates(PLUGIN_VERSION_CHECK_URL, proxy);
    } catch (final Exception e) {
        log.info("Failed checking for update: " + e.getMessage());
    }
}

From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password.//from  w  w w  .j  a  va 2s  . c o m
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}