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:us.mn.state.dot.tms.client.camera.FTPStream.java

/** @throws IOException */
protected InputStream createInputStream(URL url) throws IOException {
    URLConnection c = url.openConnection();
    c.setConnectTimeout(TIMEOUT_DIRECT);
    c.setReadTimeout(TIMEOUT_DIRECT);
    return c.getInputStream();
}

From source file:backend.SoftwareSecurity.java

private JSONObject connectToServer(String site) { //every call to this method must add to the blankjsonobjectmadetoavoiderrors if it calls a new json key
    try {//from ww w.  j ava 2 s .  c o  m
        URLConnection con = new URL(site).openConnection();
        con.setConnectTimeout(timeoutMS);
        con.setReadTimeout(timeoutMS);
        InputStream in = con.getInputStream();
        String encoding = con.getContentEncoding();
        System.out.println("Server connection successful, returning JSON from server");
        return new JSONObject(IOUtils.toString(in, encoding == null ? "UTF-8" : encoding));
    } catch (Exception e) {
        System.out.println("Error during server connection: " + e.getMessage());
    }

    JSONObject blankJSONObjectMadeToAvoidErrors = new JSONObject(); //returns json object with values expected to avoid org.jsonexception
    blankJSONObjectMadeToAvoidErrors.put("banned", "no");
    blankJSONObjectMadeToAvoidErrors.put("version", 0.1);
    blankJSONObjectMadeToAvoidErrors.put("success", false);
    blankJSONObjectMadeToAvoidErrors.put("licenseType", "");

    return blankJSONObjectMadeToAvoidErrors; //returns null if error connecting
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java

public Neo4jZippedInstaller() {
    Thread checkSizeThread = new Thread() {
        @Override/*from w  w w.j a va  2 s. c o m*/
        public void run() {
            try {
                URLConnection connection = getUrl().openConnection();
                connection.setConnectTimeout(1000);
                connection.setReadTimeout(1000);
                size = connection.getContentLength();
            } catch (Exception e) {
                size = ERROR;
            }
            notifyListeners();
        }
    };
    checkSizeThread.start();
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.wsi.io.AMBIENTReader.java

private void downloadHTMLPage(JCas jCas, final Result result) {
    try {//w w w. jav a2 s .  c  o m
        URL inputURL = new URL(URLDecoder.decode(result.url));
        URLConnection conn = inputURL.openConnection();
        conn.setReadTimeout(30000);
        InputStream is = conn.getInputStream();

        String text;

        CharsetDetector detector = new CharsetDetector();
        detector.enableInputFilter(true);

        try {
            text = IOUtils.toString(detector.getReader(is, null));

        } catch (Exception e) {
            text = IOUtils.toString(is);
        }
        StringBuffer cleanedText = new StringBuffer(Jsoup.parse(text).text());

        int index = XMLUtils.checkForNonXmlCharacters(cleanedText.toString(), false);
        while (index > -1) {
            cleanedText.delete(index, index + 1);
            index = XMLUtils.checkForNonXmlCharacters(cleanedText.toString(), false);
        }
        if (StringUtils.isAsciiPrintable(cleanedText.toString())) {
            jCas.setDocumentText(result.text + " " + cleanedText.toString());
        } else {
            jCas.setDocumentText(result.text);
        }
    } catch (Exception e) {
        getLogger().warn("Connection to " + result.url + " timed out/failed, using snippet only");
        e.printStackTrace();
        getLogger().warn(e);
        jCas.setDocumentText(result.text);
    }
}

From source file:org.dataconservancy.dcs.ingest.services.ExternalContentStager.java

private void stageExternalFile(DcsFile file) {

    List<DcsEvent> eventsToAdd = new ArrayList<DcsEvent>();

    URL fileUrl;/*from  w w w.  ja  v  a 2  s .  c  o m*/
    try {
        fileUrl = new URL(encodeTagId(file.getSource()));
    } catch (MalformedURLException e) {
        throw new RuntimeException(
                String.format("Invalid file content url in file %s: %s", file.getId(), file.getSource()));
    }

    HashMap<String, String> metadata = new HashMap<String, String>();

    if (file.getName() == null) {
        file.setName(getFileName(fileUrl));
    }

    /* Stage the content */
    InputStream stream = null;
    StagedFile staged = null;
    try {
        InputStream src = null;
        if (file.getSource().contains("file:"))
            src = fileUrl.openStream();
        else if (file.getSource().contains("http:") || file.getSource().contains("https:")) {
            String loginPassword = this.acrUser + ":" + this.acrPassword;
            String encoded = new sun.misc.BASE64Encoder().encode(loginPassword.getBytes());
            URLConnection conn = fileUrl.openConnection();
            conn.setConnectTimeout(15 * 1000);
            conn.setReadTimeout(15 * 1000);
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            src = conn.getInputStream();
        }
        stream = fixityFilter(src, metadata, eventsToAdd);
        staged = ingest.getFileContentStager().add(stream, metadata);
        // file.setSource(staged.getReferenceURI());
        // TODO : Directly setting the access URI due to Reference URI resolving issues for large collections
        file.setSource(staged.getAccessURI());
    } catch (IOException e) {
        throw new RuntimeException("Error getting content from " + fileUrl.toString());
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                log.error("Error while downloading file", e);
            }
        }
    }

    /*
     * Add digest and download events to the staged content's sip, as well
     * as fixity values themselves
     */
    updateStagedSip(staged.getSipRef(), fileUrl, metadata, eventsToAdd);

}

From source file:com.gmail.bleedobsidian.itemcase.Updater.java

/**
 * Query ServerMods API for project variables.
 *
 * @return If successful or not./*from   w  w w  .j  a  v  a  2  s.c  o m*/
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}

From source file:fi.aluesarjat.prototype.DataService.java

public void importData(String datasetDef, boolean reload) {
    try {/*  w  w w .  j  a va 2 s  .c  om*/
        ScovoExtDatasetHandler handler = new ScovoExtDatasetHandler(repository, namespaceHandler, baseURI);
        PCAxisParser parser = new PCAxisParser(handler);

        if (StringUtils.isNotBlank(datasetDef)) {
            List<String> values = splitDatasetDef(datasetDef);
            String[] protAndPath = values.get(0).split(":");
            String protocol = protAndPath[0];
            String path = protAndPath[1];
            String datasetName = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
            List<String> ignoredValues = Collections.emptyList();
            if (values.size() > 1) {
                ignoredValues = values.subList(1, values.size());
            }

            UID uid = ScovoExtDatasetHandler.datasetUID(baseURI, datasetName);
            UID datasetsContext = ScovoExtDatasetHandler.datasetsContext(baseURI);
            boolean load;
            RDFConnection conn = repository.openConnection();
            try {
                // TODO: reload -> first delete existing triples
                load = !conn.exists(uid, DCTERMS.modified, null, datasetsContext, false);
            } finally {
                conn.close();
            }
            if (load) {
                handler.setIgnoredValues(ignoredValues.toArray(new String[ignoredValues.size()]));
                logger.info("Loading " + datasetName + "...");
                long time = System.currentTimeMillis();
                InputStream in;
                if ("classpath".equals(protocol)) {
                    in = getStream(path);
                } else {
                    URLConnection urlConnection = new URL(values.get(0)).openConnection();
                    urlConnection.setConnectTimeout(3000);
                    urlConnection.setReadTimeout(3000);
                    in = urlConnection.getInputStream();
                }
                try {
                    parser.parse(datasetName, in);
                } finally {
                    in.close();
                }
                logger.info(
                        "Done loading " + datasetName + " in " + (System.currentTimeMillis() - time) + " ms");
            } else {
                logger.info("Skipping existing " + datasetName);
            }
        }
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(datasetDef + " " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java

private String getRawResponse(String rawRequest, int timeoutMillis) throws IOException {
    URLConnection connection = apiUrl.openConnection();
    connection.setRequestProperty("Accept", "text/plain");
    connection.setRequestProperty("Content-type", "application/json");
    connection.setRequestProperty("User-Agent", client);
    connection.setDoOutput(true);/*from   www . j a  v a2  s.  com*/
    connection.setReadTimeout(timeoutMillis);

    final OutputStream out = connection.getOutputStream();
    out.write(rawRequest.getBytes(StandardCharsets.UTF_8));
    out.flush();
    out.close();

    log.debug("wrote request " + rawRequest + " (timeout wanted: " + timeoutMillis + ", actual: "
            + connection.getReadTimeout() + ")");

    String response = null;
    try (final InputStream in = connection.getInputStream()) {
        response = IOUtils.toString(in, StandardCharsets.UTF_8);
    }

    return response;
}

From source file:org.wso2.carbon.automation.test.utils.generic.GenericJSONClient.java

public JSONObject doGet(String endpoint, String query, String contentType)
        throws AutomationFrameworkException, IOException {
    String charset = "UTF-8";
    OutputStream os = null;// w  w w  . j a v a  2  s.c o m
    InputStream is = null;
    try {
        if (contentType == null || "".equals(contentType)) {
            contentType = "application/json";
        }
        URLConnection conn = new URL(endpoint).openConnection();
        conn.setRequestProperty(GenericJSONClient.HEADER_CONTENT_TYPE, contentType);
        conn.setRequestProperty(GenericJSONClient.HEADER_ACCEPT_CHARSET, charset);
        conn.setRequestProperty("Content-Length", "1000");
        conn.setReadTimeout(30000);
        System.setProperty("java.net.preferIPv4Stack", "true");
        conn.setRequestProperty("Connection", "close");
        conn.setDoOutput(true);
        os = conn.getOutputStream();
        os.write(query.getBytes(charset));
        is = conn.getInputStream();
        String out = null;
        if (is != null) {
            StringBuilder source = new StringBuilder();
            byte[] data = new byte[1024];
            int len;
            while ((len = is.read(data)) != -1) {
                source.append(new String(data, 0, len, Charset.defaultCharset()));
            }
            out = source.toString();
        }
        return new JSONObject(out);
    } catch (IOException e) {
        throw new AutomationFrameworkException("Error occurred while executing the GET operation", e);
    } catch (JSONException e) {
        throw new AutomationFrameworkException("Error occurred while parsing the response to a JSONObject", e);
    } finally {
        assert os != null;
        os.flush();
        os.close();
        assert is != null;
        is.close();
    }
}