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.mule.tck.util.WebServiceOnlineCheck.java

public static boolean isWebServiceOnline() {
    logger.debug("Verifying that the web service is on-line...");

    BufferedReader input = null;/*from  w w  w .  j  a v  a  2  s . c o m*/
    try {
        URLConnection conn = new URL(TEST_URL).openConnection();
        // setting these timeouts ensures the client does not deadlock indefinitely
        // when the server has problems.
        conn.setConnectTimeout(AbstractMuleContextTestCase.RECEIVE_TIMEOUT);
        conn.setReadTimeout(AbstractMuleContextTestCase.RECEIVE_TIMEOUT);
        InputStream in = conn.getInputStream();

        input = new BufferedReader(new InputStreamReader(in));

        String response = "";
        String line;
        while ((line = input.readLine()) != null) {
            response += line;
        }

        if (StringUtils.containsIgnoreCase(response, "Cisco")) {
            return true;
        } else {
            logger.warn("Unexpected response, web service does not seem to be on-line: \n" + response);
            return false;
        }
    } catch (Exception e) {
        logger.warn("Exception occurred, web service does not seem to be on-line: " + e);
        return false;
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.connectbot.util.UpdateHelper.java

/**
 * Read contents of a URL and return as a String. Handles any server
 * downtime with a 6-second timeout.// w  w  w  . j a  va2 s. c o  m
 */
private static String getUrl(String tryUrl, String userAgent) throws Exception {

    URL url = new URL(tryUrl);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(6000);
    connection.setReadTimeout(6000);
    connection.setRequestProperty("User-Agent", userAgent);
    connection.connect();

    InputStream is = connection.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    int bytesRead;
    byte[] buffer = new byte[1024];
    while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }

    os.flush();
    os.close();
    is.close();

    return new String(os.toByteArray());

}

From source file:org.sakaiproject.compilatio.util.CompilatioAPIUtil.java

public static Document callCompilatioReturnDocument(String apiURL, Map<String, String> parameters,
        String secretKey, final int timeout) throws TransientSubmissionException, SubmissionException {

    SOAPConnectionFactory soapConnectionFactory;
    Document xmlDocument = null;//  w w  w  .j a  v  a 2 s  .  c  o m
    try {
        soapConnectionFactory = SOAPConnectionFactory.newInstance();

        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyAction = soapBody.addChildElement(parameters.get("action"));
        parameters.remove("action");
        // api key
        SOAPElement soapBodyKey = soapBodyAction.addChildElement("key");
        soapBodyKey.addTextNode(secretKey);

        Set<Entry<String, String>> ets = parameters.entrySet();
        Iterator<Entry<String, String>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, String> param = it.next();
            SOAPElement soapBodyElement = soapBodyAction.addChildElement(param.getKey());
            soapBodyElement.addTextNode(param.getValue());
        }

        URL endpoint = new URL(null, apiURL, new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL url) throws IOException {
                URL target = new URL(url.toString());
                URLConnection connection = target.openConnection();
                // Connection settings
                connection.setConnectTimeout(timeout);
                connection.setReadTimeout(timeout);
                return (connection);
            }
        });

        SOAPMessage soapResponse = soapConnection.call(soapMessage, endpoint);

        // loading the XML document
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapResponse.writeTo(out);
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        builderfactory.setNamespaceAware(true);

        DocumentBuilder builder = builderfactory.newDocumentBuilder();
        xmlDocument = builder.parse(new InputSource(new StringReader(out.toString())));
        soapConnection.close();

    } catch (UnsupportedOperationException | SOAPException | IOException | ParserConfigurationException
            | SAXException e) {
        log.error(e);
    }
    return xmlDocument;

}

From source file:org.opencastproject.rest.RestServiceTestEnv.java

/**
 * Return a localhost base URL with a random port between 8081 and 9000.
 * The method features a port usage detection to ensure it returns a free port.
 *///  ww  w. j av  a2 s  .  c om
public static URL localhostRandomPort() {
    for (int tries = 100; tries > 0; tries--) {
        final URL url = UrlSupport.url("http", "localhost",
                8081 + new Random(System.currentTimeMillis()).nextInt(919));
        InputStream in = null;
        try {
            final URLConnection con = url.openConnection();
            con.setConnectTimeout(1000);
            con.setReadTimeout(1000);
            con.getInputStream();
        } catch (IOException e) {
            IoSupport.closeQuietly(in);
            return url;
        }
    }
    throw new RuntimeException("Cannot find free port. Giving up.");
}

From source file:org.apache.atlas.security.SecureClientUtils.java

private static void setTimeouts(URLConnection connection, int socketTimeout) {
    connection.setConnectTimeout(socketTimeout);
    connection.setReadTimeout(socketTimeout);
}

From source file:org.sakaiproject.contentreview.compilatio.util.CompilatioAPIUtil.java

public static Document callCompilatioReturnDocument(String apiURL, Map<String, String> parameters,
        String secretKey, final int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {

    SOAPConnectionFactory soapConnectionFactory;
    Document xmlDocument = null;/*from   w ww .  ja v a 2  s.c  o  m*/
    try {
        soapConnectionFactory = SOAPConnectionFactory.newInstance();

        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyAction = soapBody.addChildElement(parameters.get("action"));
        parameters.remove("action");
        // api key
        SOAPElement soapBodyKey = soapBodyAction.addChildElement("key");
        soapBodyKey.addTextNode(secretKey);

        Set<Entry<String, String>> ets = parameters.entrySet();
        Iterator<Entry<String, String>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, String> param = it.next();
            SOAPElement soapBodyElement = soapBodyAction.addChildElement(param.getKey());
            soapBodyElement.addTextNode(param.getValue());
        }

        URL endpoint = new URL(null, apiURL, new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL url) throws IOException {
                URL target = new URL(url.toString());
                URLConnection connection = target.openConnection();
                // Connection settings
                connection.setConnectTimeout(timeout);
                connection.setReadTimeout(timeout);
                return (connection);
            }
        });

        SOAPMessage soapResponse = soapConnection.call(soapMessage, endpoint);

        // loading the XML document
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapResponse.writeTo(out);
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        builderfactory.setNamespaceAware(true);

        DocumentBuilder builder = builderfactory.newDocumentBuilder();
        xmlDocument = builder.parse(new InputSource(new StringReader(out.toString())));
        soapConnection.close();

    } catch (UnsupportedOperationException | SOAPException | IOException | ParserConfigurationException
            | SAXException e) {
        log.error(e);
    }
    return xmlDocument;

}

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static SmartPhoneStatus remove(PhotoSerie ps) throws IOException {

    lastStatus = SmartPhoneStatus.TRYING;
    URL url;// w w  w  .j av  a  2s  .com
    String retval;
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/" + WebService.WebCommands.removejob
                + "/?" + WebService.WebParameters.jobid + "=" + ps.getId());
        System.out.println("Trying " + url.toString());
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), System.out);

    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);
        return SmartPhoneStatus.ERROR;

    }
    return SmartPhoneStatus.CONNECTED;
}

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static SmartPhoneStatus update(PhotoSerie ps) throws IOException {
    URL url;//from   ww w.  j a  v a 2s .c  om
    String retval;
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/"
                + WebService.WebCommands.updateTriggered + "/?" + WebService.WebParameters.jobid + "="
                + ps.getId() + "&" + WebService.WebParameters.receivedImages + "=" + ps.getReceived());
        lastStatus = SmartPhoneStatus.TRYING;
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), System.out);

    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);

        return SmartPhoneStatus.ERROR;

    }

    lastStatus = SmartPhoneStatus.CONNECTED;
    return SmartPhoneStatus.CONNECTED;
}

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static String getFromSmartPhone(WebService.WebCommands command, boolean doCheck) throws IOException {
    String retval;//  w w  w .j a va 2s  .c  o  m
    SmartPhoneStatus status = SmartPhoneStatus.TRYING;

    lastStatus = SmartPhoneStatus.TRYING;
    URL url;
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/" + command.name());
        System.out.println("Trying " + url.toString());
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), sw);
        retval = sw.toString();
        status = SmartPhoneStatus.CONNECTED;

        lastStatus = SmartPhoneStatus.CONNECTED;
    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);
        status = SmartPhoneStatus.ERROR;
        retval = SmartPhoneStatus.ERROR.name();

        lastStatus = SmartPhoneStatus.ERROR;
    }

    return retval;
}

From source file:com.adrguides.utils.HTTPUtils.java

public static InputStream openAddress(Context context, URL url) throws IOException {
    if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) {
        return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15
    } else {/*from   w ww  .  ja  v  a 2 s . com*/
        URLConnection urlconn = url.openConnection();
        urlconn.setReadTimeout(10000 /* milliseconds */);
        urlconn.setConnectTimeout(15000 /* milliseconds */);
        urlconn.setAllowUserInteraction(false);
        urlconn.setDoInput(true);
        urlconn.setDoOutput(false);
        if (urlconn instanceof HttpURLConnection) {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responsecode = connection.getResponseCode();
            if (responsecode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Http response code returned:" + responsecode);
            }
        }
        return urlconn.getInputStream();
    }
}