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

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

Introduction

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

Prototype

public HttpException(String message, Throwable cause) 

Source Link

Document

Creates a new HttpException with the specified detail message and cause.

Usage

From source file:com.bdaum.zoom.net.core.internal.Activator.java

public static InputStream openStream(String url, int timeout)
        throws MalformedURLException, IOException, HttpException {
    URL u = new URL(url);
    URLConnection con = u.openConnection();
    con.setConnectTimeout(timeout);//from   w w w .  ja v  a2 s  .c  om
    con.setReadTimeout(timeout);
    try {
        return new BufferedInputStream(con.getInputStream());
    } catch (IOException e) {
        int responseCode = -1;
        if (con instanceof HttpURLConnection)
            responseCode = ((HttpURLConnection) con).getResponseCode();
        else if (con instanceof HttpsURLConnection)
            responseCode = ((HttpsURLConnection) con).getResponseCode();
        if (responseCode >= 0 && responseCode != HttpStatus.SC_OK)
            throw new HttpException(getStatusText(responseCode), e);
        throw e;
    }
}

From source file:net.paissad.waqtsalat.utils.DownloadHelper.java

/**
 * <p>//from   www.j a  v a2 s  .  c  om
 * Download a resource from the specified url and save it to the specified
 * file.
 * </p>
 * <b>Note</b>: If you plan to cancel the download at any time, then this
 * method should be embed into it's own thread.
 * <p>
 * <b>Example</b>:
 * 
 * <pre>
 *  final DownloadHelper downloader = new DownloadHelper();
 *  Thread t = new Thread() {
 *      public void run() {
 *          try {
 *              downloader.download("http://domain.com/file.zip", new File("/tmp/output.zip"));
 *          } catch (Exception e) {
 *              ...
 *          }
 *      }
 *  };
 *  t.start();
 *  // Waits 3 seconds and then cancels the download.
 *  Thread.sleep(3 * 1000L);
 *  downloader.cancel();
 *  ...
 * </pre>
 * 
 * </p>
 * 
 * @param url
 *            - The url of the file to download.
 * @param file
 *            - The downloaded file (where it will be stored).
 * @throws IOException
 * @throws HttpException
 */
public void download(final String url, final File file) throws HttpException, IOException {

    GetMethod method = null;
    InputStream responseBody = null;
    OutputStream out = null;

    try {
        final boolean fileExisted = file.exists();

        HttpClient client = new HttpClient();
        method = new GetMethod(url);
        method.setFollowRedirects(true);
        method.setRequestHeader("User-Agent", WSConstants.WS_USER_AGENT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        method.getParams().setParameter(HttpMethodParams.WARN_EXTRA_INPUT, Boolean.TRUE);

        // Execute the method.
        int responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK) {
            logger.error("Http method failed : {}.", method.getStatusLine().toString());
        }

        // Read the response body.
        responseBody = method.getResponseBodyAsStream();

        // Let's try to compute the amount of total bytes of the file to
        // download.
        URL u = new URL(url);
        URLConnection urlc = u.openConnection();
        this.totalBytes = urlc.getContentLength();
        long lastModified = urlc.getLastModified();

        // The OutputStream for the 'downloaded' file.
        out = new BufferedOutputStream(new FileOutputStream(file));

        this.updateState(DownloadState.IN_PROGRESS);

        byte[] data = new byte[BUFFER_SIZE];
        int length;
        while ((length = responseBody.read(data, 0, BUFFER_SIZE)) != -1 && !isCancelled) {
            out.write(data, 0, length);
            this.bytesDownloaded += length;
            setChanged();
            notifyObservers(getBytesDownloaded());
        }

        if (isCancelled) {
            this.updateState(DownloadState.CANCELED);
            logger.info("The download has been cancelled.");

        } else {
            // The download was not cancelled.
            out.flush();
            if (lastModified > 0) {
                file.setLastModified(lastModified);
            }

            if (bytesDownloaded != totalBytes) {
                logger.warn("The expected bytes to download is {}, but got {}.", getTotalBytes(),
                        getBytesDownloaded());
                this.updateState(DownloadState.ERROR);
            }

            this.updateState(DownloadState.FINISHED);
            logger.info("Download of '{}' finished successfully.", url);
        }

        // If the file did not exist before the download but does exit now,
        // we must remove it if an error occurred or if the download was
        // cancelled.
        if (getState() == DownloadState.CANCELED || getState() == DownloadState.ERROR) {
            if (!fileExisted && file.exists()) {
                FileUtils.forceDelete(file);
            }
        }

    } catch (HttpException he) {
        this.updateState(DownloadState.ERROR);
        logger.error("Fatal protocol violation : " + he);
        throw new HttpException("Error while downloading from the url '" + url + "'", he);

    } catch (IOException ioe) {
        this.updateState(DownloadState.ERROR);
        logger.error("Fatal transport error : " + ioe);
        throw new IOException(ioe);

    } finally {
        if (method != null)
            method.releaseConnection();
        if (responseBody != null)
            responseBody.close();
        if (out != null)
            out.close();
    }
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state, boolean addCasTicket)
        throws IOException, HttpException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - entering");
    }//from   ww w  .j  a  v  a  2  s  .co  m

    try {
        if (this.isAddCasTicketParams()) {
            HttpClientCAS.addCASTicket(method);
        }
    } catch (MotuCasException e) {
        throw new HttpException(e.notifyException(), e);
    }

    int returnint = super.executeMethod(hostconfig, method, state);
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - exiting");
    }
    return returnint;
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

public int executeMethod(HostConfiguration hostConfiguration, HttpMethod method, boolean addCasTicket)
        throws IOException, HttpException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HostConfiguration, HttpMethod, boolean) - entering");
    }/* ww  w  .  ja  v  a  2  s .c  om*/

    try {
        if (this.isAddCasTicketParams()) {
            HttpClientCAS.addCASTicket(method);
        }
    } catch (MotuCasException e) {
        throw new HttpException(e.notifyException(), e);
    }

    int returnint = 500;
    try {
        returnint = super.executeMethod(hostConfiguration, method);
    } catch (IOException e) {
        method.releaseConnection();
        throw e;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HostConfiguration, HttpMethod, boolean) - exiting");
    }
    return returnint;
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

public int executeMethod(HttpMethod method) throws IOException, HttpException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HttpMethod) - entering");
    }/*from w  w  w  .  ja  v a  2  s.c o  m*/
    try {
        if (this.isAddCasTicketParams()) {
            HttpClientCAS.addCASTicket(method);
        }
    } catch (MotuCasException e) {
        throw new HttpException(e.notifyException(), e);
    }

    // int returnint = super.executeMethod(method);
    int returnint = super.executeMethod(null, method, null);
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HttpMethod) - exiting");
    }
    return returnint;
}