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.eclipse.kura.core.deployment.download.impl.HttpDownloadCountingOutputStream.java

@Override
public void startWork() throws KuraException {

    this.executor = Executors.newSingleThreadExecutor();

    this.future = this.executor.submit(new Callable<Void>() {

        @Override//from ww w. j av a 2 s. c o  m
        public Void call() throws Exception {
            URL localUrl = null;
            boolean shouldAuthenticate = false;
            try {
                shouldAuthenticate = HttpDownloadCountingOutputStream.this.options.getUsername() != null
                        && HttpDownloadCountingOutputStream.this.options.getPassword() != null
                        && !(HttpDownloadCountingOutputStream.this.options.getUsername().trim().isEmpty()
                                && !HttpDownloadCountingOutputStream.this.options.getPassword().trim()
                                        .isEmpty());

                if (shouldAuthenticate) {
                    Authenticator.setDefault(new Authenticator() {

                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(
                                    HttpDownloadCountingOutputStream.this.options.getUsername(),
                                    HttpDownloadCountingOutputStream.this.options.getPassword().toCharArray());
                        }
                    });
                }

                localUrl = new URL(HttpDownloadCountingOutputStream.this.m_downloadURL);
                URLConnection urlConnection = localUrl.openConnection();
                int connectTimeout = getConnectTimeout();
                int readTimeout = getPropReadTimeout();
                urlConnection.setConnectTimeout(connectTimeout);
                urlConnection.setReadTimeout(readTimeout);

                testConnectionProtocol(urlConnection);

                HttpDownloadCountingOutputStream.this.is = localUrl.openStream();

                String s = urlConnection.getHeaderField("Content-Length");
                s_logger.info("Content-lenght: " + s);

                setTotalBytes(s != null ? Integer.parseInt(s) : -1);
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), 0,
                        HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.IN_PROGRESS, null);

                int bufferSize = getBufferSize();

                if (bufferSize == 0 && getTotalBytes() > 0) {
                    int newSize = Math.round(HttpDownloadCountingOutputStream.this.totalBytes / 100 * 1);
                    bufferSize = newSize;
                    setBufferSize(newSize);
                } else if (bufferSize == 0) {
                    int newSize = 1024 * 4;
                    bufferSize = newSize;
                    setBufferSize(newSize);
                }

                long numBytes = IOUtils.copyLarge(HttpDownloadCountingOutputStream.this.is,
                        HttpDownloadCountingOutputStream.this, new byte[bufferSize]);
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), numBytes,
                        HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.COMPLETED, null);

            } catch (IOException e) {
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), getByteCount(),
                        HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.FAILED,
                        e.getMessage());
                throw new KuraConnectException(e);
            } finally {
                if (HttpDownloadCountingOutputStream.this.is != null) {
                    try {
                        HttpDownloadCountingOutputStream.this.is.close();
                    } catch (IOException e) {
                    }
                }
                try {
                    close();
                } catch (IOException e) {
                }
                localUrl = null;
                if (shouldAuthenticate) {
                    Authenticator.setDefault(null);
                }
            }

            return null;
        }

    });

    try {
        this.future.get();
    } catch (ExecutionException ex) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex);
    } catch (InterruptedException ex) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex);
    }
}

From source file:eagle.jobrunning.crawler.RMResourceFetcher.java

private List<Object> doFetchRunningJobConfiguration(String appID) throws Exception {
    InputStream is = null;//  w w w  .  j a  v  a  2  s  . c  o m
    try {
        checkUrl();
        String jobID = JobUtils.getJobIDByAppID(appID);
        String urlString = jobRunningConfigServiceURLBuilder.build(selector.getSelectedUrl(), jobID);
        LOG.info("Going to fetch job completed information for " + jobID + " , url: " + urlString);
        final URLConnection connection = URLConnectionUtils.getConnection(urlString);
        connection.setRequestProperty(XML_HTTP_HEADER, XML_FORMAT);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        is = connection.getInputStream();
        Map<String, String> configs = XmlHelper.getConfigs(is);
        return Arrays.asList((Object) configs);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.romeikat.datamessie.core.base.service.download.AbstractDownloader.java

protected URLConnection getConnection(final String url) throws IOException {
    final URLConnection urlConnection = new URL(url).openConnection();
    if (urlConnection instanceof HttpURLConnection) {
        final HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        httpUrlConnection.setInstanceFollowRedirects(true);
    }//from w w  w .j  a  v  a2 s  .com
    urlConnection.setConnectTimeout(timeout);
    urlConnection.setReadTimeout(timeout);
    urlConnection.setRequestProperty("User-Agent", userAgent);
    return urlConnection;
}

From source file:org.apache.eagle.security.hive.jobrunning.HiveJobFetchSpout.java

private boolean fetchRunningConfig(AppInfo appInfo, List<MRJob> mrJobs) {
    InputStream is = null;/*w w w. j ava 2  s. co m*/
    for (MRJob mrJob : mrJobs) {
        String confURL = appInfo.getTrackingUrl() + Constants.MR_JOBS_URL + "/" + mrJob.getId() + "/"
                + Constants.MR_CONF_URL + "?" + Constants.ANONYMOUS_PARAMETER;
        try {
            LOG.info("fetch job conf from {}", confURL);
            final URLConnection connection = URLConnectionUtils.getConnection(confURL);
            connection.setRequestProperty(XML_HTTP_HEADER, XML_FORMAT);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            is = connection.getInputStream();
            Map<String, String> hiveQueryLog = new HashMap<>();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document dt = db.parse(is);
            Element element = dt.getDocumentElement();
            NodeList propertyList = element.getElementsByTagName("property");
            int length = propertyList.getLength();
            for (int i = 0; i < length; i++) {
                Node property = propertyList.item(i);
                String key = property.getChildNodes().item(0).getTextContent();
                String value = property.getChildNodes().item(1).getTextContent();
                hiveQueryLog.put(key, value);
            }

            if (hiveQueryLog.containsKey(Constants.HIVE_QUERY_STRING)) {
                collector.emit(new ValuesArray(appInfo.getUser(), mrJob.getId(),
                        Constants.ResourceType.JOB_CONFIGURATION, hiveQueryLog), mrJob.getId());
            }
        } catch (Exception e) {
            LOG.warn("fetch job conf from {} failed, {}", confURL, e);
            e.printStackTrace();
            return false;
        } finally {
            Utils.closeInputStream(is);
        }
    }
    return true;
}

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

private void shoutcastProxyReaderLoop(Socket proxy, URLConnection connection) throws IOException {

    connection.setConnectTimeout(5000);/*from   w w w  .  ja  va 2  s. c  o m*/
    connection.setReadTimeout(5000);
    connection.setRequestProperty("Icy-MetaData", "1");
    connection.connect();

    InputStream in = connection.getInputStream();

    OutputStream out = proxy.getOutputStream();
    out.write(("HTTP/1.0 200 OK\r\n" + "Pragma: no-cache\r\n" + "Content-Type: " + connection.getContentType()
            + "\r\n\r\n").getBytes(StandardCharsets.UTF_8));

    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);
    while (true) {
        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) {
            break;
        }

        out.write(buf, 0, count);

        total += count;
        if (metadataOffset > 0 && total >= metadataOffset) {
            // read metadata
            total = 0;
            count = in.read();
            if (count < 0) {
                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) {
                    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));
                    // break;
                }
            }
        }
    }
}

From source file:game.Clue.JerseyClient.java

public void sendPUT(String name) {
    System.out.println("SendPUT method called");
    try {//w  ww .  j  av a2 s . c o  m
        JSONObject jsonObject = new JSONObject("{name:" + name + "}");

        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/player1");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("PUT", "application/json");

        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

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

}

From source file:game.Clue.JerseyClient.java

public void sendPOST() {
    System.out.println("POST method called");
    try {//from   w  ww.  j a v  a 2 s .c  o  m

        JSONObject jsonObject = new JSONObject("{player:Brian}");
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("POST", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        System.out.println(jsonObject.toString());
        out.write("{" + jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

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

}

From source file:game.Clue.JerseyClient.java

public void isgameReady() {
    //Check to see if all players have joined game

    try {//from  ww w . ja va  2 s .co m
        // 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/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.println("\nGET Request for :" + "Game Ready Status?  " + "Sent");
        System.out.print(in.readLine());
        //close connection
        in.close();

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

    }

}

From source file:game.Clue.JerseyClient.java

public JSONObject getGameState() {

    JSONObject Object = null;/*from   w ww  .j  av  a  2  s .  c  om*/
    try {
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player1");
        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()));
        Object = new JSONObject(in.readLine());
        //;
        // JsonParser parser=new JsonParser(in.readLine());

        //  while (in.readLine() != null) {
        //}
        // System.out.print(in.readLine());
        System.out.println(Object.getJSONArray("players").getJSONObject(0).getString("character"));
        System.out.println("\nREST Service Invoked Successfully..GET Request Sent");

        //sendPUT();
        //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);
    }

    return Object;

}

From source file:game.Clue.JerseyClient.java

public void requestLogintoServer(String name) {

    try {//from  ww w  .j a  v  a 2  s .  c o  m
        for (int i = 0; i < 6; i++) {
            JSONObject jsonObject = new JSONObject(name);

            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.setDoOutput(true);
            //setDoOutput(true);
            connection.setRequestProperty("PUT", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(jsonObject.toString());

            System.out.println("Sent PUT message for logging into server");
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

}