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:org.jgrades.monitor.restart.SystemStateServiceImpl.java

@Override
public String restartApplication() {
    try {//from  w  w  w  .  jav  a  2 s  .  co  m
        URL url = new URL(buildAddress());
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(restartTimeout);
        setAuthProperty(conn);
        return IOUtils.toString(conn.getInputStream());
    } catch (IOException e) {
        LOGGER.debug("Problem during restarting tomcat", e);
        return e.getMessage();
    }
}

From source file:se.blinfo.session.client.SessionClient.java

private String call(String path) {
    URL sessionServiceUrl;/*from  w  w w  . j a  v a 2 s.  c  om*/
    try {
        sessionServiceUrl = new URL(baseUrl + path);
        URLConnection yc;
        try {
            yc = sessionServiceUrl.openConnection();
            yc.setConnectTimeout(5 * 1000); //5 sekunder
            yc.setReadTimeout(5 * 1000);
            yc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String response = in.readLine();
            in.close();
            return response;
        } catch (IOException ex) {
            Logger.getLogger(SessionClient.class.getName()).log(Level.SEVERE, "Kunde inte hmta data", ex);
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(SessionClient.class.getName()).log(Level.SEVERE, "Ogiltig url", ex);
    }
    return "";
}

From source file:org.apache.htrace.util.TestHTracedProcess.java

private String doGet(final URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(TIMEOUT);
    connection.setReadTimeout(TIMEOUT);
    connection.connect();//from   ww  w.  j a v  a 2s .  c o m
    StringBuffer sb = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    try {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            sb.append(line);
        }
    } finally {
        reader.close();
    }
    return sb.toString();
}

From source file:org.geoserver.wps.spatialstatistics.ppio.GridCoverageURLPPIO.java

@Override
public Object decode(String input) throws Exception {
    WPSInfo wps = geoServer.getService(WPSInfo.class);

    URL url = new URL(input);
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout((int) wps.getConnectionTimeout());
    conn.setReadTimeout((int) wps.getConnectionTimeout());

    return decode(conn.getInputStream());
}

From source file:edu.kit.dama.ui.simon.impl.WebServerProbe.java

@Override
public boolean checkProbe() {
    try {//from  w w  w  .j a v a 2 s .  co  m
        URLConnection con = serverUrl.openConnection();
        con.setConnectTimeout(timeout);
        con.connect();
        String header0 = con.getHeaderField(0);
        return header0 != null && header0.endsWith("200 OK");
    } catch (IOException ex) {
        LOGGER.error("Failed to check Web server probe", ex);
    }
    return false;
}

From source file:emily.command.fun.JokeCommand.java

private String getJokeFromWeb(String username) {
    try {/*  w ww .  java2  s .  co m*/
        URL loginurl = new URL("http://api.icndb.com/jokes/random?firstName=&lastName=" + username);
        URLConnection yc = loginurl.openConnection();
        yc.setConnectTimeout(10 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine = in.readLine();
        JsonParser parser = new JsonParser();
        JsonObject array = parser.parse(inputLine).getAsJsonObject();
        return array.get("value").getAsJsonObject().get("joke").getAsString();
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

From source file:RandomOrgSeededRandomGenerator.java

/**
 * Construct a new random.org seeded random generator.
 * /*from  w ww  .  ja  va  2 s .  com*/
 */
private RandomOrgSeededRandomGenerator() {

    try {
        final URL url = new URL(
                "http://www.random.org/strings/?num=10&len=10&digits=on&unique=on&format=plain&rnd=new");
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        final StringBuilder stringBuilder = new StringBuilder();

        String line;
        while ((line = in.readLine()) != null) {
            stringBuilder.append(line);
        }

        in.close();

        final byte[] seed = stringBuilder.toString().getBytes();

        random = new SecureRandom(seed);
    } catch (final MalformedURLException e) {
        //logger.info("Default secure random is used.");
        random = new SecureRandom();
    } catch (final IOException e) {
        //logger.info("Default secure random is used.");
        random = new SecureRandom();
    }
}

From source file:org.xwiki.rendering.internal.macro.rss.DefaultRomeFeedFactory.java

/**
 * {@inheritDoc}/*from   ww w .ja  v  a  2s .c o  m*/
 * @see RomeFeedFactory#createFeed(org.xwiki.rendering.macro.rss.RssMacroParameters)
 */
public SyndFeed createFeed(RssMacroParameters parameters) throws MacroExecutionException {
    if (StringUtils.isEmpty(parameters.getFeed())) {
        throw new MacroExecutionException("The required 'feed' parameter is missing");
    }

    SyndFeedInput syndFeedInput = new SyndFeedInput();

    SyndFeed feed;
    try {
        URLConnection connection = parameters.getFeedURL().openConnection();
        connection.setConnectTimeout(TIMEOUT_MILLISECONDS);
        feed = syndFeedInput.build(new XmlReader(connection));
    } catch (SocketTimeoutException ex) {
        throw new MacroExecutionException(
                MessageFormat.format("Connection timeout when trying to reach [{0}]", parameters.getFeedURL()));
    } catch (Exception ex) {
        throw new MacroExecutionException(
                MessageFormat.format("Error processing [{0}] : {1}", parameters.getFeedURL(), ex.getMessage()),
                ex);
    }
    if (feed == null) {
        throw new MacroExecutionException(
                MessageFormat.format("No feed found at [{0}]", parameters.getFeedURL()));
    }

    return feed;
}

From source file:com.zoffcc.applications.aagtl.ImageManager.java

public void DownloadFromUrl(String imageURL, String fileName) { // this is
                                                                // the downloader method
    try {//  w  ww  . j a  v  a2 s .  com
        URL url = new URL(imageURL);
        File file = new File(fileName);

        //long startTime = System.currentTimeMillis();
        //Log.d("ImageManager", "download begining");
        //Log.d("ImageManager", "download url:" + url);
        //Log.d("ImageManager", "downloaded file name:" + fileName);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(10000);
        ucon.setReadTimeout(7000);

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is, HTMLDownloader.large_buffer_size);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(HTMLDownloader.default_buffer_size);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
        //Log.d("ImageManager", "download ready in"
        //      + ((System.currentTimeMillis() - startTime) / 1000)
        //      + " sec");

    } catch (SocketTimeoutException e2) {
        Log.d("ImageManager", "Connectiont timout: " + e2);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e);
    }

}

From source file:com.enonic.cms.core.http.HTTPService.java

private URLConnection setUpConnection(String address, int timeoutMs, int readTimeoutMs) throws IOException {
    URL url = new URL(address);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(timeoutMs > 0 ? timeoutMs : DEFAULT_CONNECTION_TIMEOUT);
    urlConn.setReadTimeout(readTimeoutMs > 0 ? readTimeoutMs : DEFAULT_READ_TIMEOUT);
    urlConn.setRequestProperty("User-Agent", userAgent);
    String userInfo = url.getUserInfo();
    if (StringUtils.isNotBlank(userInfo)) {
        String userInfoBase64Encoded = new String(Base64.encodeBase64(userInfo.getBytes()));
        urlConn.setRequestProperty("Authorization", "Basic " + userInfoBase64Encoded);
    }/*from   w  ww.  ja va2s  .c  o m*/
    return urlConn;

}