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:de.indiplex.javapt.JavAPT.java

private String checkURL(String u) throws IOException {
    String s = null;//from w  w  w.ja va2s . c  o  m
    if (!u.endsWith("/")) {
        u = u + "/";
    }
    try {
        URLConnection conn = new URL(u + "Packages.bz2").openConnection();
        conn.setConnectTimeout(2000);
        conn.getInputStream().close();
        s = u;
    } catch (IOException ex) {
        URLConnection conn = new URL(u + "dists/stable/main/binary-iphoneos-arm/Packages.bz2").openConnection();
        conn.setConnectTimeout(12000);
        conn.getInputStream().close();
        s = u + "dists/stable/main/binary-iphoneos-arm";
    }
    if (s != null) {
        if (!s.endsWith("/")) {
            s = s + "/";
        }
    }
    return s;
}

From source file:org.mycore.media.MCRMediaViewSourceParser.java

/**
 * Helper method that connects to the given URL and returns the response as
 * a String//w w  w .j  a  v a 2  s .  co  m
 * 
 * @param url
 *            the URL to connect to
 * @return the response content as a String
 */
protected String getMetadata(String url) throws MCRPersistenceException {
    try {
        URLConnection connection = getConnection(url);
        connection.setConnectTimeout(getConnectTimeout());
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        forwardData(connection, out);

        return new String(out.toByteArray());
    } catch (IOException exc) {
        String msg = "Could not get metadata from Audio/Video Store URL: " + url;
        throw new MCRPersistenceException(msg, exc);
    }
}

From source file:de.static_interface.sinklibrary.Updater.java

private boolean isUpdateAvailable() {
    try {//from  w ww .j a va 2  s .c  om
        final URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);

        String version = SinkLibrary.getInstance().getVersion();

        conn.addRequestProperty("User-Agent", "SinkLibrary/v" + version + " (modified by Trojaner)");

        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) {
            SinkLibrary.getInstance().getLogger()
                    .warning("The updater could not find any files for the project id " + id);
            result = UpdateResult.FAIL_BADID;
            return false;
        }

        versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            SinkLibrary.getInstance().getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            SinkLibrary.getInstance().getLogger()
                    .warning("Please double-check your configuration to ensure it is correct.");
            result = UpdateResult.FAIL_APIKEY;
        } else {
            SinkLibrary.getInstance().getLogger()
                    .warning("The updater could not contact dev.bukkit.org for updating.");
            SinkLibrary.getInstance().getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:game.Clue.JerseyClient.java

public JerseyClient() {

    String string = "";

    try {//  w ww  .j a  v a 2  s .  c  o  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:au.com.wallaceit.reddinator.Rservice.java

private Bitmap loadImage(String urlstr) {
    URL url;//w  ww  .  jav a  2  s.  co  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:org.geoserver.wps.executor.SimpleInputProvider.java

/**
 * Executes/*from w  w w  .  j  av a  2  s.  co  m*/
 * 
 * @param ref
 * @return
 */
Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception {
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    try {
        if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(executor.getConnectionTimeout());
            params.setConnectionTimeout(executor.getConnectionTimeout());
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(executor.getConnectionTimeout());
                            conn.setReadTimeout(executor.getConnectionTimeout());
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                input = method.getResponseBodyAsStream();
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(executor.getConnectionTimeout());
            conn.setReadTimeout(executor.getConnectionTimeout());
            input = conn.getInputStream();
        }

        // actually parse teh data
        if (input != null) {
            return ppio.decode(input);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        // make sure to close the connection and streams no matter what
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

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 ww  w  .  ja v a  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;
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Asynchronously loads the given file// w  w w.j a  v a 2 s  .  c  om
 * @param url the URL to load
 * @param path the path to save the file to
 */
private Future<Path> asyncLoadFile(final String url, final Path path) {
    Callable<Path> job = () -> {
        long t0 = System.currentTimeMillis();

        // For the resulting file, drop the ".download" suffix
        String name = path.getFileName().toString();
        name = name.substring(0, name.length() - DOWNLOAD_SUFFIX.length());

        try {

            // Set up a few timeouts and fetch the attachment
            URLConnection con = new URL(url).openConnection();
            con.setConnectTimeout(60 * 1000); // 1 minute
            con.setReadTimeout(60 * 60 * 1000); // 1 hour

            if (!StringUtils.isEmpty(authHeader)) {
                con.setRequestProperty("Authorization", authHeader);
            }

            try (ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
                    FileOutputStream fos = new FileOutputStream(path.toFile())) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
            log.info(String.format("Copied %s -> %s in %d ms", url, path, System.currentTimeMillis() - t0));

        } catch (Exception e) {
            log.log(Level.SEVERE, "Failed downloading " + url + ": " + e.getMessage());

            // Delete the old file
            if (Files.exists(path)) {
                try {
                    Files.delete(path);
                } catch (IOException e1) {
                    log.finer("Failed deleting old file " + path);
                }
            }

            // Save an error file
            Path errorFile = path.getParent().resolve(name + ".err.txt");
            try (PrintStream err = new PrintStream(new FileOutputStream(errorFile.toFile()))) {
                e.printStackTrace(err);
            } catch (IOException ex) {
                log.finer("Failed generating error file " + errorFile);
            }
            return errorFile;
        }

        Path resultPath = path.getParent().resolve(name);
        try {
            Files.move(path, resultPath);
        } catch (IOException e) {
            log.log(Level.SEVERE, "Failed renaming path " + path + ": " + e.getMessage());
        }
        return resultPath;
    };

    log.info("Submitting new job: " + url);
    return processPool.submit(job);
}

From source file:org.xbmc.httpapi.Connection.java

/**
 * Create a new URLConnection with the request headers set, including authentication.
 *
 * @param url The request url/*from   w ww  . j av  a  2  s.  c  o  m*/
 * @return URLConnection
 * @throws IOException
 */
private URLConnection getUrlConnection(URL url) throws IOException {
    final URLConnection uc = url.openConnection();
    uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
    uc.setReadTimeout(mSocketReadTimeout);
    uc.setRequestProperty("Connection", "close");

    if (authEncoded != null) {
        uc.setRequestProperty("Authorization", "Basic " + authEncoded);
    }

    return uc;
}

From source file:at.gv.egiz.pdfas.lib.pki.impl.DefaultCertificateVerificationDataProvider.java

@Override
public CertificateVerificationData getCertificateVerificationData(
        java.security.cert.X509Certificate eeCertificate, ISettings settings)
        throws CertificateException, IOException {

    X509Certificate iaikEeCertificate = toIAIKX509Certificate(Objects.requireNonNull(eeCertificate));

    // @formatter:off
    final Set<java.security.cert.X509Certificate> certs = new LinkedHashSet<>(); // not thread-safe
    final List<byte[]> ocsps = new ArrayList<>(); // not thread-safe
    final Set<java.security.cert.X509CRL> crls = new LinkedHashSet<>(); // not thread-safe
    // @formatter:on

    StopWatch sw = new StopWatch();
    sw.start();//  ww  w  .  jav a2  s .c om

    if (log.isDebugEnabled()) {
        log.debug("Retrieving certificate validation info info for {}", iaikEeCertificate.getSubjectDN());
    } else if (log.isInfoEnabled()) {
        log.info("Retrieving certificate validation data for certificate (SHA-1 fingerprint): {}",
                Hex.encodeHexString(iaikEeCertificate.getFingerprintSHA()));
    }

    // retrieve certificate chain for eeCertificate
    X509Certificate[] caChainCertificates = retrieveChain(iaikEeCertificate, Objects.requireNonNull(settings));
    // build up full (sorted) chain including eeCertificate
    X509Certificate[] fullChainCertificates = Util.createCertificateChain(iaikEeCertificate,
            caChainCertificates);
    // add chain to certs list
    certs.addAll(Arrays.asList(fullChainCertificates));

    // determine revocation info, preferring OCSP
    // assume last certificate in chain is trust anchor
    OCSPClient ocspClient = OCSPClient.builder().setConnectTimeOutMillis(DEFAULT_CONNECTION_TIMEOUT_MS)
            .setSocketTimeOutMillis(DEFAULT_READ_TIMEOUT_MS).build();
    for (int i = 0; i < fullChainCertificates.length - 1; i++) {
        final X509Certificate subjectCertificate = fullChainCertificates[i];
        final X509Certificate issuerCertificate = fullChainCertificates[i + 1];
        OCSPResponse ocspResponse = null;
        if (OCSPClient.Util.hasOcspResponder(subjectCertificate)) {
            try {
                ocspResponse = ocspClient.getOcspResponse(issuerCertificate, subjectCertificate);
            } catch (Exception e) {
                log.info("Unable to retrieve OCSP response: {}", String.valueOf(e));
            }
        }

        if (ocspResponse != null) {

            ocsps.add(ocspResponse.getEncoded());

            // add ocsp signer certificate to certs
            // The currently used OCSP client support BasicOCSPResponse only, otherwise an exception would have been
            // thrown earlier. Therefore we can safely cast to BasicOCSPResponse here.
            X509Certificate ocspSignerCertificate = ((BasicOCSPResponse) ocspResponse.getResponse())
                    .getSignerCertificate();
            certs.add(ocspSignerCertificate);

        } else {

            // fall back to CRL

            CRLDistributionPoints cRLDistributionPoints;
            try {
                cRLDistributionPoints = (CRLDistributionPoints) subjectCertificate
                        .getExtension(CRLDistributionPoints.oid);
            } catch (X509ExtensionInitException e) {
                throw new IllegalStateException("Unable to initialize extension CRLDistributionPoints.", e);
            }
            X509CRL x509Crl = null;
            if (cRLDistributionPoints != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieving CRL revocation info for: {}", subjectCertificate.getSubjectDN());
                } else if (log.isInfoEnabled()) {
                    log.info("Retrieving CRL revocation info for certificate (SHA-1 fingerprint): {}",
                            Hex.encodeHexString(subjectCertificate.getFingerprintSHA()));
                }

                Exception lastException = null;
                @SuppressWarnings("unchecked")
                Enumeration<DistributionPoint> e = cRLDistributionPoints.getDistributionPoints();
                while (e.hasMoreElements() && x509Crl == null) {
                    DistributionPoint distributionPoint = e.nextElement();

                    // inspect distribution point
                    if (distributionPoint.containsUriDpName()) {

                        String[] distributionPointNameURIs = distributionPoint.getDistributionPointNameURIs();
                        for (String distributionPointNameURI : distributionPointNameURIs) {
                            URL url;
                            try {
                                log.debug("Trying to download crl from distribution point: {}",
                                        distributionPointNameURI);
                                if (distributionPointNameURI.toLowerCase().startsWith("ldap://")) {
                                    url = new URL(null, distributionPointNameURI,
                                            new iaik.x509.net.ldap.Handler());
                                } else {
                                    url = new URL(distributionPointNameURI);
                                }
                                URLConnection urlConnection = url.openConnection();
                                urlConnection.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT_MS);
                                urlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);
                                try (InputStream in = urlConnection.getInputStream()) {
                                    x509Crl = new X509CRL(in);
                                    // we got crl, exit loop
                                    break;
                                } catch (CRLException e1) {
                                    lastException = e1;
                                    log.debug("Unable to parse CRL read from distribution point: {} ({})",
                                            distributionPointNameURI, e1.getMessage());
                                }
                            } catch (MalformedURLException e1) {
                                log.debug("Unsupported CRL distribution point uri: {} ({})",
                                        distributionPointNameURI, e1.getMessage());
                                lastException = e1;
                            } catch (IOException e1) {
                                log.debug("Error reading from CRL distribution point uri: {} ({})",
                                        distributionPointNameURI, e1.getMessage());
                                lastException = e1;
                            } catch (Exception e1) {
                                log.debug("Unknown error reading from CRL distribution point uri: {} ({})",
                                        distributionPointNameURI, e1.getMessage());
                                lastException = e1;
                            }
                        }

                    }

                }
                if (x509Crl != null) {
                    crls.add(x509Crl);
                } else if (lastException != null) {
                    log.info("Unable to load CRL: {}", String.valueOf(lastException));
                }
            }

        }

    }
    sw.stop();
    log.debug("Querying certificate validation info took: {}ms", sw.getTime());

    return new CertificateVerificationData() {

        @Override
        public List<byte[]> getEncodedOCSPResponses() {
            return ocsps;
        }

        @Override
        public Set<java.security.cert.X509Certificate> getChainCerts() {
            return certs;
        }

        @Override
        public Set<java.security.cert.X509CRL> getCRLs() {
            return crls;
        }
    };
}