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:com.adito.rss.FeedManager.java

protected void loadAvailable() throws IOException {
    URL location = new URL(baseLocation, "index.txt");

    availableFeeds.clear();//from  w ww  .  ja v a  2s .  c  o m
    URLConnection conx = location.openConnection();
    conx.setConnectTimeout(CONNECT_TIMEOUT);
    conx.setReadTimeout(READ_TIMEOUT);

    if (log.isInfoEnabled()) {
        log.info("Retrieving RSS feeds index from " + location);
    }
    InputStream inputStream = null;
    try {
        inputStream = conx.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            availableFeeds.add(line);
        }
    } finally {
        Util.closeStream(inputStream);
    }
    if (log.isInfoEnabled())
        log.info("There are " + availableFeeds.size() + " available feeds");
}

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

/**
 * Query ServerMods API for project variables.
 * /* w w  w . java2 s.  c  o  m*/
 * @return If successful or not.
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(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:io.s4.latin.adapter.TwitterFeedListener.java

public void connectAndRead() throws Exception {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);//from  ww w .j a  v a 2 s.c o  m

    String userPassword = userid + ":" + password;
    System.out.println("connect to " + connection.getURL().toString() + " ...");

    String encoded = EncodingUtil.getAsciiString(Base64.encodeBase64(EncodingUtil.getAsciiBytes(userPassword)));
    connection.setRequestProperty("Authorization", "Basic " + encoded);
    connection.setRequestProperty("Accept-Charset", "utf-8,ISO-8859-1");
    connection.connect();
    System.out.println("Connect OK!");
    System.out.println("Reading TwitterFeed ....");
    Long startTime = new Date().getTime();
    InputStream is = connection.getInputStream();
    Charset utf8 = Charset.forName("UTF-8");

    InputStreamReader isr = new InputStreamReader(is, utf8);
    BufferedReader br = new BufferedReader(isr);

    String inputLine = null;

    while ((inputLine = br.readLine()) != null) {
        if (inputLine.trim().length() == 0) {
            blankCount++;
            continue;
        }
        messageCount++;
        messageQueue.add(inputLine);
        if (messageCount % 500 == 0) {
            Long currentTime = new Date().getTime();
            System.out.println("Lines processed: " + messageCount + "\t ( " + blankCount + " empty lines ) in "
                    + (currentTime - startTime) / 1000 + " seconds. Reading "
                    + messageCount / ((currentTime - startTime) / 1000) + " rows/second");
        }
    }
}

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

public Neo4jZippedInstaller() {
    Thread checkSizeThread = new Thread() {
        @Override/*w w  w  .  ja  v  a 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: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:org.illalabs.rss.RssStreamProviderTask.java

/**
 * Reads the url and queues the data//from   w ww .  j a  va 2s  . c o m
 * 
 * @param feedUrl
 *            rss feed url
 * @return set of all article urls that were read from the feed
 * @throws IOException
 *             when it cannot connect to the url or the url is malformed
 * @throws FeedException
 *             when it cannot reed the feed.
 */
@VisibleForTesting
protected Set<String> queueFeedEntries(URL feedUrl) throws IOException, FeedException {
    Set<String> batch = Sets.newConcurrentHashSet();
    URLConnection connection = feedUrl.openConnection();
    connection.setConnectTimeout(this.timeOut);
    connection.setConnectTimeout(this.timeOut);
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new InputStreamReader(connection.getInputStream()));
    for (Object entryObj : feed.getEntries()) {
        SyndEntry entry = (SyndEntry) entryObj;
        ObjectNode nodeEntry = this.serializer.deserialize(entry);
        nodeEntry.put(RSS_KEY, this.feedDetails.getUrl());
        String entryId = determineId(nodeEntry);
        batch.add(entryId);
        Datum datum = new Datum(nodeEntry, entryId, DateTime.now());
        try {
            JsonNode published = nodeEntry.get(DATE_KEY);
            if (published != null) {
                try {
                    DateTime date = RFC3339Utils.parseToUTC(published.asText());
                    if (date.isAfter(this.publishedSince)
                            && (!seenBefore(entryId, this.feedDetails.getUrl()))) {
                        this.dataQueue.put(datum);
                        LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                    }
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.trace(
                            "Failed to parse date from object node, attempting to add node to queue by default.");
                    if (!seenBefore(entryId, this.feedDetails.getUrl())) {
                        this.dataQueue.put(datum);
                        LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                    }
                }
            } else {
                LOGGER.debug("No published date present, attempting to add node to queue by default.");
                if (!seenBefore(entryId, this.feedDetails.getUrl())) {
                    this.dataQueue.put(datum);
                    LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                }
            }
        } catch (InterruptedException ie) {
            LOGGER.error("Interupted Exception.");
            Thread.currentThread().interrupt();
        }
    }
    return batch;
}

From source file:net.ae97.totalpermissions.update.UpdateChecker.java

@Override
public void run() {
    if (disabled) {
        return;/* ww w. ja  v a  2s.c om*/
    }
    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectIds=54850");
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        if (apikey != null && !apikey.isEmpty() && !apikey.equals("PUT_API_KEY_HERE")) {
            conn.addRequestProperty("X-API-Key", apikey);
        }
        conn.addRequestProperty("User-Agent", "Updater - TotalPermissions-v" + pluginVersion);
        conn.setDoOutput(true);

        BufferedReader reader = null;
        JsonElement details = null;
        try {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String json = reader.readLine();
            JsonArray array = new JsonParser().parse(json).getAsJsonArray();
            details = array.get(array.size() - 1);
        } catch (IOException e) {
            if (e.getMessage().contains("HTTP response code: 403")) {
                throw new IOException("CurseAPI rejected API-KEY", e);
            }
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        if (details == null) {
            return;
        }

        String onlineVersion = details.getAsJsonObject().get("name").getAsString();

        if (!checkForUpdate(pluginVersion, onlineVersion)) {
            return;
        }

        pluginLogger.log(Level.INFO, "Update found! Current: {0} Latest: {1}",
                new String[] { StringUtils.join(getVersionInts(pluginVersion), "."),
                        StringUtils.join(getVersionInts(onlineVersion), ".") });

        if (!download) {
            return;
        }

        String downloadLink = details.getAsJsonObject().get("downloadUrl").getAsString();

        String pluginFileName = pluginFile.getName();

        if (!pluginFileName.equalsIgnoreCase(pluginName + ".jar")) {
            pluginLogger.log(Level.WARNING, "FILE NAME IS NOT {0}.jar! Forcing rename", pluginName);
            pluginFile.deleteOnExit();
        }

        File output = new File(Bukkit.getUpdateFolderFile(), pluginName + ".jar");
        download(downloadLink, output);

    } catch (MalformedURLException ex) {
        pluginLogger.log(Level.SEVERE, "URL could not be created", ex);
    } catch (IOException ex) {
        pluginLogger.log(Level.SEVERE, "Error occurred on checking for update for " + pluginName, ex);
    }
}

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

public void importData(String datasetDef, boolean reload) {
    try {/*from  w w  w.ja  va  2 s .  co  m*/
        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: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 ava2s . 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
}