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.alfaariss.oa.authentication.remote.aselect.idp.storage.config.IDPConfigStorage.java

/**
 * @see com.alfaariss.oa.engine.idp.storage.configuration.AbstractConfigurationStorage#createIDP(com.alfaariss.oa.api.configuration.IConfigurationManager, org.w3c.dom.Element)
 *///  w w  w  .jav  a 2  s  .c  o m
@Override
protected IIDP createIDP(IConfigurationManager configManager, Element config) throws OAException {
    ASelectIDP oASelectIDP = null;
    try {
        String sServerID = configManager.getParam(config, "server_id");
        if (sServerID == null) {
            _logger.error("No 'server_id' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sOrganizationID = configManager.getParam(config, "id");
        if (sOrganizationID == null) {
            _logger.error("No 'id' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sFriendlyname = configManager.getParam(config, "friendlyname");
        if (sFriendlyname == null) {
            _logger.error("No 'friendlyname' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sURL = configManager.getParam(config, "url");
        if (sURL == null) {
            _logger.error("No 'url' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }
        URL urlTarget = null;
        try {
            urlTarget = new URL(sURL);
        } catch (MalformedURLException e) {
            _logger.error("Invalid 'url' parameter found in configuration: " + sURL);
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        try {
            URLConnection urlConnection = urlTarget.openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.setReadTimeout(3000);
            urlConnection.connect();
        } catch (IOException e) {
            _logger.warn("Could not connect to 'url' parameter found in configuration: " + sURL);
        }

        String sLevel = configManager.getParam(config, "level");
        if (sLevel == null) {
            _logger.error("No 'level' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        int iLevel;
        try {
            iLevel = Integer.parseInt(sLevel);
        } catch (NumberFormatException e) {
            _logger.error("Invalid 'level' parameter found in configuration, not a number: " + sLevel);
            throw new OAException(SystemErrors.ERROR_INIT);
        }

        String sCountry = configManager.getParam(config, "country");
        if (sCountry == null)
            _logger.info("No optional 'country' parameter found in configuration");

        String sLanguage = configManager.getParam(config, "language");
        if (sLanguage == null)
            _logger.info("No optional 'language' parameter found in configuration");

        boolean bDoSigning = false;
        String sSigning = configManager.getParam(config, "signing");
        if (sSigning != null) {
            if (sSigning.equalsIgnoreCase("TRUE"))
                bDoSigning = true;
            else if (!sSigning.equalsIgnoreCase("FALSE")) {
                _logger.error("Invalid 'signing' parameter found in configuration, must be 'true' or 'false': "
                        + sSigning);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        boolean bASynchronousLogout = false;
        String sASynchronousLogout = configManager.getParam(config, "asynchronouslogout");
        if (sASynchronousLogout != null) {
            if (sASynchronousLogout.equalsIgnoreCase("TRUE"))
                bASynchronousLogout = true;
            else if (!sASynchronousLogout.equalsIgnoreCase("FALSE")) {
                _logger.error(
                        "Invalid 'asynchronouslogout' parameter found in configuration, must be 'true' or 'false': "
                                + sASynchronousLogout);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        boolean bSynchronousLogout = false;
        String sSynchronousLogout = configManager.getParam(config, "synchronouslogout");
        if (sSynchronousLogout != null) {
            if (sSynchronousLogout.equalsIgnoreCase("TRUE"))
                bSynchronousLogout = true;
            else if (!sSynchronousLogout.equalsIgnoreCase("FALSE")) {
                _logger.error(
                        "Invalid 'synchronouslogout' parameter found in configuration, must be 'true' or 'false': "
                                + sSynchronousLogout);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        boolean bSendArpTarget = false;
        String sSendArpTarget = configManager.getParam(config, "send_arp_target");
        if (sSendArpTarget != null) {
            if (sSendArpTarget.equalsIgnoreCase("TRUE"))
                bSendArpTarget = true;
            else if (!sSendArpTarget.equalsIgnoreCase("FALSE")) {
                _logger.error(
                        "Invalid 'send_arp_target' parameter found in configuration, must be 'true' or 'false': "
                                + sSigning);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        oASelectIDP = new ASelectIDP(sOrganizationID, sFriendlyname, sServerID, sURL, iLevel, bDoSigning,
                sCountry, sLanguage, bASynchronousLogout, bSynchronousLogout, bSendArpTarget);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during create", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL, e);
    }
    return oASelectIDP;
}

From source file:com.servoy.extension.MarketPlaceExtensionProvider.java

private URLConnection ws_getConnection(String action, String acceptContentType, String extensionId,
        String version) throws Exception {
    String unescapedURL = MARKETPLACE_WS + action + "/" + extensionId //$NON-NLS-1$
            + (version != null ? "/" + version : "")/* + "?nodebug=true" */; //$NON-NLS-1$ //$NON-NLS-2$
    URL mpURL = new URI(null, null, unescapedURL, null).toURL(); // the URI should escape it correctly
    URLConnection urlConnection = mpURL.openConnection();

    urlConnection.addRequestProperty("accept", acceptContentType); //$NON-NLS-1$
    urlConnection.setConnectTimeout(30 * 1000); // don't make an unstoppable job if the network connection is down
    urlConnection.setReadTimeout(30 * 1000); // don't make an unstoppable job if the network connection is down or server doesn't want to respond

    return urlConnection;
}

From source file:ome.system.UpgradeCheck.java

/**
 * If the {@link #url} has been set to null or the empty string, then no
 * upgrade check will be performed (silently). If however the string is an
 * invalid URL, a warning will be printed.
 * /*from ww  w.ja va 2s .  com*/
 * This method should <em>never</em> throw an exception.
 */
public void run() {

    // If null or empty, the upgrade check is disabled.
    if (url == null || url.length() == 0) {
        return; // EARLY EXIT!
    }

    StringBuilder query = new StringBuilder();
    try {
        query.append(url);
        query.append("?version=");
        query.append(URLEncoder.encode(version, "UTF-8"));
        query.append(";os.name=");
        query.append(URLEncoder.encode(System.getProperty("os.name"), "UTF-8"));
        query.append(";os.arch=");
        query.append(URLEncoder.encode(System.getProperty("os.arch"), "UTF-8"));
        query.append(";os.version=");
        query.append(URLEncoder.encode(System.getProperty("os.version"), "UTF-8"));
        query.append(";java.runtime.version=");
        query.append(URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8"));
        query.append(";java.vm.vendor=");
        query.append(URLEncoder.encode(System.getProperty("java.vm.vendor"), "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        // Internal issue
        set(null, uee);
        return;
    }

    URL _url;
    try {
        _url = new URL(query.toString());
    } catch (Exception e) {
        set(null, e);
        log.error("Invalid URL: " + query.toString());
        return;
    }

    BufferedInputStream bufIn = null;
    try {
        URLConnection conn = _url.openConnection();
        conn.setUseCaches(false);
        conn.addRequestProperty("User-Agent", agent);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.connect();

        log.debug("Attempting to connect to " + query);

        InputStream in = conn.getInputStream();
        bufIn = new BufferedInputStream(in);

        StringBuilder sb = new StringBuilder();
        while (true) {
            int data = bufIn.read();
            if (data == -1) {
                break;
            } else {
                sb.append((char) data);
            }
        }
        String result = sb.toString();
        if (result.length() == 0) {
            log.info("no update needed");
            set(null, null);
        } else {
            log.warn("UPGRADE AVAILABLE:" + result);
            set(result, null);
        }
    } catch (UnknownHostException uhe) {
        log.error("Unknown host:" + url);
        set(null, uhe);
    } catch (IOException ioe) {
        log.error(String.format("Error reading from url: %s \"%s\"", query, ioe.getMessage()));
        set(null, ioe);
    } catch (Exception ex) {
        log.error("Unknown exception thrown on UpgradeCheck", ex);
        set(null, ex);
    } finally {
        Utils.closeQuietly(bufIn);
    }
}

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

@Override
public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from  ww  w .ja v a 2  s.  c om*/

    InputStream urlStream = null;
    try {
        URL url = getUrl();
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);

        int length = connection.getContentLength();
        monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()),
                length >= 0 ? length : IProgressMonitor.UNKNOWN);

        urlStream = connection.getInputStream();
        ZipInputStream zipStream = new ZipInputStream(urlStream);
        byte[] buffer = new byte[1024 * 8];
        long start = System.currentTimeMillis();
        int total = length;
        int totalRead = 0;
        ZipEntry entry;
        float kBps = -1;
        while ((entry = zipStream.getNextEntry()) != null) {
            if (monitor.isCanceled())
                break;
            String fullFilename = entry.getName();
            IPath fullFilenamePath = new Path(fullFilename);
            int secsRemaining = (int) ((total - totalRead) / 1024 / kBps);
            String textRemaining = secsToText(secsRemaining);
            monitor.subTask(NLS.bind("{0} remaining. Reading {1}",
                    textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils
                            .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45)));
            int entrySize = (int) entry.getCompressedSize();
            OutputStream output = null;
            try {
                int len = 0;
                int read = 0;
                String action = null;
                if (jarFiles.contains(fullFilename)) {
                    action = "Copying";
                    String filename = FilenameUtils.getName(fullFilename);
                    output = new FileOutputStream(dirPath.append(filename).toOSString());
                } else {
                    action = "Skipping";
                    output = new NullOutputStream();
                }
                int secs = (int) ((System.currentTimeMillis() - start) / 1000);
                kBps = (float) totalRead / 1024 / secs;

                while ((len = zipStream.read(buffer)) > 0) {
                    if (monitor.isCanceled())
                        break;
                    read += len;
                    monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)",
                            new Object[] {
                                    String.format("%s",
                                            textRemaining.length() > 0 ? textRemaining : "unknown time"),
                                    action,
                                    StringUtils.abbreviateMiddle(
                                            fullFilenamePath.removeFirstSegments(1).toString(), "...", 45),
                                    String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024),
                                    String.format("%,.1f", (float) entry.getSize() / 1024) }));
                    output.write(buffer, 0, len);
                }
                totalRead += entrySize;
                monitor.worked(entrySize);
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
    } finally {
        IOUtils.closeQuietly(urlStream);
        monitor.done();
    }
}

From source file:org.ambraproject.service.search.SolrHttpServiceImpl.java

/**
 * @inheritDoc//from  ww  w  .  j  a  v a2 s  .co  m
 */
@Override
public Document makeSolrRequest(Map<String, String> params) throws SolrException {
    if (solrUrl == null || solrUrl.isEmpty()) {
        setSolrUrl(config.getString(URL_CONFIG_PARAM));
    }

    //make sure the return type is xml
    if (!params.keySet().contains(RETURN_TYPE_PARAM) || !params.get(RETURN_TYPE_PARAM).equals(XML)) {
        params.put(RETURN_TYPE_PARAM, XML);
    }
    //make sure that we include a 'q' parameter
    if (!params.keySet().contains(Q_PARAM)) {
        params.put(Q_PARAM, NO_FILTER);
    }

    String queryString = "?";
    for (String param : params.keySet()) {
        String value = params.get(param);
        if (queryString.length() > 1) {
            queryString += "&";
        }
        queryString += (cleanInput(param) + "=" + cleanInput(value));
    }

    URL url;
    String urlString = solrUrl + queryString;
    log.debug("Making Solr http request to " + urlString);
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new SolrException("Bad Solr Url: " + urlString, e);
    }

    InputStream urlStream = null;
    Document doc = null;
    try {
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.connect();
        urlStream = connection.getInputStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(urlStream);
    } catch (IOException e) {
        throw new SolrException("Error connecting to the Solr server at " + solrUrl, e);
    } catch (ParserConfigurationException e) {
        throw new SolrException("Error configuring parser xml parser for solr response", e);
    } catch (SAXException e) {
        throw new SolrException("Solr Returned bad XML for url: " + urlString, e);
    } finally {
        //Close the input stream
        if (urlStream != null) {
            try {
                urlStream.close();
            } catch (IOException e) {
                log.error("Error closing url stream to Solr", e);
            }
        }
    }

    return doc;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.Fetcher.java

protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod,
        final long lastFetchTime) throws IOException {
    String method = GET_STR;/*from   w w w  .j  a v a2 s  . c om*/

    if (requestMethod != null) {
        method = requestMethod;
    }

    LOGGER.info(method + "ing: " + url + "; timeout is " + timeout);

    final URLConnection connection = new URL(url).openConnection();

    connection.setIfModifiedSince(lastFetchTime);

    if (timeout != 0) {
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
    }

    final HttpURLConnection http = (HttpURLConnection) connection;

    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;
        https.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
    }

    http.setInstanceFollowRedirects(false);
    http.setRequestMethod(method);
    http.setAllowUserInteraction(true);

    for (final String key : requestProps.keySet()) {
        http.addRequestProperty(key, requestProps.get(key));
    }

    if (method.equals(POST_STR) && data != null) {
        http.setDoOutput(true); // Triggers POST.

        try (final OutputStream output = http.getOutputStream()) {
            output.write(data.getBytes(UTF8_STR));
        }
    }

    connection.connect();

    return http;
}

From source file:org.apache.marmotta.ucuenca.wk.commons.function.SemanticDistance.java

private synchronized String http(String s) throws SQLException, IOException {

    Statement stmt = conn.createStatement();
    String sql;/*from   w w w  .  ja v a 2s .  com*/
    sql = "SELECT * FROM cache where cache.key='" + commonservices.getMD5(s) + "'";
    java.sql.ResultSet rs = stmt.executeQuery(sql);
    String resp = "";
    if (rs.next()) {
        resp = rs.getString("value");
        rs.close();
        stmt.close();
    } else {
        rs.close();
        stmt.close();
        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();

        try {
            JsonParser parser = new JsonParser();
            parser.parse(resp);
            PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)");
            stmt2.setString(1, commonservices.getMD5(s));
            stmt2.setString(2, resp);
            stmt2.executeUpdate();
            stmt2.close();
        } catch (Exception e) {

        }
    }

    return resp;
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

/**
 * Get the public facing hostname for this machine.  Uses AWS metadata service.
 *///from  w  w  w . j  a  v  a 2s .c  om
protected String getInstanceMetadata(String name, String defValue) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bout = null;
    String ret_val = null;
    InputStream is = null;

    try {
        URL url = new URL("http://169.254.169.254/latest/meta-data/" + name);

        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(5000);
        urlConn.setReadTimeout(15000);
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        is = new BufferedInputStream(urlConn.getInputStream());

        baos = new ByteArrayOutputStream();
        bout = new BufferedOutputStream(baos, 1024);

        int buffSize = 8 * 1024;
        byte data[] = new byte[buffSize];
        int count;

        while ((count = is.read(data, 0, buffSize)) >= 0) {
            baos.write(data, 0, count);
        }

        ret_val = baos.toString();
    } catch (Exception e) {
        // ignore
        //e.printStackTrace();
    } finally {
        try {
            bout.close();
            is.close();
        } catch (Exception e) {
            // ignore
        }
    }

    if (ret_val == null) {
        ret_val = defValue;
    }

    return ret_val;
}

From source file:org.geoserver.wps.executor.RemoteRequestInputProvider.java

@Override
protected Object getValueInternal(ProgressListener listener) throws Exception {
    InputReferenceType ref = input.getReference();
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;//from   w w  w.j av  a 2 s  . c o  m
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    listener.started();
    try {
        if ("file".equalsIgnoreCase(destination.getProtocol())) {
            File file = DataUtilities.urlToFile(destination);
            if (maxSize > 0 && maxSize < file.length()) {
                throw new WPSException("Input " + getInputId() + " size " + file.length()
                        + " exceeds maximum allowed size of " + maxSize, "NoApplicableCode", getInputId());
            }

            input = new FileInputStream(file);
        } else 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(timeout);
            params.setConnectionTimeout(timeout);
            // 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(timeout);
                            conn.setReadTimeout(timeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(
                                new InputStreamRequestEntity(refInput, complexPPIO.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, complexPPIO.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) {
                try {
                    Header length = method.getResponseHeader("Content-Lenght");
                    if (maxSize > 0 && length != null && Long.parseLong(length.getValue()) > maxSize) {
                        throw new WPSException(
                                "Input " + getInputId() + " size " + length.getValue()
                                        + " exceeds maximum allowed size of " + maxSize
                                        + " according to HTTP Content-Lenght response header",
                                "NoApplicableCode", getInputId());
                    }
                } catch (NumberFormatException e) {
                    LOGGER.log(Level.FINE, "Failed to parse content lenght to check input limits respect, "
                            + "moving on and checking data as it comes in", e);
                }
                input = method.getResponseBodyAsStream();
                if (maxSize > 0) {
                    input = new MaxSizeInputStream(input, getInputId(), maxSize);
                }
            } 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(timeout);
            conn.setReadTimeout(timeout);
            input = conn.getInputStream();

            if (maxSize > 0) {
                input = new MaxSizeInputStream(input, getInputId(), maxSize);
            }
        }

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

From source file:org.adaway.service.UpdateService.java

/**
 * Check for updates of hosts sources/*from   w  w w  .  j a  va 2  s .  c o  m*/
 *
 * @return return code
 */
private int checkForUpdates() {
    Cursor enabledHostsSourcesCursor;
    long currentLastModifiedLocal;
    long currentLastModifiedOnline;
    boolean updateAvailable = false;

    int returnCode = StatusCodes.ENABLED; // default return code

    if (Utils.isAndroidOnline(mService)) {

        mNumberOfFailedDownloads = 0;
        mNumberOfDownloads = 0;

        // get cursor over all enabled hosts source
        enabledHostsSourcesCursor = ProviderHelper.getEnabledHostsSourcesCursor(mService);

        // iterate over all hosts sources in db with cursor
        if (enabledHostsSourcesCursor != null && enabledHostsSourcesCursor.moveToFirst()) {
            do {

                mNumberOfDownloads++;

                // get url and lastModified from db
                String currentUrl = enabledHostsSourcesCursor
                        .getString(enabledHostsSourcesCursor.getColumnIndex("url"));
                currentLastModifiedLocal = enabledHostsSourcesCursor
                        .getLong(enabledHostsSourcesCursor.getColumnIndex("last_modified_local"));

                try {
                    Log.v(Constants.TAG, "Checking hosts file: " + currentUrl);

                    /* build connection */
                    URL mURL = new URL(currentUrl);
                    URLConnection connection = mURL.openConnection();
                    connection.setConnectTimeout(15000);
                    connection.setReadTimeout(30000);

                    currentLastModifiedOnline = connection.getLastModified();

                    Log.d(Constants.TAG, "mConnectionLastModified: " + currentLastModifiedOnline + " ("
                            + DateUtils.longToDateString(mService, currentLastModifiedOnline) + ")");

                    Log.d(Constants.TAG, "mCurrentLastModified: " + currentLastModifiedLocal + " ("
                            + DateUtils.longToDateString(mService, currentLastModifiedLocal) + ")");

                    // check if file is available
                    connection.connect();
                    connection.getInputStream();

                    // check if update available for this hosts file
                    if (currentLastModifiedOnline > currentLastModifiedLocal) {
                        updateAvailable = true;
                    }

                    // save last modified online for later viewing in list
                    ProviderHelper.updateHostsSourceLastModifiedOnline(mService,
                            enabledHostsSourcesCursor
                                    .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)),
                            currentLastModifiedOnline);

                } catch (Exception e) {
                    Log.e(Constants.TAG, "Exception while downloading from " + currentUrl, e);

                    mNumberOfFailedDownloads++;

                    // set last_modified_online of failed download to 0 (not available)
                    ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor
                            .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), 0);
                }

            } while (enabledHostsSourcesCursor.moveToNext());
        }

        // close cursor in the end
        if (enabledHostsSourcesCursor != null && !enabledHostsSourcesCursor.isClosed()) {
            enabledHostsSourcesCursor.close();
        }

        // if all downloads failed return download_fail error
        if (mNumberOfDownloads == mNumberOfFailedDownloads && mNumberOfDownloads != 0) {
            returnCode = StatusCodes.DOWNLOAD_FAIL;
        }
    } else {
        // only report no connection when not in background
        if (!mBackgroundExecution) {
            returnCode = StatusCodes.NO_CONNECTION;
        } else {
            Log.e(Constants.TAG, "Should not happen! In background execution is no connection available!");
        }
    }

    // set return code if update is available
    if (updateAvailable) {
        returnCode = StatusCodes.UPDATE_AVAILABLE;
    }

    // check if hosts file is applied
    if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_SYSTEM_ETC_HOSTS)) {
        returnCode = StatusCodes.DISABLED;
    }

    return returnCode;
}