Example usage for org.apache.commons.httpclient HttpMethod getStatusLine

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusLine

Introduction

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

Prototype

public abstract StatusLine getStatusLine();

Source Link

Usage

From source file:com.zimbra.qa.unittest.TestPreAuthServlet.java

public void testPreAuthAccountNotActive() throws Exception {
    String user = "user1";
    Account acct = TestUtil.getAccount(user);

    Provisioning prov = Provisioning.getInstance();

    Map<String, Object> attrs = new HashMap<String, Object>();
    attrs.put(Provisioning.A_zimbraAccountStatus, "maintenance");
    prov.modifyAttrs(acct, attrs);//from  w  ww . j av  a 2s.co m

    System.out.println("Before the test:");
    System.out.println(
            Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
    System.out.println();

    String preAuthKey = setUpDomain();
    String preAuthUrl = genPreAuthUrl(preAuthKey, user, false, false);

    System.out.println("preAuthKey=" + preAuthKey);
    System.out.println("preAuth=" + preAuthUrl);

    Server localServer = Provisioning.getInstance().getLocalServer();
    String protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
    String url = protoHostPort + preAuthUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();
        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
        assertEquals(400, statusCode);

    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }

    //revert account status back to active
    attrs = new HashMap<String, Object>();
    attrs.put(Provisioning.A_zimbraAccountStatus, "active");
    prov.modifyAttrs(acct, attrs);

    System.out.println("After the test:");
    System.out.println(
            Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
    System.out.println();
}

From source file:com.isencia.passerelle.model.util.RESTFacade.java

private String invokeMethodForURL(HttpMethod method) {
    try {// w  w  w  . j  a v a  2 s  .  c om
        // Execute the method.
        int statusCode = httpClient.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Response status error : " + method.getStatusLine());
        }

        String response = method.getResponseBodyAsString();
        if (logger.isDebugEnabled()) {
            logger.debug("Received response\n" + response);
        }

        return response;
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
        return null;
    } catch (IOException e) {
        logger.error("Fatal transport error: ", e);
        return null;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:mitm.common.security.ca.handlers.comodo.Tier2PartnerDetails.java

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error Tier2 partner details. Message: " + httpMethod.getStatusLine());
    }//from   w w  w  .  ja  v a2s  . c  om

    InputStream input = httpMethod.getResponseBodyAsStream();

    if (input == null) {
        throw new IOException("Response body is null.");
    }

    /*
     * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
     */
    InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

    String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

    if (logger.isDebugEnabled()) {
        logger.debug("Response:\r\n" + response);
    }

    Map<String, String[]> parameters = NetUtils.parseQuery(response);

    errorCode = CustomClientStatusCode.fromCode(getValue(parameters, "errorCode"));

    if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) {
        error = true;

        errorMessage = getValue(parameters, "errorMessage");
    } else {
        error = false;

        verificationLevel = getValue(parameters, "verificationLevel");
        accountStatus = getValue(parameters, "accountStatus");
        resellerStatus = getValue(parameters, "resellerStatus");
        webHostResellerStatus = getValue(parameters, "webHostResellerStatus");
        epkiStatus = getValue(parameters, "epkiStatus");
        capLiveCCCs = getValue(parameters, "capLiveCCCs");
        peakLiveCCCs = getValue(parameters, "peakLiveCCCs");
        currentLiveCCCs = getValue(parameters, "currentLiveCCCs");
        authorizedDomains = getValue(parameters, "authorizedDomains");
    }
}

From source file:mitm.common.security.ca.handlers.comodo.CollectCustomClientCert.java

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error Collecting certificate. Message: " + httpMethod.getStatusLine());
    }/*w  w w  . j a v a 2 s.  c o m*/

    InputStream input = httpMethod.getResponseBodyAsStream();

    if (input == null) {
        throw new IOException("Response body is null.");
    }

    /*
     * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
     */
    InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

    String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

    if (logger.isDebugEnabled()) {
        logger.debug("Response:\r\n" + response);
    }

    LineNumberReader lineReader = new LineNumberReader(new StringReader(response));

    String statusParameter = lineReader.readLine();

    errorCode = CustomClientStatusCode.fromCode(statusParameter);

    if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) {
        error = true;

        errorMessage = lineReader.readLine();
    } else {
        error = false;

        if (errorCode == CustomClientStatusCode.CERTIFICATES_ATTACHED) {
            /*
             * The certificate is base64 encoded between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----
             */

            StrBuilder base64 = new StrBuilder(4096);

            /* 
             * Skip -----BEGIN CERTIFICATE-----
             */
            String line = lineReader.readLine();

            if (!"-----BEGIN CERTIFICATE-----".equalsIgnoreCase(line)) {
                throw new IOException("-----BEGIN CERTIFICATE----- expected but got: " + line);
            }

            do {
                line = lineReader.readLine();

                if ("-----END CERTIFICATE-----".equalsIgnoreCase(line)) {
                    break;
                }

                if (line != null) {
                    base64.append(line);
                }
            } while (line != null);

            try {
                byte[] decoded = Base64.decodeBase64(MiscStringUtils.toAsciiBytes(base64.toString()));

                Collection<X509Certificate> certificates = CertificateUtils
                        .readX509Certificates(new ByteArrayInputStream(decoded));

                if (certificates != null && certificates.size() > 0) {
                    certificate = certificates.iterator().next();
                }
            } catch (CertificateException e) {
                throw new IOException(e);
            } catch (NoSuchProviderException e) {
                throw new IOException(e);
            }
        }
    }
}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * Does the HTTP call and returns the response body as a string, or throws and HttpException.
 *
 * @param method The HttpMethod to call.
 * @return Response body as a string.// w ww . java  2 s . c o  m
 * @throws IOException  if any communication exception occurs.
 * @throws HttpException If HttpStatus is NOT SC_OK, an HttpException is thrown with the error.
 */
protected String doHttpCall(HttpMethod method) throws IOException, HttpException {
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        throw new HttpException(
                "Method failed: " + method.getStatusLine() + " Response:" + method.getResponseBodyAsString());
    }
    return method.getResponseBodyAsString();
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

private void logResponseInfo(HttpMethod method) throws IOException {
    if (!mDebugEnabled) {
        return;//w w w . j av  a2s . c o  m
    }
    StringBuilder responseLog = new StringBuilder();
    responseLog.append("WebDAV response:\n").append(method.getStatusLine()).append('\n');
    Header headers[] = method.getResponseHeaders();
    if (headers != null && headers.length > 0) {
        for (Header hdr : headers) {
            String hdrName = hdr.getName();
            responseLog.append(hdrName).append('=');
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                responseLog.append("*** REPLACED ***\n");
            } else {
                responseLog.append(hdr.getValue()).append('\n');
            }
        }
    }
    if (method.getResponseBody() == null || !ZimbraLog.dav.isTraceEnabled()) {
        ZimbraLog.dav.debug(responseLog.toString());
    } else {
        ZimbraLog.dav.debug("%s\n%s", responseLog.toString(), new String(method.getResponseBody(), "UTF-8"));
    }
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

private static int executeHttpMethod(HttpMethod method) throws Exception {
    HttpClient client = new HttpClient();
    int statusCode;
    try {/*from  ww  w.  j av  a  2 s .  c o  m*/
        statusCode = client.executeMethod(method);
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        e.printStackTrace();
        throw e;
    }
    if (statusCode != HttpStatus.SC_OK) {
        // QQQ For now, we are indeed assuming we get back JSON errors.
        // In future this may be changed depending on the requested
        // output format sent to the servlet.
        String errorBody = method.getResponseBodyAsString();
        JSONObject result = new JSONObject(errorBody);
        String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"),
                result.getString("stacktrace") };
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, errors[2]);
        throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: " + method.getStatusLine()
                + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]);
    }
    return statusCode;
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private HTTPResponse convertResponse(HttpMethod method) {
    Headers headers = new Headers();
    for (Header header : method.getResponseHeaders()) {
        headers = headers.add(header.getName(), header.getValue());
    }//from w  w w .j  a v a  2 s  .c o  m
    InputStream stream = null;
    HTTPResponse response;
    try {
        stream = getInputStream(method);
        StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()),
                Status.valueOf(method.getStatusCode()), method.getStatusText());
        response = responseCreator.createResponse(line, headers, stream);
    } finally {
        if (stream == null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpStreamResponse createStreamResponse(HttpMethod method) throws IOException {

    StatusLine statusLine = method.getStatusLine();
    String filename = getFileName(method);
    long length = getContentLength(method);
    String contentType = getContentType(method);

    HttpStreamResponse streamResponse = new HttpStreamResponse(statusLine.getStatusCode(),
            statusLine.getReasonPhrase(), method.getResponseBodyAsStream(), filename, contentType, length);
    return streamResponse;
}

From source file:br.com.edu.dbpediaspotlight.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {
    String response = null;//from w w  w. ja  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.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}