Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setReadTimeout.

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {// ww  w. j ava2 s .  com
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java

private String getFileIdFromFileName(String authToken, String fileName, String inFolderId) {

    HttpURLConnection conn = null;
    String fileId = "";

    try {//from  ww w  .  ja va2  s . com

        fileName = URLEncoder.encode(fileName, "UTF-8");

        String inFolderParam = "";
        if (!Strings.isNullOrEmpty(inFolderId)) {
            inFolderParam = "+and+'" + inFolderId + "'+in+parents";
        }

        //To search in a folder:
        String searchUrl = "https://www.googleapis.com/drive/v2/files?q=title%20%3D%20%27" + fileName
                + "%27%20and%20trashed%20%3D%20false" + inFolderParam;

        URL url = new URL(searchUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "OAuth " + authToken);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(30000);

        String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        if (fileMetadataJson.getJSONArray("items") != null
                && fileMetadataJson.getJSONArray("items").length() > 0) {
            fileId = fileMetadataJson.getJSONArray("items").getJSONObject(0).get("id").toString();
            LOG.debug("Found file with ID " + fileId);
        }

    } catch (Exception e) {
        LOG.error("SearchForGPSLoggerFile", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return fileId;
}

From source file:com.zaa.WeatherLoad.java

public void Load() {
    HttpURLConnection lv_connection = null;
    try {/*from  www . ja  v  a  2 s.co  m*/
        City.InitCity();
        String lv_name, lv_dt, lv_encoding, lv_response;
        Set lt_keys = Cache.gv_city.keySet();
        Iterator lv_iterator = lt_keys.iterator();
        JSONArray lv_json_array, lv_json_weather;
        JSONObject lv_json, lv_json_response, lv_json_weather_row, lv_json_temp;
        City lv_city;
        CityTemp lv_city_temp;
        int lv_resp_code;
        InputStream lv_in_stream;
        Hashtable lv_city_temp_col;
        while (lv_iterator.hasNext()) {
            lv_name = lv_iterator.next().toString();
            lv_city_temp_col = (Hashtable) Cache.gv_city_temp.get(lv_name);
            lv_connection = (HttpURLConnection) new URL("http://api.openweathermap.org/data/2.5/weather?q="
                    + URLEncoder.encode(lv_name, "utf-8") + "&units=metric").openConnection();
            lv_connection.setConnectTimeout(30000);
            lv_connection.setReadTimeout(30000);
            lv_connection.setDoOutput(true);
            lv_connection.setDoInput(true);
            lv_connection.setRequestMethod("GET");
            lv_connection.setRequestProperty("Accept-Encoding", "gzip");
            lv_resp_code = lv_connection.getResponseCode();
            lv_in_stream = new BufferedInputStream(lv_connection.getInputStream(), 8192);
            lv_encoding = lv_connection.getHeaderField("Content-Encoding");
            if (lv_encoding != null && lv_encoding.equalsIgnoreCase("gzip")) {
                lv_in_stream = new GZIPInputStream(lv_in_stream);
            }
            lv_response = convertStreamToString(lv_in_stream);
            lv_json_response = new JSONObject(lv_response);
            if (lv_json_response.getString("cod").equals("200")) {
                lv_city = (City) Cache.gv_city.get(lv_name);
                lv_json = lv_json_response.getJSONObject("main");
                lv_city.SetTemp(lv_json.getString("temp"));
                lv_city.SetPressure(lv_json.getString("pressure"));
                lv_city.SetHumidity(lv_json.getString("humidity"));
                lv_json = lv_json_response.getJSONObject("wind");
                lv_city.SetWindSpeed(lv_json.getString("speed"));
                lv_json_weather = lv_json_response.getJSONArray("weather");
                if (lv_json_weather != null) {
                    lv_json_weather_row = (JSONObject) lv_json_weather.get(0);
                    lv_city.SetIcon(lv_json_weather_row.getString("icon").substring(0, 2));
                }
                lv_city.Save();
            }
            lv_connection.disconnect();
            lv_connection = (HttpURLConnection) new URL(
                    "http://api.openweathermap.org/data/2.5/forecast/daily?q="
                            + URLEncoder.encode(lv_name, "utf-8") + "&units=metric&cnt=7").openConnection();
            lv_connection.setConnectTimeout(30000);
            lv_connection.setReadTimeout(30000);
            lv_connection.setDoOutput(true);
            lv_connection.setDoInput(true);
            lv_connection.setRequestMethod("GET");
            lv_connection.setRequestProperty("Accept-Encoding", "gzip");
            lv_resp_code = lv_connection.getResponseCode();
            lv_in_stream = new BufferedInputStream(lv_connection.getInputStream(), 8192);
            lv_encoding = lv_connection.getHeaderField("Content-Encoding");
            if (lv_encoding != null && lv_encoding.equalsIgnoreCase("gzip")) {
                lv_in_stream = new GZIPInputStream(lv_in_stream);
            }
            lv_response = convertStreamToString(lv_in_stream);
            lv_json_response = new JSONObject(lv_response);
            if (lv_json_response.getString("cod").equals("200")) {
                CityTemp.DeleteCityTemp(lv_name);
                lv_json_array = lv_json_response.getJSONArray("list");
                if (lv_json_array != null) {
                    for (int i = 0; i < lv_json_array.length(); i++) {
                        lv_json = (JSONObject) lv_json_array.get(i);
                        lv_dt = lv_json.getString("dt");
                        lv_city_temp = (CityTemp) lv_city_temp_col.get(lv_dt);
                        if (lv_city_temp == null) {
                            lv_city_temp = new CityTemp(lv_name, lv_dt);
                            lv_city_temp_col.put(lv_dt, lv_city_temp);
                        }
                        lv_json_weather = lv_json.getJSONArray("weather");
                        if (lv_json_weather != null) {
                            lv_json_weather_row = (JSONObject) lv_json_weather.get(0);
                            lv_city_temp.SetIcon(lv_json_weather_row.getString("icon").substring(0, 2));
                        }
                        lv_json_temp = lv_json.getJSONObject("temp");
                        lv_city_temp.SetTempDay(lv_json_temp.getString("day"));
                        lv_city_temp.SetTempNight(lv_json_temp.getString("night"));
                        lv_city_temp.Save();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        gv_handler.sendEmptyMessage(Weather.NO_NET);
    } finally {
        if (lv_connection != null) {
            lv_connection.disconnect();
        }
    }
    gv_handler.sendEmptyMessage(Weather.LOAD_OK);
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {/*from w w w .j a  va 2  s  .c o m*/
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<? extends Playground> getWithin(Context context, GeoPoint topLeft, GeoPoint bottomRight,
        int maxQuantity) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {//w  ww.  j av a  2  s  . c o  m
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground?" + TYPE_PARAM + "=" + WITHIN + "&"
                + TOP_LEFT_LATITUDE_PARAM + "=" + topLeft.getLatitudeE6() / 1E6 + "&" + TOP_LEFT_LONGITUDE_PARAM
                + "=" + topLeft.getLongitudeE6() / 1E6 + "&" + BOTTOM_RIGHT_LATITUDE_PARAM + "="
                + bottomRight.getLatitudeE6() / 1E6 + "&" + BOTTOM_RIGHT_LONGITUDE_PARAM + "="
                + bottomRight.getLongitudeE6() / 1E6);
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    Log.d(TAG, "   -> returned " + result);
    return playgrounds;
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryDMS(String DMS_endpoint, String postObject, String cookie) {
    HttpURLConnection connectionDMS = null;
    try {// ww w  .j a  v a2s .  c  o m

        String postObjectString = postObject;
        byte[] postObjectByte = postObjectString.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postObjectByte.length;
        URL DMS_Url = new URL(dms_URL + "/" + DMS_endpoint);

        // prepare header
        connectionDMS = (HttpURLConnection) DMS_Url.openConnection();
        connectionDMS.setDoOutput(true);
        connectionDMS.setDoInput(true);
        connectionDMS.setConnectTimeout(5000);
        connectionDMS.setReadTimeout(5000);
        connectionDMS.setRequestProperty("Content-Type", "application/json");
        connectionDMS.setRequestProperty("Accept", "application/json");
        connectionDMS.setRequestProperty("charset", "utf-8");
        connectionDMS.setRequestProperty("vitalAccessToken", cookie);
        connectionDMS.setRequestMethod("POST");
        connectionDMS.setRequestProperty("Content-Length", Integer.toString(postDataLength));

        DataOutputStream wr = new DataOutputStream(connectionDMS.getOutputStream());
        wr.write(postObjectByte);
        wr.flush();
        int HttpResult = connectionDMS.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            Object obj = new InputStreamReader(connectionDMS.getInputStream(), "utf-8");

            return obj.toString();

        } else {
            return null;
        }
    } catch (Exception e) {
        //logger.error(e.toString());
        //throw new ConnectionErrorException("Error in connection with DMSManager");
    } finally {
        if (connectionDMS != null) {
            connectionDMS.disconnect();
        }
    }
    return "";
}

From source file:com.edgenius.wiki.service.impl.NotificationServiceImpl.java

public void doVersionCheck() {
    HttpURLConnection conn = null;
    try {/*  ww  w.ja  va  2s. c o m*/
        log.info("Version check starting");
        int currVer = (int) (NumberUtils.toFloat(Version.VERSION, 0f) * 1000);
        //hard code
        URL url = new URL("http://product.edgenius.com/versioncheck/" + SharedConstants.APP_NAME + "/"
                + Installation.INSTANCE_ID + "/" + currVer);
        //         Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy url", 80));
        //         conn = (HttpURLConnection) url.openConnection(proxy);
        conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        //         conn.addRequestProperty("Authorization", "Basic "+encrytString(username+":" + password));

        conn.setReadTimeout(20000);
        InputStream in = conn.getInputStream();
        StringBuffer sb = new StringBuffer();
        byte[] b = new byte[1024 * 10];
        int len;
        while ((len = in.read(b)) != -1) {
            sb.append(new String(b, 0, len));

        }
        String content = sb.toString();
        //         String content = "<version>3.01</version>";
        int start = content.indexOf("<version>");
        int end = content.indexOf("</version>");
        if (start != -1 && end != -1 && start < end) {
            String verStr = content.substring(start + 9, end);
            int version = (int) (NumberUtils.toFloat(verStr, 0f) * 1000);

            if (version > 0 && currVer > 0) {
                if (version > currVer) {
                    //check if this new version is already send notification to user, if so, silence.

                    List<ActivityLog> activities = activityLog.getByTarget(
                            ActivityType.Type.SYSTEM_EVENT.getCode(),
                            ActivityType.SubType.VERSION_PING.getCode(), version, "VERSION_CHECK"); //hardcode
                    if (activities == null || activities.size() == 0) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("newVer", verStr);
                        map.put("currVer", Version.VERSION);
                        mailService.sendPlainToSystemAdmins(WikiConstants.MAIL_TEMPL_VERSION_CHECK, map);
                        log.info("New version {} found and notified to system administrators.", version);

                        //log activity
                        ActivityLog activity = new ActivityLog();
                        activity.setType(ActivityType.Type.SYSTEM_EVENT.getCode());
                        activity.setSubType(ActivityType.SubType.VERSION_PING.getCode());
                        activity.setTgtResourceType(version);
                        activity.setTgtResourceName("VERSION_CHECK");//hardcode
                        activity.setExtroInfo(verStr);
                        activity.setCreatedDate(new Date());
                        activityLog.save(activity);
                    } else {
                        log.info(
                                "New version {} found, but this version is already notified so no action takes",
                                2000);
                    }
                }
            } else {
                log.info("Wrong version number returned:{}", content);
            }
        }
        log.info("Version check is done");

    } catch (Exception e) {
        log.warn("Version check not success. This probably because of your network connection");
    } finally {
        try {
            if (conn != null)
                conn.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:com.beesham.popularmovies.sync.MoviesSyncAdapter.java

/**
 * Gets and stores the movie trailer and reviews JSON data
 * @param movieId/*  ww  w.ja  v a2s.c  om*/
 * @param flag
 * @return
 */
private String getTrailersOrReviews(String movieId, int flag) {
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    String movieJsonStr = null;
    String MOVIE_QUERY_URL = null;

    try {
        switch (flag) {
        case 0:
            MOVIE_QUERY_URL = getContext().getString(R.string.movies_base_trailers_url, movieId);
            break;
        case 1:
            MOVIE_QUERY_URL = getContext().getString(R.string.movies_base_reviews_url, movieId);
            break;
        }
        final String API_KEY_PARAM = "api_key";

        Uri builtUri = Uri.parse(MOVIE_QUERY_URL).buildUpon().appendQueryParameter(API_KEY_PARAM, API_KEY)
                .build();

        URL url = new URL(builtUri.toString());

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(15000);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null)
            return null;

        reader = new BufferedReader((new InputStreamReader(inputStream)));
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0)
            return null;

        movieJsonStr = buffer.toString();

    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
        }
    }

    return movieJsonStr;
}

From source file:com.beesham.popularmovies.sync.MoviesSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient,
        SyncResult syncResult) {//from  ww w. ja  va  2  s  . c om
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    String moviesJsonStr = null;

    try {
        final String MOVIES_BASE_URL = getContext().getString(R.string.movies_base_url);
        final String API_KEY_PARAM = "api_key";

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        String sort_by = prefs.getString(getContext().getString(R.string.pref_sort_key),
                getContext().getString(R.string.pref_sort_default));

        Uri builtUri = Uri.parse(MOVIES_BASE_URL).buildUpon().appendPath(sort_by)
                .appendQueryParameter(API_KEY_PARAM, API_KEY).build();

        URL url = new URL(builtUri.toString());

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(15000);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null)
            return;

        reader = new BufferedReader((new InputStreamReader(inputStream)));
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0)
            return;

        moviesJsonStr = buffer.toString();
        getMovieDataFromJson(moviesJsonStr);

    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
        }
    }
}

From source file:com.vuze.android.remote.AndroidUtils.java

private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) {
    try {/*w ww. ja  v  a 2  s .c o m*/
        HttpURLConnection.setFollowRedirects(false);

        URL url = new URL(URLName);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection conHttps = (HttpsURLConnection) con;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
                        new SecureRandom());
                conHttps.setSSLSocketFactory(ctx.getSocketFactory());
            }

            conHttps.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        con.setConnectTimeout(conTimeout);
        con.setReadTimeout(readTimeout);
        con.setRequestMethod("HEAD");
        con.getResponseCode();
        if (DEBUG) {
            Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage());
        }
        return true;
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, "isLive " + URLName, e);
        }
        return false;
    }
}