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:com.moviejukebox.tools.WebBrowser.java

public URLConnection openProxiedConnection(URL url) throws IOException {
    URLConnection cnx = url.openConnection(YamjHttpClientBuilder.getProxy());

    if (PROXY_USERNAME != null) {
        cnx.setRequestProperty("Proxy-Authorization", ENCODED_PASSWORD);
    }/*from ww  w . ja  va 2 s. c  o m*/

    cnx.setConnectTimeout(TIMEOUT_CONNECT);
    cnx.setReadTimeout(TIMEOUT_READ);

    return cnx;
}

From source file:com.twitter.hraven.rest.client.HRavenRestClient.java

public String getCluster(String hostname) throws IOException {
    String urlString = String.format("http://%s/api/v1/getCluster?hostname=%s", apiHostname,
            StringUtil.cleanseToken(hostname));

    if (LOG.isInfoEnabled()) {
        LOG.info("Requesting cluster for " + hostname);
    }//from   w  w  w  . j a  v  a 2 s  . c om
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(this.connectTimeout);
    connection.setReadTimeout(this.readTimeout);
    InputStream input = connection.getInputStream();
    java.util.Scanner s = new java.util.Scanner(input).useDelimiter("\\A");
    String cluster = s.hasNext() ? s.next() : "";
    try {
        input.close();
    } catch (IOException ioe) {
        LOG.error("IOException in closing input stream, returning no error " + ioe.getMessage());
    }
    return cluster;
}

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

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

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

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

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

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

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

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

From source file:game.Clue.JerseyClient.java

public void getAvailableSlot() {

    try {// w  ww.  ja  v  a2 s .co  m
        for (int i = 1; i < 7; i++) {
            // URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game/Status");
            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player"
                            + i + "/");
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //  while (in.readLine() != null) {
            //}
            System.out.println("\nGET Request for :" + "Get Available slot " + "Sent");

            if ((in.readLine()).contains("no name")) {
                game_slot = i;
                i = 7;
            } else {

            }
            System.out.print("You have slot # " + game_slot);
            //close connection
            in.close();
        }

    } catch (Exception e) {
        System.out.println("\nError slot taken..Checking for another open slot...");
        System.out.println(e);

    }

}

From source file:au.com.wallaceit.reddinator.Rservice.java

private Bitmap loadImage(String urlstr) {
    URL url;/*from  www .j av  a 2  s . c o m*/
    Bitmap bmp;
    try {
        url = new URL(urlstr);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(8000);
        con.setReadTimeout(8000);
        bmp = BitmapFactory.decodeStream(con.getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return bmp;
}

From source file:game.Clue.JerseyClient.java

public JerseyClient() {

    String string = "";

    try {//from  w w w. j  a  va 2s. co  m
        //System.out.println("jerseyclient started");
        currentgame_state = new JSONObject(
                "{\"players\":[{\"position\":\"0,3\",\"name\":null,\"active\":\"true\",\"cards\":\"MR GREEN,CANDLESTICK,BALLROOM\",\"character\":\"scarlet\"},{\"position\":\"1,4\",\"name\":null,\"active\":\"true\",\"cards\":\"PROFESSOR PLUM,BILLARD ROOM,ROPE\",\"character\":\"mustard\"},{\"position\":\"4,3\",\"name\":null,\"active\":\"true\",\"cards\":\"DINING ROOM,REVOLVER,WRENCH\",\"character\":\"white\"},{\"position\":\"4,1\",\"name\":null,\"active\":\"true\",\"cards\":\"LIBRARY,COLONEL MUSTARD,STUDY\",\"character\":\"green\"},{\"position\":\"3,0\",\"name\":null,\"active\":\"true\",\"cards\":\"MISS SCARLET,MRS PEACOCK,KNIFE\",\"character\":\"peacock\"},{\"position\":\"1,0\",\"name\":null,\"active\":\"true\",\"cards\":\"HALL,CONSERVATORY,LOUNGE\",\"character\":\"plum\"}],\"move_state\":{\"player\":\"scarlet\",\"moves\":[[\"[0,4], [0,2]\",\"accusation\"]]},\"winner\":null}\"))");

        String username = "Mario";
        // Step1: Let's 1st read file from fileSystem
        InputStream crunchifyInputStream = new FileInputStream(
                "/Users/" + username + "/Documents/JsonTest/JSONFile.txt");
        InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream);
        BufferedReader br = new BufferedReader(crunchifyReader);
        String line;
        while ((line = br.readLine()) != null) {
            string += line + "\n";
        }

        JSONObject jsonObject = new JSONObject(string);
        //System.out.println(jsonObject);

        // Step2: Now get JSON File Data from REST Service
        try {

            JsonParser Parser;
            //URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game");
            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game");
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //  while (in.readLine() != null) {
            //}
            System.out.print(in.readLine());
            System.out.println("\nREST Service Invoked Successfully..GET Request Sent");
            //getGameState();

            // sendPUT(ClueGameUI.jTextField2.getText());
            //send JSON to Parser
            //Parser=new JsonParser(in.readLine());
            //System.out.println("Parser called");
            // sendPUT();
            //close connection
            in.close();

        } catch (Exception e) {
            System.out.println("\nError while calling REST Service");
            System.out.println(e);
        }

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

From source file:com.baidu.jprotobuf.rpc.client.SimpleHttpRequestExecutor.java

/**
 * Open an HttpURLConnection for the given remote invocation request.
 * @param config the HTTP invoker configuration that specifies the
 * target service//from  w ww . j av  a  2 s .c om
 * @return the HttpURLConnection for the given request
 * @throws IOException if thrown by I/O methods
 * @see java.net.URL#openConnection()
 */
protected HttpURLConnection openConnection(IDLHttpClientInvoker invoker) throws IOException {
    URLConnection con = new URL(invoker.getServiceUrl()).openConnection();
    if (!(con instanceof HttpURLConnection)) {
        throw new IOException("Service URL [" + invoker.getServiceUrl() + "] is not an HTTP URL");
    }

    if (invoker.getConnectTimeout() > 0) {
        con.setConnectTimeout(invoker.getConnectTimeout());
    }

    if (invoker.getReadTimeout() > 0) {
        con.setReadTimeout(invoker.getReadTimeout());
    }

    return (HttpURLConnection) con;
}

From source file:com.net.h1karo.sharecontrol.ShareControl.java

public void updateCheck() {
    String CBuildString = "", NBuildString = "";

    int CMajor = 0, CMinor = 0, CMaintenance = 0, CBuild = 0, NMajor = 0, NMinor = 0, NMaintenance = 0,
            NBuild = 0;//from   w  w w.  j a  v  a  2 s  .  com

    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=90354");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "ShareControl Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.getLogger().warning("No files found, or Feed URL is bad.");
            result = UpdateResult.ERROR;
            return;
        }
        String newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name"));
        newVersion = newVersionTitle.replace("ShareControl v", "").trim();

        /**\\**/
        /**\\**//**\\**/
        /**\    GET VERSIONS    /**\
          /**\\**/
        /**\\**//**\\**/

        String[] CStrings = currentVersion.split(Pattern.quote("."));

        CMajor = Integer.parseInt(CStrings[0]);
        if (CStrings.length > 1)
            if (CStrings[1].contains("-")) {
                CMinor = Integer.parseInt(CStrings[1].split(Pattern.quote("-"))[0]);
                CBuildString = CStrings[1].split(Pattern.quote("-"))[1];
                if (CBuildString.contains("b")) {
                    beta = true;
                    CBuildString = CBuildString.replace("b", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 1;
                } else if (CBuildString.contains("a")) {
                    alpha = true;
                    CBuildString = CBuildString.replace("a", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 10;
                } else
                    CBuild = Integer.parseInt(CBuildString);
            } else {
                CMinor = Integer.parseInt(CStrings[1]);
                if (CStrings.length > 2)
                    if (CStrings[2].contains("-")) {
                        CMaintenance = Integer.parseInt(CStrings[2].split(Pattern.quote("-"))[0]);
                        CBuildString = CStrings[2].split(Pattern.quote("-"))[1];
                        if (CBuildString.contains("b")) {
                            beta = true;
                            CBuildString = CBuildString.replace("b", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 1;
                        } else if (CBuildString.contains("a")) {
                            alpha = true;
                            CBuildString = CBuildString.replace("a", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 10;
                        } else
                            CBuild = Integer.parseInt(CBuildString);
                    } else
                        CMaintenance = Integer.parseInt(CStrings[2]);
            }

        String[] NStrings = newVersion.split(Pattern.quote("."));

        NMajor = Integer.parseInt(NStrings[0]);
        if (NStrings.length > 1)
            if (NStrings[1].contains("-")) {
                NMinor = Integer.parseInt(NStrings[1].split(Pattern.quote("-"))[0]);
                NBuildString = NStrings[1].split(Pattern.quote("-"))[1];
                if (NBuildString.contains("b")) {
                    beta = true;
                    NBuildString = NBuildString.replace("b", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 1;
                } else if (NBuildString.contains("a")) {
                    alpha = true;
                    NBuildString = NBuildString.replace("a", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 10;
                } else
                    NBuild = Integer.parseInt(NBuildString);
            } else {
                NMinor = Integer.parseInt(NStrings[1]);
                if (NStrings.length > 2)
                    if (NStrings[2].contains("-")) {
                        NMaintenance = Integer.parseInt(NStrings[2].split(Pattern.quote("-"))[0]);
                        NBuildString = NStrings[2].split(Pattern.quote("-"))[1];
                        if (NBuildString.contains("b")) {
                            beta = true;
                            NBuildString = NBuildString.replace("b", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 1;
                        } else if (NBuildString.contains("a")) {
                            alpha = true;
                            NBuildString = NBuildString.replace("a", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 10;
                        } else
                            NBuild = Integer.parseInt(NBuildString);
                    } else
                        NMaintenance = Integer.parseInt(NStrings[2]);
            }

        /**\\**/
        /**\\**//**\\**/
        /**\   CHECK VERSIONS   /**\
          /**\\**/
        /**\\**//**\\**/
        if ((CMajor < NMajor) || (CMajor == NMajor && CMinor < NMinor)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance < NMaintenance)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance == NMaintenance && CBuild < NBuild))
            result = UpdateResult.UPDATE_AVAILABLE;
        else
            result = UpdateResult.NO_UPDATE;
        return;
    } catch (Exception e) {
        console.sendMessage(" There was an issue attempting to check for the latest version.");
    }
    result = UpdateResult.ERROR;
}

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

private void setReadTimeout(int timeout, URLConnection connection) {
    if (getTimeout(timeout) != NO_TIMEOUT) {
        connection.setReadTimeout(getTimeout(timeout));
    }//  www.j  ava  2  s.  c  o  m
}

From source file:edu.ucuenca.authorsrelatedness.Distance.java

public synchronized String Http(String s) throws SQLException, IOException {

    String get = Cache.getInstance().get(s);
    String resp = "";
    if (get != null) {
        //System.out.print(".");
        resp = get;/*from  w w  w. j a  va  2  s.c o m*/
    } else {
        final URL url = new URL(s);
        final URLConnection connection = url.openConnection();
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
        connection.addRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

        Cache.getInstance().put(s, resp);
    }

    return resp;
}