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.taiter.ce.Main.java

public void updateCheck() {
    try {/*from  w  w  w. j  av a  2s.  c o  m*/
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Checking for updates...");

        URLConnection connection = updateListURL.openConnection();
        connection.setConnectTimeout(5000);
        connection.addRequestProperty("User-Agent", "Custom Enchantments - Update Checker");
        connection.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        JSONObject newestUpdate = (JSONObject) array.get(array.size() - 1);

        newVersion = newestUpdate.get("name").toString().replace("Custom Enchantments ", "").trim();
        newMD5 = newestUpdate.get("md5").toString();

        int newLength = newVersion.length();
        int currentLength = currentVersion.length();

        double versionNew;
        double versionCurrent;

        Boolean newHasSubVersion = false;
        Boolean currentHasSubVersion = false;

        try {
            versionNew = Double.parseDouble(newVersion);
        } catch (NumberFormatException ex) {
            newHasSubVersion = true;
            versionNew = Double.parseDouble(newVersion.substring(0, newVersion.length() - 1));
        }

        try {
            versionCurrent = Double.parseDouble(currentVersion);
        } catch (NumberFormatException ex) {
            currentHasSubVersion = true;
            versionCurrent = Double.parseDouble(currentVersion.substring(0, currentVersion.length() - 1));
        }

        if ((versionNew > versionCurrent) || ((versionNew == versionCurrent) && newHasSubVersion
                && currentHasSubVersion && ((byte) newVersion.toCharArray()[newLength
                        - 1] > (byte) currentVersion.toCharArray()[currentLength - 1]))) {
            hasUpdate = true;
            updateDownloadURL = new URL(newestUpdate.get("downloadUrl").toString().replace("\\.", ""));
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] A new update is available!");
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] The new version is " + ChatColor.AQUA
                    + newVersion + ChatColor.GREEN + ".");
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] You are currently using "
                    + ChatColor.AQUA + currentVersion + ChatColor.GREEN + ".");
            Bukkit.getConsoleSender().sendMessage(
                    ChatColor.GREEN + "[CE] You can use '/ce update applyupdate' to update automatically.");

        } else {
            hasUpdate = false;
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.GREEN + "[CE] You are using the latest Version of CE!");
        }
        hasChecked = true;
    } catch (IOException ioex) {
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Failed to check for updates");
    }

}

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

/**
 * Executes a query./*  ww w  .  ja va2s .co  m*/
 * @param command    Name of the command to execute
 * @param parameters Parameters
 * @param manager    Reference back to business layer
 * @return Parsed JSON object, empty object on error.
 */
public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) {
    URLConnection uc = null;
    try {
        final ObjectMapper mapper = Client.MAPPER;

        if (mUrlSuffix == null) {
            throw new NoSettingsException();
        }

        final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP);
        uc = url.openConnection();
        uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
        uc.setReadTimeout(mSocketReadTimeout);
        if (authEncoded != null) {
            uc.setRequestProperty("Authorization", "Basic " + authEncoded);
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setDoOutput(true);

        final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1");
        if (parameters != null) {
            data.put("params", parameters);
        }

        final JsonFactory jsonFactory = new JsonFactory();
        final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8);
        jg.setCodec(mapper);

        // POST data
        jg.writeTree(data);
        jg.flush();

        final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream());
        jp.setCodec(mapper);
        final JsonNode ret = jp.readValueAs(JsonNode.class);
        return ret;

    } catch (MalformedURLException e) {
        manager.onError(e);
    } catch (IOException e) {
        int responseCode = -1;
        try {
            responseCode = ((HttpURLConnection) uc).getResponseCode();
        } catch (IOException e1) {
        } // do nothing, getResponse code failed so treat as default i/o exception.
        if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));
        } else {
            manager.onError(e);
        }
    } catch (NoSettingsException e) {
        manager.onError(e);
    }
    return new ObjectNode(null);
}

From source file:org.wso2.emm.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);/*from www.  ja v a2 s .c  o  m*/
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}

From source file:org.wso2.iot.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);//from   ww  w. ja v  a 2s.c  o m
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                        Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                        message);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                        Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                        message);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

private InputStream openStreamForLocalUrl(final String localUrl) throws MalformedURLException, IOException {
    URL url = new URL("http://" + mConfig.getDreamboxAddress() + localUrl);
    URLConnection connection = url.openConnection();

    // set user and password
    String userpassword = mConfig.getUserName() + ":" + mConfig.getPassword();
    String encoded = new String(Base64.encodeBase64(userpassword.getBytes()));
    connection.setRequestProperty("Authorization", "Basic " + encoded);

    // set timeout
    connection.setConnectTimeout(mConfig.getTimeout());
    InputStream stream = connection.getInputStream();
    return stream;
}

From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's details.
 *
 * @return true if successful./*from  w ww.j  av a  2 s . c om*/
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", Updater.USER_AGENT);

        conn.setDoOutput(true);

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

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

        if (array.isEmpty()) {
            this.plugin.getLogger()
                    .warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

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

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

From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java

public boolean downloadPhoto(File saveLocation, PhotoEntry photo) throws IOException, ParseException {
    boolean downloadSuccess = false;
    final int BUFFER_SIZE = 8096;
    final int TIMEOUT_MS = 10 * 1000;

    File saveFolder = saveLocation.getParentFile();
    boolean createdFolder = false;

    if (!saveFolder.exists()) {
        log.info("Creating local folder: " + saveFolder.getName());
        if (!saveFolder.mkdirs())
            throw new IOException("Unable to create folder " + saveFolder.getName());
        createdFolder = true;//from ww w.  j  a  v  a 2  s.  c  om
    }

    log.debug("Beginning download for " + saveLocation + "...");

    File tempFile = new File(saveLocation + ".tmp");
    tempFile.deleteOnExit();

    FileOutputStream fos = new FileOutputStream(tempFile);

    List<MediaContent> media = photo.getMediaContents();
    URL fileUrl = new URL(photo.getMediaContents().get(0).getUrl());

    if (media.size() > 1) {
        if (media.size() > 2) {
            log.debug("Extracting h264 video stream...");
            fileUrl = new URL(photo.getMediaContents().get(2).getUrl());
        } else {
            log.debug("Extracting low-res video stream...");
            fileUrl = new URL(photo.getMediaContents().get(1).getUrl());
        }
    }

    try {
        URLConnection conn = fileUrl.openConnection();
        conn.setConnectTimeout(TIMEOUT_MS);
        conn.setReadTimeout(TIMEOUT_MS);
        InputStream dis = conn.getInputStream();

        int totalRead = 0;
        int readCount = 0;
        byte b[] = new byte[BUFFER_SIZE];
        while ((readCount = dis.read(b)) != 0 && readCount != -1) {
            totalRead += readCount;
            fos.write(b, 0, readCount);
        }
        dis.close();
        fos.close();

        if (!tempFile.renameTo(saveLocation))
            throw new IOException("Unable to rename temp file to " + saveLocation);

        // Fix up the timestamps from the photo metadata
        updateTimeFromTags(saveLocation, photo, createdFolder);

        log.info("Written " + FileUtils.byteCountToDisplaySize(totalRead) + " to " + saveLocation
                + " successfully.");
        downloadSuccess = true;
    } catch (ConnectException ex) {
        log.warn("Network connection downloading " + fileUrl, ex);
        saveLocation = null;
    } catch (Exception ex) {
        log.error("Unexpected exception downloading " + fileUrl, ex);
        saveLocation = null;

    }

    return downloadSuccess;
}

From source file:org.geoserver.wps.Execute.java

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

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

    // execute the request
    try {
        if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(connectionTimeout);
            params.setConnectionTimeout(connectionTimeout);
            // 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(connectionTimeout);
                            conn.setReadTimeout(connectionTimeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

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

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

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

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

private String getPageAsStringFromUrl(String link) {
    String html = "";
    BufferedReader in = null;//from w w  w .ja  v  a 2s .c  o m
    try {
        URL url = new URL(link);
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            html += inputLine + " \n";
        }
    } catch (Exception e) {
        //            LOG.error(e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
    return html;
}