Example usage for org.apache.commons.httpclient HttpException getMessage

List of usage examples for org.apache.commons.httpclient HttpException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * ExtrasTransportHttp is an implementation of IExtraTransport and provides
 * Communication via http(s) protocol./*  w  ww . ja  v a 2 s . co m*/
 * 
 * @see de.extra.client.transport.IExtraTransport#senden(java.lang.String)
 */
@Override
public InputStream senden(final InputStream extraRequest) throws ExtraTransportException {

    if (client != null) {

        // Init response
        InputStream extraResponse = null;

        // Build url String and create post request
        PostMethod method = new PostMethod(requestURL);

        try {

            RequestEntity entity = new InputStreamRequestEntity(extraRequest);
            method.setRequestEntity(entity);

            // Execute the method - send it
            int statusCode = client.executeMethod(method);

            // Something goes wrong
            if (statusCode != HttpStatus.SC_OK) {
                throw new ExtraTransportException(
                        "Versand von Request fehlgeschlagen: " + method.getStatusLine());
            } else {

                // Read the response body and save it

                extraResponse = method.getResponseBodyAsStream();
            }

        } catch (HttpException e) {
            throw new ExtraTransportException("Schwere Protokollverletzung: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new ExtraTransportException("Schwerer Transportfehler: " + e.getMessage(), e);
        } finally {

            // Release the connection.
            method.releaseConnection();
        }
        return extraResponse;
    } else {
        throw new ExtraTransportException("Http Client nicht initialisiert!");
    }
}

From source file:de.juwimm.cms.content.modules.ModuleFactoryStandardImpl.java

public Module loadPlugins(String classname, List<String> additionalJarFiles) {
    Module module = null;/*from   www. j a  v  a2  s . co  m*/
    Communication comm = ((Communication) getBean(Beans.COMMUNICATION));
    SiteValue site = comm.getCurrentSite();
    String urlPath = site.getDcfUrl();
    final String userHome = System.getProperty("user.home");
    final String fileSeparator = System.getProperty("file.separator");

    StringBuffer pluginCachePath = new StringBuffer(userHome);
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(".tizzitCache");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append("plugins");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(Constants.SERVER_HOST);
    pluginCachePath.append(fileSeparator);

    final String pluginPath = pluginCachePath.toString();

    final int addSize = additionalJarFiles.size();

    /* enthaelt alle Jar files die sich nicht auf dem lokalen Rechner befinden */
    ArrayList<String> httpLoad = new ArrayList<String>();

    for (int i = 0; i < addSize; i++) {
        String filePath = pluginPath + additionalJarFiles.get(i);
        File tempFile = new File(filePath);
        if (!tempFile.exists()) {
            httpLoad.add(additionalJarFiles.get(i));
        }
    }

    if (httpLoad.size() > 0) {
        File dir = new File(pluginPath);
        if (!dir.exists()) {
            if (log.isDebugEnabled())
                log.debug("Going to create plugin directory...");
            boolean ret = dir.mkdirs();
            if (!ret) {
                log.warn("Could not create plugin directory");
            }
        }

        /* laedt die Jarfiles auf den lokalen Rechner herunter */
        HttpClient httpclient = new HttpClient();
        for (int i = 0; i < httpLoad.size(); i++) {
            String url = urlPath + httpLoad.get(i);
            if (log.isDebugEnabled())
                log.debug("Plugin URL " + url);
            HttpMethod method = new GetMethod(url);
            try {
                int status = httpclient.executeMethod(method);
                if (status == HttpStatus.SC_OK) {
                    File file = new File(pluginPath + httpLoad.get(i));
                    byte[] data = method.getResponseBody();
                    if (log.isDebugEnabled())
                        log.debug("Received " + data.length + " bytes of data");
                    FileOutputStream output = new FileOutputStream(file);
                    output.write(data);
                    output.close();
                } else {
                    log.warn("No OK received");
                }
            } catch (HttpException htex) {
                log.warn("HTTP exception " + htex.getMessage());
            } catch (IOException ioe) {
                log.warn("IO exception " + ioe.getMessage());
            }
            method.releaseConnection();
        }
    }

    try {
        if (log.isDebugEnabled())
            log.debug("Creating URL");

        URL[] url = new URL[addSize];
        for (int i = 0; i < addSize; i++) {
            String jarModule = additionalJarFiles.get(i);
            String jarPath = "file:///" + pluginPath + jarModule;
            if (log.isDebugEnabled())
                log.debug("Jar path " + jarPath);
            url[i] = new URL(jarPath);
        }
        URLClassLoader cl = this.getURLClassLoader(url);
        //URLClassLoader cl = new URLClassLoader(url, this.getClass().getClassLoader());
        if (log.isDebugEnabled())
            log.debug("Created URL classloader");
        Class c = cl.loadClass(classname);
        if (log.isDebugEnabled())
            log.debug("Created class");
        module = (Module) c.newInstance();
        if (log.isDebugEnabled())
            log.debug("Got the module");
    } catch (Exception loadex) {
        log.warn(loadex.getClass().toString());
        log.error("Cannot load from URL " + loadex.getMessage(), loadex);
    }
    return module;
}

From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java

/**
 * It makes a GET towards the gateway. The response is retrieved with the {@link  PanlabGWClient#getResponse_stream()} ;
 * @author ctranoris//from  ww  w.ja  va  2 s. c  o m
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the resource Instance, e.g.: uop
 * @see PanlabGWClient#getResponse_stream()
 */
public void GETexecute(String resourceInstance, String ptmAlias) {
    HttpClient client = new HttpClient();

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.
    GetMethod get = new GetMethod(url);
    get.setRequestHeader("User-Agent", userAgent);
    get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        // execute the GET
        client.executeMethod(get);

        // print the status and response
        InputStream responseBody = get.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        get.releaseConnection();
    }

}

From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java

/**
 * It makes a GET towards the FedWay gateway. The response is retrieved with the {@link  PanlabGWClient#getResponse_stream()} ;
 * @author ctranoris/*from w w w .  j  a v a2s  . co  m*/
 * @param subject sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the resource Instance, e.g.: uop
 * @see PanlabGWClient#getResponse_stream()
 */
public void informFedWay(String fedway, String subject, String myDescription, String resourceid, Date start_ts,
        Date end_ts, String guid, String scenarioid, String scenarioName, String username) {
    ////http://nam.ece.upatras.gr/fedway/submit_event.php?subject=aResource&descr=myDescription&resourceid=123456&start_ts=2011-09-15%2017:00:00&end_ts=2011-09-17%2011:01:31&guid=guid5&scenarioid=scen1234&scenarioName=myScenario

    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    HttpClient client = new HttpClient();
    String url = "";

    try {
        url = "subject=" + URLEncoder.encode(subject, "UTF-8") + "&descr="
                + URLEncoder.encode(myDescription, "UTF-8") + "&resourceid="
                + URLEncoder.encode(resourceid, "UTF-8") + "&start_ts="
                + URLEncoder.encode(sdf.format(start_ts), "UTF-8") + //2011-09-15%2017:00:00
                "&end_ts=" + URLEncoder.encode(sdf.format(end_ts), "UTF-8") + //2011-09-17%2011:01:31
                "&guid=" + URLEncoder.encode(guid, "UTF-8") + "&scenarioid="
                + URLEncoder.encode(scenarioid, "UTF-8") + "&scenarioName="
                + URLEncoder.encode(scenarioName, "UTF-8") + "&username="
                + URLEncoder.encode(username, "UTF-8");

    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    url = fedway + "/submit_event.php?" + url;

    System.out.println("Request: " + url);

    // Create a method instance.
    GetMethod get = new GetMethod(url);
    get.setRequestHeader("User-Agent", userAgent);
    get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        // execute the GET
        client.executeMethod(get);

        // print the status and response
        InputStream responseBody = get.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        get.releaseConnection();
    }

}

From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java

/**
 * It makes a DELETE towards the gateway
 * @author ctranoris//from   w  ww.  j  a  v  a 2s .  c om
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public void DELETEexecute(String resourceInstance, String ptmAlias, String content) {
    System.out.println("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.

    DeleteMethod delMethod = new DeleteMethod(url);
    delMethod.setRequestHeader("User-Agent", userAgent);
    delMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    //      delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    //            new DefaultHttpMethodRetryHandler(3, false));

    //      RequestEntity requestEntity = null;
    //      try {
    //         requestEntity = new StringRequestEntity(tgwcontent,
    //               "application/x-www-form-urlencoded", "utf-8");
    //      } catch (UnsupportedEncodingException e1) {
    //         e1.printStackTrace();
    //      }

    //delMethod.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(delMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + delMethod.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = delMethod.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         System.out.println("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        delMethod.releaseConnection();
    }

}

From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java

/**
 * It makes a POST towards the gateway/*w w w. j av  a2 s  .  c o  m*/
 * @author ctranoris
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) {

    boolean status = false;
    System.out.println("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("User-Agent", userAgent);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    //HttpMethodParams.
    RequestEntity requestEntity = null;
    try {
        requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    post.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(post);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + post.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = post.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         System.out.println("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

        status = true;
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        post.releaseConnection();
    }

    return status;

}

From source file:com.dtolabs.client.utils.HttpClientChannel.java

/**
 * Perform the HTTP request.  Can only be performed once.
 *//*from   ww  w .  j  a  v a2 s  . c  o  m*/
public void makeRequest() throws IOException, HttpClientException {
    if (requestMade) {
        return;
    }

    requestMade = true;
    RequestEntity reqEntity = null;
    NameValuePair[] postBody = null;
    if (isPostMethod()) {
        setMethodType("POST");
    }
    HttpMethod method = initMethod();
    if (isPostMethod()) {
        reqEntity = getRequestEntity((PostMethod) method);
        if (null != reqEntity) {
            logger.debug("preparing to post request entity data: " + reqEntity.getContentType());

            ((PostMethod) method).setRequestEntity(reqEntity);
        } else {
            logger.debug("preparing to post form data");
            postBody = getRequestBody((PostMethod) method);
            ((PostMethod) method).setRequestBody(postBody);
        }
    }
    logger.debug("calling preMakeRequest");
    if (!preMakeRequest(method)) {
        return;
    }
    logger.debug("calling doAuthentication...");
    if (!doAuthentication(method)) {
        return;
    }
    int bytesread = 0;
    try {
        if (!isPostMethod()) {
            method.setFollowRedirects(true);
        }
        logger.debug("make request...");
        resultCode = httpc.executeMethod(method);
        reasonCode = method.getStatusText();
        if (isPostMethod()) {
            //check redirect after post
            method = checkFollowRedirect(method, resultCode);
        }
        logger.debug("check needs reauth...");

        if (needsReAuthentication(resultCode, method)) {
            logger.debug("re-authentication needed, performing...");
            method.releaseConnection();
            method.abort();
            //need to re-authenticate.
            method = initMethod();
            if (isPostMethod() && null != reqEntity) {
                ((PostMethod) method).setRequestEntity(reqEntity);
            } else if (isPostMethod() && null != postBody) {
                ((PostMethod) method).setRequestBody(postBody);
            }
            if (!doAuthentication(method)) {
                //user login failed
                return;
            }
            //user login has succeeded
            logger.debug("remaking original request...");
            resultCode = httpc.executeMethod(method);
            reasonCode = method.getStatusText();
            if (needsReAuthentication(resultCode, method)) {
                //user request was unauthorized
                throw new HttpClientException("Unauthorized Action: "
                        + (null != method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                ? method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                        .getValue()
                                : reasonCode));
            }
        }

        logger.debug("finish...");
        if (null != method.getResponseHeader("Content-Type")) {
            resultType = method.getResponseHeader("Content-Type").getValue();
        }
        String type = resultType;
        if (type != null && type.indexOf(";") > 0) {
            type = type.substring(0, type.indexOf(";")).trim();
        }
        if (null == expectedContentType || expectedContentType.equals(type)) {
            if (null != destinationStream && resultCode >= 200 && resultCode < 300) {
                //read the input stream and write it to the destination
                contentLengthRetrieved = Streams.copyStreamCount(method.getResponseBodyAsStream(),
                        destinationStream);
            } else {
                final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(1024 * 50);
                Streams.copyStream(method.getResponseBodyAsStream(), outputBytes);
                resultStream = new ByteArrayInputStream(outputBytes.toByteArray());
            }
        }
        reqMadeMethod = method;
    } catch (HttpException e) {
        logger.error("HTTP error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

    logger.debug("Response received");
    postMakeRequest();
}

From source file:com.ephesoft.dcma.batch.status.StatusConveyor.java

/**
 * Notifies any service event to fired on current server but needs to be handled by the server under which the service is
 * registered. It hits the particular server with the details required and registered server handles it respectively.
 * //from   w ww.  j ava 2s.c  o m
 * @param paramMap {@link Map<String, String>} details to be send to the server.
 * @param serviceType {@link ServiceType} type of service.
 */
public void notifyServiceEvent(final Map<String, String> paramMap, final ServiceType serviceType) {
    if (null != serviceType) {
        LOGGER.debug(EphesoftStringUtil.concatenate("Notifying server for service: ", serviceType.toString()));
        final String notifyWebServiceUrl = getNotifyWebServiceUrl(serviceType);
        if (null != notifyWebServiceUrl && !notifyWebServiceUrl.isEmpty()) {
            final HttpClient httpClient = new HttpClient();
            final PostMethod postMethod = new PostMethod(notifyWebServiceUrl);
            Part[] partArray = null;
            int index = 0;

            // If the details are to be send to web service
            if (null == paramMap || paramMap.isEmpty()) {
                partArray = new Part[1];
            } else {
                LOGGER.debug(EphesoftStringUtil.concatenate("Parameter passed are: ", paramMap.toString()));
                partArray = new Part[(paramMap.size() + 1)];
                final Iterator<String> keyIterator = paramMap.keySet().iterator();
                String key = null;
                while (keyIterator.hasNext()) {
                    key = keyIterator.next();
                    partArray[index] = new StringPart(key, paramMap.get(key));
                    index++;
                }
            }

            // Type of service which is a required parameter to be send
            partArray[index] = new StringPart(ICommonConstants.SERVICE_TYPE_PARAMETER,
                    String.valueOf(serviceType.getServiceType()));
            MultipartRequestEntity entity = new MultipartRequestEntity(partArray, postMethod.getParams());
            postMethod.setRequestEntity(entity);
            try {
                int statusCode = httpClient.executeMethod(postMethod);

                if (statusCode == STATUS_OK) {
                    LOGGER.debug(EphesoftStringUtil.concatenate(
                            "Server was notified successfully for service: ", serviceType.toString()));
                } else {
                    LOGGER.error(
                            EphesoftStringUtil.concatenate("Server was not able to be notified for service: ",
                                    serviceType.toString(), " and status code: ", statusCode));
                }
            } catch (HttpException httpException) {
                LOGGER.error(
                        EphesoftStringUtil.concatenate("Could not connect to server for notifying service: ",
                                serviceType.toString(), ICommonConstants.SPACE, httpException.getMessage()));
            } catch (IOException ioException) {
                LOGGER.error(
                        EphesoftStringUtil.concatenate("Could not connect to server for notifying service: ",
                                serviceType.toString(), ICommonConstants.SPACE, ioException.getMessage()));
            }
        }
    }
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

@Override
public long download(boolean resume, DownloadCompleteCallback callback) {
    switch (status) {
    case ABORTED:
    case UNRECOVERABLE_ERROR:
    case DOWNLOAD_FINISHED:
        return 0;
    default://from  w  w w. j  a va  2 s. co  m

    }
    int bytes = 0;
    File file = new File(toFile);
    try {

        long localFileSize = 0;
        if (file.exists() && resume) {
            localFileSize = file.length();
            s_logger.info("Resuming download to file (current size)=" + localFileSize);
        }

        Date start = new Date();

        int responseCode = 0;

        if (localFileSize > 0) {
            // require partial content support for resume
            request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
            if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
                errorString = "HTTP Server does not support partial get";
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                return 0;
            }
        } else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
            status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
            errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
            return 0; //FIXME: retry?
        }

        Header contentLengthHeader = request.getResponseHeader("Content-Length");
        boolean chunked = false;
        long remoteSize2 = 0;
        if (contentLengthHeader == null) {
            Header chunkedHeader = request.getResponseHeader("Transfer-Encoding");
            if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                errorString = " Failed to receive length of download ";
                return 0; //FIXME: what status do we put here? Do we retry?
            } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                chunked = true;
            }
        } else {
            remoteSize2 = Long.parseLong(contentLengthHeader.getValue());
        }

        if (remoteSize == 0) {
            remoteSize = remoteSize2;
        }

        if (remoteSize > MAX_TEMPLATE_SIZE_IN_BYTES) {
            s_logger.info("Remote size is too large: " + remoteSize + " , max=" + MAX_TEMPLATE_SIZE_IN_BYTES);
            status = Status.UNRECOVERABLE_ERROR;
            errorString = "Download file size is too large";
            return 0;
        }

        if (remoteSize == 0) {
            remoteSize = MAX_TEMPLATE_SIZE_IN_BYTES;
        }

        InputStream in = !chunked ? new BufferedInputStream(request.getResponseBodyAsStream())
                : new ChunkedInputStream(request.getResponseBodyAsStream());

        RandomAccessFile out = new RandomAccessFile(file, "rwd");
        out.seek(localFileSize);

        s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize="
                + remoteSize + " , max size=" + MAX_TEMPLATE_SIZE_IN_BYTES);

        byte[] block = new byte[CHUNK_SIZE];
        long offset = 0;
        boolean done = false;
        status = TemplateDownloader.Status.IN_PROGRESS;
        while (!done && status != Status.ABORTED && offset <= remoteSize) {
            if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) {
                out.write(block, 0, bytes);
                offset += bytes;
                out.seek(offset);
                totalBytes += bytes;
            } else {
                done = true;
            }
        }
        Date finish = new Date();
        String downloaded = "(incomplete download)";
        if (totalBytes >= remoteSize) {
            status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
            downloaded = "(download complete remote=" + remoteSize + "bytes)";
        }
        errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
        downloadTime += finish.getTime() - start.getTime();
        out.close();

        return totalBytes;
    } catch (HttpException hte) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        errorString = hte.getMessage();
    } catch (IOException ioe) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; //probably a file write error?
        errorString = ioe.getMessage();
    } finally {
        if (status == Status.UNRECOVERABLE_ERROR && file.exists() && !file.isDirectory()) {
            file.delete();
        }
        request.releaseConnection();
        if (callback != null) {
            callback.downloadComplete(status);
        }
    }
    return 0;
}

From source file:autohit.call.modules.SimpleHttpModule.java

/**
 * Start method. It will set the target address for the client, as well as
 * clearing any state.//w  ww.  java2s.  c  om
 * 
 * @param url
 *            the Url path, not to include protocol, address, and port (ie.
 *            "/goats/index.html").
 * @return the data from the page as a String
 * @throws CallException
 */
private String get(String url) throws CallException {

    if (started == false) {
        throw buildException("module:SimpleHttp:Tried to get when a session wasn't started.",
                CallException.CODE_MODULE_FAULT);
    }

    String result = null;

    // Construct our method.
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);

    //execute the method
    try {
        // Do it
        debug("(get)get=" + url);
        httpClient.executeMethod(method);

        // Process result
        result = method.getResponseBodyAsString();
        log("(get)" + method.getStatusLine().toString() + " size=" + result.length());

    } catch (HttpException he) {
        // Bad but not fatal
        error("(get)Error on connect to url " + url + ".  Error=" + he.getMessage());
    } catch (IOException ioe) {
        // Fatal
        throw buildException("(get)Unable to connect.  Session is invalid.  message=" + ioe.getMessage(),
                CallException.CODE_MODULE_FAULT, ioe);
    } finally {
        try {
            method.releaseConnection();
            method.recycle();
        } catch (Exception e) {
            // Already FUBAR
        }
    }
    return result;
}