Example usage for org.apache.commons.httpclient StatusLine getStatusCode

List of usage examples for org.apache.commons.httpclient StatusLine getStatusCode

Introduction

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

Prototype

public final int getStatusCode() 

Source Link

Usage

From source file:is.landsbokasafn.deduplicator.indexer.WarcFileIterator.java

protected static CrawlDataItem processResponse(WARCRecord record, ArchiveRecordHeader header)
        throws IOException {
    CrawlDataItem cdi = new CrawlDataItem();
    cdi.setURL(header.getUrl());/* w ww.  ja  v  a 2s.c om*/
    cdi.setContentDigest((String) header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST));
    cdi.setRevisit(false);
    cdi.setTimestamp(header.getDate());
    cdi.setWarcRecordId((String) header.getHeaderValue(WARCConstants.HEADER_KEY_ID));

    // Process the HTTP header, if any
    byte[] statusBytes = HttpParser.readRawLine(record);
    int eolCharCount = getEolCharsCount(statusBytes);
    if (eolCharCount > 0) {
        String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount,
                WARCConstants.DEFAULT_ENCODING);
        if ((statusLine != null) && StatusLine.startsWithHTTP(statusLine)) {
            StatusLine status = new StatusLine(statusLine);
            cdi.setStatusCode(status.getStatusCode());
            Header[] headers = HttpParser.parseHeaders(record, WARCConstants.DEFAULT_ENCODING);
            for (Header h : headers) {
                if (h.getName().equalsIgnoreCase("Content-Type")) {
                    cdi.setMimeType(h.getValue());
                } else if (h.getName().equalsIgnoreCase("ETag")) {
                    cdi.setEtag(h.getValue());
                }
            }
        }
    }

    return cdi;
}

From source file:com.springsource.insight.plugin.apache.http.hc3.HttpPlaceholderMethod.java

@Override
public int getStatusCode() {
    StatusLine st = getStatusLine();
    return st.getStatusCode();
}

From source file:com.jivesoftware.os.jive.utils.shell.utils.Curl.java

public String curl(String path) throws IOException {
    GetMethod method = new GetMethod(path);
    byte[] responseBody;
    StatusLine statusLine;
    try {//from  w w w .  j a v  a  2 s .  co m
        client.executeMethod(method);

        responseBody = method.getResponseBody();
        statusLine = method.getStatusLine();
        if (statusLine.getStatusCode() == 200) {
            return new String(responseBody);
        } else {
            return null;
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:com.springsource.insight.plugin.apache.http.hc3.HttpPlaceholderMethodTest.java

@Test
public void testPlaceholderMethodContents() throws URIException {
    assertEquals("Mismatched method", HttpClientDefinitions.PLACEHOLDER_METHOD_NAME,
            HttpPlaceholderMethod.PLACEHOLDER.getName());
    assertEquals("Mismatched URI", HttpClientDefinitions.PLACEHOLDER_URI_VALUE,
            String.valueOf(HttpPlaceholderMethod.PLACEHOLDER.getURI()));

    StatusLine statusLine = HttpPlaceholderMethod.PLACEHOLDER.getStatusLine();
    assertEquals("Mismatched HTTP version", "HTTP/1.1", statusLine.getHttpVersion());
    assertEquals("Mismatched status code", 500, statusLine.getStatusCode());
}

From source file:flex.messaging.services.http.proxy.SecurityFilter.java

private void sendSecurityInfo(ProxyContext context) {
    Target target = context.getTarget();
    String targetHost = target.getUrl().getHost();

    int statusCode = 200;

    boolean customAuth = target.useCustomAuthentication();

    StatusLine statusLine = context.getHttpMethod().getStatusLine();
    if (statusLine != null) {
        statusCode = statusLine.getStatusCode();
    }// w ww.j  av  a2s . co  m

    context.setStatusCode(statusCode);

    if (statusCode == 401 || statusCode == 403) {
        if (!customAuth) {
            if (!context.isHttpRequest()) {
                throw new ProxyException(NO_BASIC_NOT_HTTP);
            } else if (context.isSoapRequest()) {
                // Note: if we remove this error, must do the proxyDomain/targetHost check as done above
                throw new ProxyException(NO_BASIC_FOR_SOAP);
            } else {
                // Don't allow a 401 (and 403, although this should never happen) to be sent to the client
                // if the service is not using custom authentication and the domains do not match

                if (!context.isLocalDomainAndPort()) {
                    HttpServletRequest clientRequest = FlexContext.getHttpRequest();

                    String errorMessage = ProxyConstants.DOMAIN_ERROR + " . The proxy domain:port is "
                            + clientRequest.getServerName() + ":" + clientRequest.getServerPort()
                            + " and the target domain:port is " + targetHost + ":" + target.getUrl().getPort();

                    Log.getLogger(HTTPProxyService.LOG_CATEGORY).error(errorMessage);

                    throw new ProxyException(DOMAIN_ERROR);
                } else {
                    //For BASIC Auth, send back the status code
                    HttpServletResponse clientResponse = FlexContext.getHttpResponse();
                    clientResponse.setStatus(statusCode);
                }
            }
        } else {
            String message = null;
            if (statusLine != null)
                message = statusLine.toString();

            if (statusCode == 401) {
                ProxyException se = new ProxyException();
                se.setCode("Client.Authentication");
                if (message == null) {
                    se.setMessage(LOGIN_REQUIRED);
                } else {
                    se.setMessage(EMPTY_ERROR, new Object[] { message });
                }

                Header header = context.getHttpMethod().getResponseHeader(ProxyConstants.HEADER_AUTHENTICATE);
                if (header != null)
                    se.setDetails(header.getValue());
                throw se;
            } else {
                ProxyException se = new ProxyException();
                se.setCode("Client.Authentication");
                if (message == null) {
                    se.setMessage(UNAUTHORIZED_ERROR);
                } else {
                    se.setMessage(EMPTY_ERROR, new Object[] { message });
                }
                throw se;
            }
        }
    }
}

From source file:dk.netarkivet.wayback.batch.copycode.NetarchiveSuiteWARCRecordToSearchResultAdapter.java

private CaptureSearchResult adaptWARCHTTPResponse(CaptureSearchResult result, WARCRecord rec)
        throws IOException {

    ArchiveRecordHeader header = rec.getHeader();
    // need to parse the documents HTTP message and headers here: WARCReader
    // does not implement this... yet..

    byte[] statusBytes = HttpParser.readRawLine(rec);
    int eolCharCount = getEolCharsCount(statusBytes);
    if (eolCharCount <= 0) {
        throw new RecoverableIOException("Failed to read http status where one " + " was expected: "
                + ((statusBytes == null) ? "(null)" : new String(statusBytes)));
    }//from  ww w  .j a v  a 2s. c  o m
    String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount,
            ARCConstants.DEFAULT_ENCODING);
    if ((statusLine == null) || !StatusLine.startsWithHTTP(statusLine)) {
        throw new RecoverableIOException("Failed parse of http status line.");
    }
    StatusLine status = new StatusLine(statusLine);
    result.setHttpCode(String.valueOf(status.getStatusCode()));

    Header[] headers = HttpParser.parseHeaders(rec, ARCConstants.DEFAULT_ENCODING);

    annotater.annotateHTTPContent(result, rec, headers, header.getMimetype());

    return result;
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

private void readHttpResponse(InputStream proxyInput) throws IOException, CommandException {
    String statusLineText = HttpParser.readLine(proxyInput, HTTP_ENTITY_CHARSET);
    StatusLine statusLine = new StatusLine(statusLineText);
    if (statusLine.getStatusCode() != HttpServletResponse.SC_OK) {
        String message = Integer.toString(statusLine.getStatusCode());
        String reasonPhrase = statusLine.getReasonPhrase();
        if (reasonPhrase != null && !reasonPhrase.isEmpty()) {
            message += ": " + reasonPhrase;
        }//from www.  jav  a2s . c om
        throw new CommandException(-1, message);
    }
    Header[] parsedHeaders = HttpParser.parseHeaders(proxyInput, HTTP_ENTITY_CHARSET);
    HeaderGroup headerGroup = new HeaderGroup();
    headerGroup.setHeaders(parsedHeaders);

    Header transferEncoding = headerGroup.getFirstHeader("Transfer-Encoding");
    if (transferEncoding == null || !transferEncoding.getValue().equals("chunked")) {
        throw new IOException("Expected Transfer-Encoding of \"chunked\" but received " + transferEncoding);
    }
    Header contentType = headerGroup.getFirstHeader("Content-Type");
    if (contentType == null || !contentType.getValue().equals(MIME_TYPE_APPLICATION_OCTET_STREAM)) {
        throw new IOException("Unexpected Content-Type " + contentType);
    }
}

From source file:colt.nicity.performance.latent.http.ApacheHttpClient.java

HttpResponse execute(HttpMethod method) throws IOException {

    applyHeadersCommonToAllRequests(method);

    byte[] responseBody;
    StatusLine statusLine;
    try {/* w  w w .j a va  2  s  .  com*/
        client.executeMethod(method);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            copyLarge(responseBodyAsStream, outputStream, new byte[1024 * 4]);
        }

        responseBody = outputStream.toByteArray();
        statusLine = method.getStatusLine();

        // Catch exception and log error here? or silently fail?
    } finally {
        method.releaseConnection();
    }

    return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);
}

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:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse execute(HttpMethod method) throws IOException {
    if (isOauthEnabled) {
        signWithOAuth(method);// w  ww. j  a  v a 2  s  .c  o  m
    }

    applyHeadersCommonToAllRequests(method);

    byte[] responseBody;
    StatusLine statusLine = null;
    LOG.startTimer(TIMER_NAME);
    try {

        client.executeMethod(method);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            IOUtils.copy(responseBodyAsStream, outputStream);
        }

        responseBody = outputStream.toByteArray();
        statusLine = method.getStatusLine();

        return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);

    } finally {
        method.releaseConnection();
        LOG.stopTimer(TIMER_NAME);
    }
}