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.pa165.ddtroops.console.client.Application.java

/**
 * Create new role in database//from  w ww  .j  ava 2 s  . c  o m
 * @param name  role id
 * @param description   role desc
 * @param energy    role energy
 * @param attack    role attack
 * @param defense   role defense
 */
private static void createRole(String name, String description, String energy, String attack, String defense) {
    try {
        RoleDTO r = new RoleDTO();
        r.setName(name);
        r.setDescription(description);
        r.setEnergy(Integer.parseInt(energy));
        r.setAttack(Integer.parseInt(attack));
        r.setDefense(Integer.parseInt(defense));
        JSONObject jsonObject = new JSONObject(r);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/post");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

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

        while (in.readLine() != null) {
        }
        System.out.println("New role " + r.getName() + " was created.");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when creating new role");
        System.out.println(e);
    }
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Update role in database/*from  w w  w  .j ava  2s .  c  o  m*/
 * @param id    role id
 * @param name  role name
 * @param description   role desc
 * @param energy    role energy
 * @param attack    role attack
 * @param defense   role defense
 */
private static void updateRole(String id, String name, String description, String energy, String attack,
        String defense) {
    try {
        RoleDTO r = new RoleDTO();
        r.setId(Long.parseLong(id));
        r.setName(name);
        r.setDescription(description);
        r.setEnergy(Integer.parseInt(energy));
        r.setAttack(Integer.parseInt(attack));
        r.setDefense(Integer.parseInt(defense));
        JSONObject jsonObject = new JSONObject(r);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/put");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Updated role with id: " + r.getId());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when updating role");
        System.out.println(e);
    }
}

From source file:org.y20k.transistor.helpers.MetadataHelper.java

public static void prepareMetadata(final String mStreamUri, final Station mStation, final Context mContext)
        throws IOException {
    metaDataThread = new Thread(new Runnable() {

        @Override/*from  www  .  j av  a2 s  .  c  o m*/
        public void run() {
            try {
                URLConnection connection = new URL(mStreamUri).openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestProperty("Icy-MetaData", "1");
                connection.connect();

                InputStream in = connection.getInputStream();

                byte buf[] = new byte[16384]; // one second of 128kbit stream
                int count = 0;
                int total = 0;
                int metadataSize = 0;
                final int metadataOffset = connection.getHeaderFieldInt("icy-metaint", 0);
                int bitRate = Math.max(connection.getHeaderFieldInt("icy-br", 128), 32);
                LogHelper.v(LOG_TAG, "createProxyConnection: connected, icy-metaint " + metadataOffset
                        + " icy-br " + bitRate);
                Thread thisThread = Thread.currentThread();
                int thisThreadCounter = 0;
                while (true && metaDataThread == thisThread) {
                    if (thisThreadCounter > 20) { //only try 20 times and terminate thread to be sure getting metadata
                        LogHelper.v(LOG_TAG,
                                "thisThreadCounter: Upper Break at thisThreadCounter=" + thisThreadCounter);
                        break;
                    }
                    thisThreadCounter++;
                    count = Math.min(in.available(), buf.length);
                    if (count <= 0) {
                        count = Math.min(bitRate * 64, buf.length); // buffer half-second of stream data
                    }
                    if (metadataOffset > 0) {
                        count = Math.min(count, metadataOffset - total);
                    }

                    count = in.read(buf, 0, count);
                    if (count == 0) {
                        continue;
                    }
                    if (count < 0) {
                        LogHelper.v(LOG_TAG, "thisThreadCounter: Break at -count < 0- thisThreadCounter="
                                + thisThreadCounter);
                        break;
                    }
                    total += count;
                    if (metadataOffset > 0 && total >= metadataOffset) {
                        // read metadata
                        total = 0;
                        count = in.read();
                        if (count < 0) {
                            LogHelper.v(LOG_TAG, "thisThreadCounter: Break2 at -count < 0- thisThreadCounter="
                                    + thisThreadCounter);
                            break;
                        }
                        count *= 16;
                        metadataSize = count;
                        if (metadataSize == 0) {
                            continue;
                        }
                        // maximum metadata length is 4080 bytes
                        total = 0;
                        while (total < metadataSize) {
                            count = in.read(buf, total, count);
                            if (count < 0) {
                                LogHelper.v(LOG_TAG,
                                        "thisThreadCounter: Break3 at -count < 0- thisThreadCounter="
                                                + thisThreadCounter);
                                break;
                            }
                            if (count == 0) {
                                continue;
                            }
                            total += count;
                            count = metadataSize - total;
                        }
                        total = 0;
                        String[] metadata = new String(buf, 0, metadataSize, StandardCharsets.UTF_8).split(";");
                        for (String s : metadata) {
                            if (s.indexOf(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER) == 0 && s
                                    .length() >= TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length() + 1) {
                                //handleMetadataString(s.substring(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1));
                                String metadata2 = s.substring(
                                        TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1);
                                if (metadata2 != null && metadata2.length() > 0) {
                                    // send local broadcast
                                    Intent i = new Intent();
                                    i.setAction(TransistorKeys.ACTION_METADATA_CHANGED);
                                    i.putExtra(TransistorKeys.EXTRA_METADATA, metadata2);
                                    i.putExtra(TransistorKeys.EXTRA_STATION, mStation);
                                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(i);

                                    // save metadata to shared preferences
                                    SharedPreferences settings = PreferenceManager
                                            .getDefaultSharedPreferences(mContext);
                                    SharedPreferences.Editor editor = settings.edit();
                                    editor.putString(TransistorKeys.PREF_STATION_METADATA, metadata2);
                                    editor.apply();

                                    //done getting the metadata
                                    LogHelper.v(LOG_TAG, "thisThreadCounter: Lower Break at thisThreadCounter="
                                            + thisThreadCounter);
                                    break;
                                }
                                // break;
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                LogHelper.e(LOG_TAG, e.getMessage());
            }
        }

    });
    metaDataThread.start();
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Fetches the master metadata.json file on a given repository and returns the
 * data as a JSONObject.//from  www.  ja  v a 2  s. c om
 */
private static JSONObject downloadMetadata(String repo) throws SQLException {
    if (repo == null)
        return null;

    try {
        // Grab master metadata.json
        URL u = new URL(repo + "/metadata.json");
        URLConnection uc = u.openConnection();
        uc.setConnectTimeout(1000); // generous max-of-1-second to connect
        uc.setReadTimeout(1000);
        uc.connect();
        InputStreamReader in = new InputStreamReader(uc.getInputStream());
        BufferedReader buff = new BufferedReader(in);
        StringBuffer sb = new StringBuffer();
        String line = null;
        do {
            line = buff.readLine();
            if (line != null)
                sb.append(line);
        } while (line != null);
        String data = sb.toString();

        // Parse it
        JSONParser parser = new JSONParser();
        JSONObject ob = (JSONObject) parser.parse(data);
        return ob;

    } catch (SocketTimeoutException e) {
        throw new SQLException(URL_TIMEOUT);
    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL.");
    } catch (IOException e) {
        throw new SQLException(URL_TIMEOUT);
    } catch (ParseException e) {
        throw new SQLException("Could not parse data from URL.");
    }

}

From source file:net.pms.configuration.DownloadPlugins.java

public static ArrayList<DownloadPlugins> downloadList() {
    ArrayList<DownloadPlugins> res = new ArrayList<>();

    if (!configuration.getExternalNetwork()) {
        // Do not try to get the plugin list if there is no
        // external network.
        return res;
    }/*from www  .  j a va  2  s  .  co m*/

    try {
        URL u = new URL(PLUGIN_LIST_URL);
        URLConnection connection = u.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        parse_list(res, in, false);
        File test = new File(configuration.getPluginDirectory() + File.separator + PLUGIN_TEST_FILE);
        if (test.exists()) {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(test)));
            parse_list(res, in, true);
        }
    } catch (IOException e) {
    }
    return res;
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

/**
 * download file url and save it//from   ww  w. ja  v  a  2  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(
                Statics.moduleCachePath + File.separator + com.appbuilder.sdk.android.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:com.viettel.dms.download.DownloadFile.java

/**
 * Download file with urlConnection/*from   w  w  w . j ava2s. c  o  m*/
 * @author : BangHN
 * since : 1.0
 */
public static void downloadWithURLConnection(String url, File output, File tmpDir) {
    BufferedOutputStream os = null;
    BufferedInputStream is = null;
    File tmp = null;
    try {
        VTLog.i("Download ZIPFile", "Downloading url :" + url);

        tmp = File.createTempFile("download", ".tmp", tmpDir);
        URL urlDownload = new URL(url);
        URLConnection cn = urlDownload.openConnection();
        cn.addRequestProperty("session", HTTPClient.sessionID);
        cn.setConnectTimeout(CONNECT_TIMEOUT);
        cn.setReadTimeout(READ_TIMEOUT);
        cn.connect();
        is = new BufferedInputStream(cn.getInputStream());
        os = new BufferedOutputStream(new FileOutputStream(tmp));
        //cp nht dung lng tp tin request
        fileSize = cn.getContentLength();
        //vn c tr?ng hp khng c ContentLength
        if (fileSize < 0) {
            //mc nh = 4 MB
            fileSize = 4 * 1024 * 1024;
        }
        copyStream(is, os);
        tmp.renameTo(output);
        tmp = null;
    } catch (IOException e) {
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        throw new RuntimeException(e);
    } catch (Exception e) {
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        throw new RuntimeException(e);
    } finally {
        if (tmp != null) {
            try {
                tmp.delete();
                tmp = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (is != null) {
            try {
                is.close();
                is = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (os != null) {
            try {
                os.close();
                os = null;
            } catch (Exception ignore) {
                ;
            }
        }
    }
}

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

public static <T extends RestObject> T getRestObject(Class<T> restObject, String url)
        throws RestfulAPIException {
    InputStream stream = null;//from   ww w .  j av a2 s . c o  m
    try {
        URLConnection conn = new URL(url).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();
        T result = mapper.readValue(stream, restObject);
        if (result.hasError()) {
            throw new RestfulAPIException("Error in json response: " + result.getError());
        }

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

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * //from  w  w  w  . ja  v  a  2 s  . c om
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private 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:mas.MAS_TOP_PAPERS.java

/**
 * @param args the command line arguments
 *//*from ww w.jav  a  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_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}