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:com.ephesoft.dcma.heartbeat.HeartBeat.java

/**
 * This method will return true if the server is active other wise false.
 * /*from ww w . j av  a 2s . c o m*/
 * @param url {@link String}
 * @return boolean true if the serve is active other wise false.
 */
private boolean checkHealth(final String url) {

    boolean isActive = false;

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

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

        if (statusCode == HttpStatus.SC_OK) {
            isActive = true;
        } else {
            LOGGER.info("Method failed: " + method.getStatusLine());
        }

    } catch (HttpException e) {
        LOGGER.error("Fatal protocol violation: " + e.getMessage());
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
    } finally {
        // Release the connection.
        if (method != null) {
            method.releaseConnection();
        }
    }

    return isActive;
}

From source file:com.sfs.upload.AdobeShareFileUploadImpl.java

/**
 * Upload the identified File to the defined storage pool.
 *
 * @param file the file//  ww  w .  j a v  a 2  s.c  om
 *
 * @return the file upload details
 *
 * @throws FileUploadException the file upload exception
 */
public final FileUploadDetails upload(final File file) throws FileUploadException {
    if (file == null) {
        throw new FileUploadException("The File object cannot be null");
    }
    if (!file.exists()) {
        throw new FileUploadException("No file exists to upload");
    }
    if (StringUtils.isBlank(this.apiKey)) {
        throw new FileUploadException("An Adobe Share API key is required");
    }
    if (StringUtils.isBlank(this.apiSharedSecret)) {
        throw new FileUploadException("An Adobe Share shared secret is required");
    }
    if (StringUtils.isBlank(this.userName)) {
        throw new FileUploadException("An Adobe Share username is required");
    }
    if (StringUtils.isBlank(this.password)) {
        throw new FileUploadException("An Adobe Share password is required");
    }

    final Date currentDate = Calendar.getInstance().getTime();
    // Add a prefix to ensure that there isn't a duplicate file name issue.
    final String format = "yyyyMMddhhmm_";
    final String fileName = Formatter.numericDate(currentDate, format) + file.getName();

    ShareAPI shareAPI = new ShareAPI(this.apiKey, this.apiSharedSecret);
    ShareAPIUser shareUser = new ShareAPIUser(this.userName, this.password);
    ShareAPINode shareNode = new ShareAPINode();

    FileUploadDetails details = null;

    try {
        logger.info("Logging into Acrobat.com");
        shareAPI.login(shareUser);
        // Upload the file to Adobe Share
        logger.info("Uploading file");
        shareNode = shareAPI.addFile(shareUser, file, fileName, "", null, true);
        logger.info("Changing privileges");
        // Set this node to be public (shared)
        shareAPI.shareFile(shareUser, shareNode, new ArrayList<String>(), userName, 2);
        logger.info("Logging out");
        shareAPI.logout(shareUser);

        if (shareNode != null) {
            details = new FileUploadDetails();
            details.setFileName(file.getName());
            details.setFileSize(file.length());
            details.setUrl(shareNode.getRecipientUrl());
        }
    } catch (HttpException he) {
        throw new FileUploadException("Error performing HTTP upload: " + he.getMessage());
    } catch (IOException ioe) {
        throw new FileUploadException("Error accessing file to upload: " + ioe.getMessage());
    } catch (ShareAPIException sapie) {
        throw new FileUploadException("Error interacting with Adobe Share: " + sapie.getMessage());
    } catch (IllegalArgumentException iae) {
        throw new FileUploadException("Error uploading file: " + iae.getMessage());
    }
    return details;
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

public HttpResponse connectGet(String url, String userAgent, ArrayList<Cookie> reqCookies,
        Header[] requestHeaders, boolean followRedirects) {
    logger.debug("HttpDelegate.connectGet(): " + url);

    GetMethod get = new GetMethod(url);
    try {/*  www . jav a2  s  .  c o  m*/
        prepareConnection(get, userAgent, reqCookies, requestHeaders, !url.contains("acceptxml=false"),
                followRedirects);
        if (logger.isDebugEnabled())
            HeaderUtil.printRequestHeaders(logger, get);

        return executeHttpMethod(get);
    } catch (HttpException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } finally {
        get.releaseConnection();
    }

    return null;
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

public HttpResponse connectPost(String url, String userAgent, ArrayList<Cookie> reqCookies,
        NameValuePair[] postData, Header[] requestHeaders, boolean followRedirects) {
    logger.debug("HttpDelegate.connectPost(): " + url);

    PostMethod post = new PostMethod(url);
    try {//w  w  w.j  a  v  a  2s .  co  m
        prepareConnection(post, userAgent, reqCookies, requestHeaders, !url.contains("acceptxml=false"),
                followRedirects);
        if (postData != null)
            post.setRequestBody(postData);

        return executeHttpMethod(post);
    } catch (HttpException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }

    return null;
}

From source file:com.ephesoft.dcma.core.service.ServerHeartBeatMonitor.java

/**
 * This method will return true if the server is active other wise false.
 * /*w  ww  .  j  a va  2  s. c  om*/
 * @param url {@link String} URL of the Heart beat service.
 * @return true if the serve is active other wise false.
 */
private boolean checkHealth(final String serviceURL) {
    boolean isActive = false;
    LOGGER.info(serviceURL);
    if (!EphesoftStringUtil.isNullOrEmpty(serviceURL)) {

        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(30000);
        client.setTimeout(30000);

        // Create a method instance.
        GetMethod method = new GetMethod(serviceURL);

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

            if (statusCode == HttpStatus.SC_OK) {
                isActive = true;
            } else {
                LOGGER.info("Method failed: " + method.getStatusLine());
            }
        } catch (HttpException httpException) {
            LOGGER.error("Fatal protocol violation: " + httpException.getMessage());
        } catch (IOException ioException) {
            LOGGER.error("Fatal transport error: " + ioException.getMessage());
        } finally {
            // Release the connection.
            if (method != null) {
                method.releaseConnection();
            }
        }

        return isActive;
    }
    return isActive;
}

From source file:ensen.controler.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;/*w ww. j a  v a2 s .co m*/

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

    try {
        // Execute the method.
        client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
        int statusCode = client.executeMethod(method);

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

        // Read the response body.
        InputStream responseBodyStream = method.getResponseBodyAsStream(); //Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        int b = responseBodyStream.read();
        ArrayList<Integer> bytes = new ArrayList<Integer>();
        while (b != -1) {
            bytes.add(b);
            b = responseBodyStream.read();
        }
        byte[] responseBody = new byte[bytes.size()];

        for (int i = 0; i < bytes.size(); i++) {
            responseBody[i] = bytes.get(i).byteValue();
        }
        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        System.out.println("Fatal protocol violation: " + e.getMessage());
        try {
            System.err.println(method.getURI());
        } catch (URIException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        System.out.println("Fatal transport error: " + e.getMessage());
        System.out.println(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

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

/**
 * Make a GET call towards the repository. The BASIC Authentication is handled automatically
 * @param tgwaddr/*from  w  w w .j a v a2  s  .  c o m*/
 */
public void execute(String tgwaddr) {

    String reqRepoURL = repoHostAddress + tgwaddr;
    HttpClient client = new HttpClient();

    // pass our credentials to HttpClient, they will only be used for
    // authenticating to servers with realm "realm" on the host
    // "www.verisign.com", to authenticate against an arbitrary realm 
    // or host change the appropriate argument to null.
    client.getState().setCredentials(new AuthScope(null, 8080),
            new UsernamePasswordCredentials(username, password));

    // create a GET method that reads a file over HTTPS, 
    // we're assuming that this file requires basic 
    // authentication using the realm above.
    GetMethod get = new GetMethod(reqRepoURL);
    System.out.println("Request: " + reqRepoURL);
    get.setRequestHeader("User-Agent", "RepoM2M-1.00");
    //get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Tell the GET method to automatically handle authentication. The
    // method will use any appropriate credentials to handle basic
    // authentication requests.  Setting this value to false will cause
    // any request for authentication to return with a status of 401.
    // It will then be up to the client to handle the authentication.
    get.setDoAuthentication(true);

    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();
        //return theinputstream;

    } 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();
    }
    //return null;       

}

From source file:com.fluxit.camel.component.n4.N4Producer.java

private InputStream invokeHttp(String url, HttpClient client, GetMethod method)
        throws HttpOperationFailedException, IOException {
    try {/*from   www.  j ava 2  s  .  c om*/

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

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // IDK que hacer con esto
        Header[] responseHeaders = method.getResponseHeaders();

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: {0}", method.getStatusLine());
            throw new HttpOperationFailedException(url, statusCode, null, null, null, new String(responseBody));
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not
        // binary data
        LOG.debug("Respuesta con codigo {0} de la invocacion HTTP {1}", statusCode, new String(responseBody));

        method.releaseConnection();

        return new ByteArrayInputStream(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage(), e);
        throw e;
    }

}

From source file:com.bdaum.juploadr.uploadapi.locrrest.LocrMethod.java

public boolean execute() throws ProtocolException, CommunicationException {

    HttpMethodBase method = getMethod();

    boolean rv = false;
    try {// w w w.  j a  v  a  2 s.  c  o  m
        int response = client.executeMethod(method);
        if (HttpStatus.SC_OK == response) {
            rv = parseResponse(method.getResponseBodyAsString());
            if (!rv) {
                throw defaultExceptionFor(handler.getErrorCode());
            }
        } else {
            throw new CommunicationException(Messages.getString("juploadr.ui.error.bad.http.response", //$NON-NLS-1$
                    Activator.getStatusText(response)));
        }
    } catch (InvalidAuthTokenException iat) {
        ((RestLocrApi) session.getApi()).reauthAccount(session);
    } catch (HttpException e) {
        throw new CommunicationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new CommunicationException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
    return rv;

}

From source file:com.funambol.json.manager.JsonAuthenticatorManagerImpl.java

public void enterSyncBeginStatus(String username, String deviceId) throws DaoException {
    try {//  w w w  . ja v a 2 s . c  om
        JsonResponse jsonResponse = authenticatorDAO.enterSyncBeginStatus(username, deviceId);
        exceptionUtil.throwExceptionOnJsonResponseError(jsonResponse);
    } catch (org.apache.commons.httpclient.HttpException httpEx) {
        log.error("Failed the connection to the Json backend", httpEx);
        throw new DaoException(httpEx.getMessage(), httpEx);
    } catch (IOException ioEx) {
        log.error("Failed the connection to the Json backend", ioEx);
        throw new DaoException(ioEx.getMessage(), ioEx);
    }
}