org.apache.http.HttpResponse.getFirstHeader()

Here are the examples of the java api org.apache.http.HttpResponse.getFirstHeader() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

191 Examples 7

19 Source : EntityForwardingRedirectStrategyTests.java
with Apache License 2.0
from vividus-framework

private void mockHeader() {
    Header header = new BasicHeader(LOCATION, REDIRECT_URI);
    when(httpResponse.getFirstHeader(LOCATION)).thenReturn(header);
}

19 Source : HttpComponentsHttpInvokerRequestExecutor.java
with MIT License
from Vip-Augus

/**
 * Determine whether the given response indicates a GZIP response.
 * <p>The default implementation checks whether the HTTP "Content-Encoding"
 * header contains "gzip" (in any casing).
 * @param httpResponse the resulting HttpResponse to check
 * @return whether the given response indicates a GZIP response
 */
protected boolean isGzipResponse(HttpResponse httpResponse) {
    Header encodingHeader = httpResponse.getFirstHeader(HTTP_HEADER_CONTENT_ENCODING);
    return (encodingHeader != null && encodingHeader.getValue() != null && encodingHeader.getValue().toLowerCase().contains(ENCODING_GZIP));
}

19 Source : SentinelApiClient.java
with MIT License
from uhonliu

private String getBody(HttpResponse response) throws Exception {
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    return EnreplacedyUtils.toString(response.getEnreplacedy(), charset != null ? charset : DEFAULT_CHARSET);
}

19 Source : HttpClientTools.java
with Apache License 2.0
from sedmelluq

/**
 * @param response Http response to get the header value from.
 * @param name Name of the header.
 * @return Value if header was present, null otherwise.
 */
public static String getHeaderValue(HttpResponse response, String name) {
    Header header = response.getFirstHeader(name);
    return header != null ? header.getValue() : null;
}

19 Source : AbstractJdkProvider.java
with Apache License 2.0
from raydac

protected void logRateLimitIfPresented(@Nonnull final String resourceUrl, @Nonnull final HttpResponse response) {
    final Log logger = this.mojo.getLog();
    Header rateLimitLimit = response.getFirstHeader("X-RateLimit-Limit");
    if (rateLimitLimit == null) {
        rateLimitLimit = response.getFirstHeader("X-Rate-Limit-Limit");
    }
    Header rateLimitRemaining = response.getFirstHeader("X-RateLimit-Remaining");
    if (rateLimitRemaining == null) {
        rateLimitRemaining = response.getFirstHeader("X-Rate-Limit-Remaining");
    }
    Header rateLimitReset = response.getFirstHeader("X-RateLimit-Reset");
    if (rateLimitReset == null) {
        rateLimitReset = response.getFirstHeader("X-Rate-Limit-Reset");
    }
    final String rateLimitLimitValue = rateLimitLimit == null ? null : rateLimitLimit.getValue().trim();
    final String rateLimitRemainingValue = rateLimitRemaining == null ? null : rateLimitRemaining.getValue().trim();
    final String rateLimitResetValue = rateLimitReset == null ? null : rateLimitReset.getValue().trim();
    long rateLimitLimitLong;
    try {
        rateLimitLimitLong = rateLimitLimitValue == null ? -1L : Long.parseLong(rateLimitLimitValue);
    } catch (NumberFormatException ex) {
        logger.warn(format("Detected unexpected '%s' value in rate limit limit header for '%s'", rateLimitLimitValue, resourceUrl));
        rateLimitLimitLong = -1L;
    }
    long rateLimitRemainingLong;
    try {
        rateLimitRemainingLong = rateLimitRemainingValue == null ? -1L : Long.parseLong(rateLimitRemainingValue);
    } catch (NumberFormatException ex) {
        logger.warn(format("Detected unexpected '%s' value in rate limit remaining header for '%s'", rateLimitRemainingValue, resourceUrl));
        rateLimitRemainingLong = -1L;
    }
    long rateLimitResetLong;
    try {
        rateLimitResetLong = rateLimitResetValue == null ? -1L : Long.parseLong(rateLimitResetValue);
    } catch (NumberFormatException ex) {
        logger.warn(format("Detected unexpected '%s' value in rate limit reset header for '%s'", rateLimitResetValue, resourceUrl));
        rateLimitResetLong = -1L;
    }
    logger.debug(format("Resource '%s', limit-remaning=%d, limit-limit=%d, limit-reset=%d", resourceUrl, rateLimitRemainingLong, rateLimitLimitLong, rateLimitResetLong));
    final String rateLimitResetDate = rateLimitResetLong < 0L ? "UNKNOWN" : new Date(rateLimitResetLong * 1000L).toString();
    if (rateLimitRemainingLong < 0L) {
        logger.debug("Rate limit remaining is not provided");
    } else if (rateLimitRemainingLong == 0L) {
        logger.error(format("Detected zero limit remaining for '%s'! Rate reset expected at '%s'", resourceUrl, rateLimitResetDate));
    } else if (rateLimitRemainingLong < 5L) {
        logger.warn(format("Detected %d limit remaining for '%s'.", rateLimitRemainingLong, resourceUrl));
    } else {
        logger.info(format("Detected %d limit remaining for '%s'.", rateLimitRemainingLong, resourceUrl));
    }
}

19 Source : HttpResponseResource.java
with BSD 2-Clause "Simplified" License
from PushFish

public String getHeaderValue(String name) {
    Header header = response.getFirstHeader(name);
    return header != null ? header.getValue() : null;
}

19 Source : HttpResponseResource.java
with BSD 2-Clause "Simplified" License
from PushFish

private static HashValue getSha1(HttpResponse response, String etag) {
    Header sha1Header = response.getFirstHeader("X-Checksum-Sha1");
    if (sha1Header != null) {
        return new HashValue(sha1Header.getValue());
    }
    // Nexus uses sha1 etags, with a constant prefix
    // e.g {SHA1{b8ad5573a5e9eba7d48ed77a48ad098e3ec2590b}}
    if (etag != null && etag.startsWith("{SHA1{")) {
        String hash = etag.substring(6, etag.length() - 2);
        return new HashValue(hash);
    }
    return null;
}

19 Source : HttpResponseResource.java
with BSD 2-Clause "Simplified" License
from PushFish

private static String getEtag(HttpResponse response) {
    Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
    return etagHeader == null ? null : etagHeader.getValue();
}

19 Source : PersoniumResponse.java
with Apache License 2.0
from personium

/**
 * 指定したレスポンスヘッダの一覧を取得.
 * @param name 取得するレスポンスヘッダ名
 * @return レスポンスヘッダ一覧
 */
public final String getFirstHeader(String name) {
    try {
        return response.getFirstHeader(name).getValue();
    } catch (Exception e) {
        return null;
    }
}

19 Source : HttpClientResponseBuilderTest.java
with MIT License
from PawelAdamski

@Test
public void should_add_header_to_response() throws IOException {
    HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");
    httpClientMock.onPost("/login").doReturn("foo").withHeader("tracking", "123").doReturn("foo").withHeader("tracking", "456");
    HttpResponse first = httpClientMock.execute(httpPost("http://localhost:8080/login"));
    HttpResponse second = httpClientMock.execute(httpPost("http://localhost:8080/login"));
    replacedertThat(first.getFirstHeader("tracking").getValue(), equalTo("123"));
    replacedertThat(second.getFirstHeader("tracking").getValue(), equalTo("456"));
}

19 Source : OAuthClientUtil.java
with Eclipse Public License 1.0
from OpenLiberty

String getErrorDescriptionFromAuthenticateHeader(HttpResponse response) {
    // WWW-Authenticate: Bearer error=invalid_token,
    // error_description=CWWKS1617E: A userinfo request was made
    // with an access token that was not recognized. The request
    // URI was /oidc/endpoint/OidcConfigSample/userinfo.
    Header header = response.getFirstHeader("WWW-Authenticate");
    String jresponse = header == null ? null : header.getValue();
    return extractErrorDescription(jresponse);
}

19 Source : AbstractItemApiTest.java
with Apache License 2.0
from openequella

protected ObjectNode createItem(String json, String token, Object... paramNameValues) throws IOException {
    HttpResponse response = posreplacedem(json, token, paramNameValues);
    replacedertResponse(response, 201, "Should have created the item");
    String itemUri = response.getFirstHeader("Location").getValue();
    return gereplacedem(itemUri, null, token);
}

19 Source : AbstractEntityApiTest.java
with Apache License 2.0
from openequella

protected ObjectNode createSchemaObject(String json, String token) throws IOException {
    HttpResponse response = postEnreplacedy(json, context.getBaseUrl() + "api/schema", token, true);
    replacedertResponse(response, 201, "Should have created the schema");
    String schemaUri = response.getFirstHeader("Location").getValue();
    return (ObjectNode) getEnreplacedy(schemaUri, token);
}

19 Source : AbstractEntityApiTest.java
with Apache License 2.0
from openequella

protected ObjectNode createCollectionObject(String json, String token) throws IOException {
    HttpResponse response = postEnreplacedy(json, context.getBaseUrl() + "api/collection", token, true);
    replacedertResponse(response, 201, "Should have created the collection");
    String collectionUri = response.getFirstHeader("Location").getValue();
    return (ObjectNode) getEnreplacedy(collectionUri, token);
}

19 Source : AbstractEntityApiTest.java
with Apache License 2.0
from openequella

protected ObjectNode createWorkflowObject(String json, String token) throws IOException {
    HttpResponse response = postEnreplacedy(json, context.getBaseUrl() + "api/workflow", token, true);
    replacedertResponse(response, 201, "Should have created the workflow");
    String workflowUri = response.getFirstHeader("Location").getValue();
    ObjectNode workflow = (ObjectNode) getEnreplacedy(workflowUri, token);
    workflows.add(getUuid(workflow));
    return workflow;
}

19 Source : TaxonomyApiTest.java
with Apache License 2.0
from openequella

private String createTerm(String taxonomyUuid, @Nullable String termUuid, String term, @Nullable String parentTermUuid, int index) throws IOException {
    final String uri = PathUtils.urlPath(context.getBaseUrl(), API_TAXONOMY_PATH, taxonomyUuid, API_TERM_PATH_PART);
    final ObjectNode jsonObj = mapper.createObjectNode();
    jsonObj.put("uuid", termUuid);
    jsonObj.put("term", term);
    jsonObj.put("parentUuid", parentTermUuid);
    if (index >= 0) {
        jsonObj.put("index", index);
    }
    final String jsonStr = jsonObj.toString();
    final HttpResponse response = postEnreplacedy(jsonStr, uri, getToken(), true);
    replacedertResponse(response, 201, "failed to create term");
    return response.getFirstHeader("Location").getValue();
}

19 Source : TaxonomyApiTest.java
with Apache License 2.0
from openequella

private String addDatum(String taxonomyUuid, String termUuid, String key, String value, boolean create) throws IOException {
    final String uri = PathUtils.urlPath(context.getBaseUrl(), API_TAXONOMY_PATH, taxonomyUuid, API_TERM_PATH_PART, termUuid, API_TERM_DATA_PATH_PART, URLEncoder.encode(key, "utf-8").replace("+", "%20"), URLEncoder.encode(value, "utf-8").replace("+", "%20"));
    final HttpResponse response = putEnreplacedy(null, uri, getToken(), true);
    replacedertResponse(response, create ? 201 : 200, "failed to create term data");
    return response.getFirstHeader("Location").getValue();
}

19 Source : ItemApiRelationTest.java
with Apache License 2.0
from openequella

private String createRelation(String itemUri, String token, ItemId fromId, ItemId toId, String type) throws IOException {
    ObjectNode relation = mapper.createObjectNode();
    relation.put("relation", type);
    if (fromId != null) {
        relation.put("from", createItemRef(fromId));
    }
    if (toId != null) {
        relation.put("to", createItemRef(toId));
    }
    HttpResponse response = postEnreplacedy(relation.toString(), itemUri + "relation", token, true);
    replacedertResponse(response, 201, "Should be able to create relation");
    return response.getFirstHeader("Location").getValue();
}

19 Source : FileApiTest.java
with Apache License 2.0
from openequella

@Test
public void testNestedFolders() throws Exception {
    // As per http://dev.equella.com/issues/6245
    // create staging
    HttpResponse response = execute(new HttpPost(context.getBaseUrl() + "api/file/"), true);
    replacedertResponse(response, 201, "201 not returned from staging creation");
    // extract Location and do a get
    final String stagingDirUrl = response.getFirstHeader("Location").getValue();
    // create a triple nested folder
    response = execute(new HttpPut(stagingDirUrl + "/f1/f2/f3"), true);
    replacedertResponse(response, 201, "201 not returned from f3 creation");
    // extract Location and do a get
    final String f3Location = response.getFirstHeader("Location").getValue();
    // Get it, check the links
    response = execute(new HttpGet(f3Location), false);
    replacedertResponse(response, 200, "200 not returned from f3 GET");
    final ObjectNode f3Node = readJson(mapper, response);
    String f3DirLink = getLink(f3Node, "dir");
    replacedertEquals("f3 Location and dir link mismatch", f3Location, f3DirLink);
    // Get the parent, check f3 is in folders
    final String f3ParentLoc = getLink((ObjectNode) f3Node.get("parent"), "self");
    final String f3ParentContentLoc = getLink((ObjectNode) f3Node.get("parent"), "content");
    // ensure parent loc is /f1/f2
    replacedertEquals("f3 parent dir location is wrong", stagingDirUrl + "/f1/f2", f3ParentLoc);
    // get the parent parent (ie f1)
    response = execute(new HttpGet(f3ParentLoc), false);
    replacedertResponse(response, 200, "200 not returned from f3ParentLoc GET");
    final ObjectNode f2Node = readJson(mapper, response);
    final String f2ParentLoc = getLink((ObjectNode) f2Node.get("parent"), "self");
    final String f2ParentContentLoc = getLink((ObjectNode) f2Node.get("parent"), "content");
    // Upload a file to f1
    final File file = new File(AbstractPage.getPathFromUrl(Attachments.get(TEST_FILE)));
    response = execute(getPut(f2ParentContentLoc + "/" + URLUtils.urlEncode(TEST_FILE, false), file), true);
    replacedertResponse(response, 201, "201 not returned from PUT file");
    // GET f1, check the file is in f1.files
    response = execute(new HttpGet(f2ParentLoc), false);
    replacedertResponse(response, 200, "200 not returned from f2ParentLoc GET");
    final ObjectNode f1Node = readJson(mapper, response);
    ObjectNode myfileNode = findFile(f1Node, TEST_FILE);
    // replacedertEquals("filename", TEST_FILE, myfileNode.get("filename").asText()); <-- redundant
    // TODO: check links
    // Upload a file to f2
    response = execute(getPut(f3ParentContentLoc + "/" + URLUtils.urlEncode(TEST_FILE, false), file), true);
    replacedertResponse(response, 201, "201 not returned from PUT file");
    // Do a deep GET, check all files and folders
    ObjectNode deepRoot = (ObjectNode) getEnreplacedy(stagingDirUrl, null, "deep", true);
    // get folder f1
    ObjectNode f1DeepNode = findFolder(deepRoot, "f1");
    // ensure file TEST_FILE
    ObjectNode myfile1DeepNode = findFile(f1DeepNode, TEST_FILE);
    // check links
    String myfile1LinkSelf = getLink(myfile1DeepNode, "self");
    replacedertEquals("file1 self link wrong", stagingDirUrl + "/f1/" + URLUtils.urlEncode(TEST_FILE, false), myfile1LinkSelf);
    String myfile1LinkDir = getLink(myfile1DeepNode, "dir");
    replacedertEquals("file1 dir link wrong", stagingDirUrl + "/f1/" + URLUtils.urlEncode(TEST_FILE, false), myfile1LinkDir);
    String myfile1LinkContent = getLink(myfile1DeepNode, "content");
    replacedertTrue("file1 content link wrong", myfile1LinkContent.endsWith("content/f1/" + URLUtils.urlEncode(TEST_FILE, false)));
    // get folder f2
    ObjectNode f2DeepNode = findFolder(f1DeepNode, "f2");
    // TODO: ensure file TEST_FILE
    // TODO: check links
    // get folder f3
    ObjectNode f3DeepNode = findFolder(f2DeepNode, "f3");
    // ensure no files and folders
    replacedertTrue("f3 files not empty", getArray(f3DeepNode, "files").size() == 0);
    replacedertTrue("f3 folders not empty", getArray(f3DeepNode, "folders").size() == 0);
// TODO: check links
}

19 Source : HttpResponseWrapper.java
with Educational Community License v2.0
from opencast

@Override
public Header getFirstHeader(String s) {
    return response.getFirstHeader(s);
}

19 Source : PostRequest.java
with GNU General Public License v2.0
from mguessan

public Header getResponseHeader(String name) {
    checkResponse();
    return response.getFirstHeader(name);
}

19 Source : EWSMethod.java
with GNU General Public License v2.0
from mguessan

@Override
public EWSMethod handleResponse(HttpResponse response) {
    this.response = response;
    org.apache.http.Header contentTypeHeader = response.getFirstHeader("Content-Type");
    if (contentTypeHeader != null && "text/xml; charset=utf-8".equals(contentTypeHeader.getValue())) {
        try (InputStream inputStream = response.getEnreplacedy().getContent()) {
            if (HttpClientAdapter.isGzipEncoded(response)) {
                processResponseStream(new GZIPInputStream(inputStream));
            } else {
                processResponseStream(inputStream);
            }
        } catch (IOException e) {
            LOGGER.error("Error while parsing soap response: " + e, e);
        }
    }
    return this;
}

19 Source : HttpRequestClient.java
with Apache License 2.0
from intuit

/**
 * Parses the response headers and returns value for intuit_tid parameter
 *
 * @param response
 * @return String
 * @throws IOException
 */
public static String getIntuitTid(HttpResponse response) throws IOException {
    return response.getFirstHeader("intuit_tid").getValue();
}

19 Source : HttpResponseProxy.java
with Apache License 2.0
from IBM

@Override
public Header getFirstHeader(final String name) {
    return original.getFirstHeader(name);
}

19 Source : DatarouterHttpResponse.java
with Apache License 2.0
from hotpads

public Header getFirstHeader(String name) {
    return response.getFirstHeader(name);
}

19 Source : ServerResponse.java
with Mozilla Public License 2.0
from hashicorp

/**
 * Returns the value of the @{code X-Nomad-Index} header.
 *
 * @throws ResponseHeaderException if the header is missing or cannot be parsed
 * @see <a href="https://www.nomadproject.io/docs/http/#blocking-queries">Blocking Queries</a>
 */
public BigInteger getIndex() throws ResponseHeaderException {
    String stringValue = httpResponse.getFirstHeader(X_NOMAD_INDEX).getValue();
    try {
        return new BigInteger(stringValue);
    } catch (NumberFormatException e) {
        throw ResponseHeaderException.parsing(X_NOMAD_INDEX, stringValue, e);
    }
}

19 Source : InstrumentApacheHttpResponseHandlerTest.java
with Apache License 2.0
from firebase

private static HttpResponse mockHttpResponse() {
    HttpResponse response = mock(HttpResponse.clreplaced);
    StatusLine statusLine = new StatusLine() {

        @Override
        public ProtocolVersion getProtocolVersion() {
            return null;
        }

        @Override
        public int getStatusCode() {
            return 200;
        }

        @Override
        public String getReasonPhrase() {
            return null;
        }
    };
    BasicHeader header = new BasicHeader("content-length", "256");
    when(response.getFirstHeader("content-length")).thenReturn(header);
    BasicHeader header1 = new BasicHeader("content-type", "text/html");
    when(response.getFirstHeader("content-type")).thenReturn(header1);
    when(response.getStatusLine()).thenReturn(statusLine);
    return response;
}

19 Source : FirebasePerfHttpClientTest.java
with Apache License 2.0
from firebase

private HttpResponse mockHttpResponse() {
    HttpResponse response = mock(HttpResponse.clreplaced);
    StatusLine statusLine = new StatusLine() {

        @Override
        public ProtocolVersion getProtocolVersion() {
            return null;
        }

        @Override
        public int getStatusCode() {
            return 200;
        }

        @Override
        public String getReasonPhrase() {
            return null;
        }
    };
    BasicHeader header = new BasicHeader("content-length", "256");
    when(response.getFirstHeader("content-length")).thenReturn(header);
    BasicHeader header1 = new BasicHeader("content-type", "text/html");
    when(response.getFirstHeader("content-type")).thenReturn(header1);
    when(response.getStatusLine()).thenReturn(statusLine);
    return response;
}

19 Source : GitLabOAuthAuthenticator.java
with Apache License 2.0
from finos

private String getLocationHeaderValue(HttpResponse response) {
    Header locationHeader = response.getFirstHeader("location");
    return (locationHeader == null) ? null : locationHeader.getValue();
}

19 Source : CacheHeaderTest.java
with Apache License 2.0
from apache

// test ETag
@Override
protected void doETag(String method) throws Exception {
    HttpRequestBase get = getSelectMethod(method);
    HttpResponse response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("Got no response code 200 in initial request", 200, response.getStatusLine().getStatusCode());
    Header head = response.getFirstHeader("ETag");
    replacedertNotNull("We got no ETag in the response", head);
    replacedertTrue("Not a valid ETag", head.getValue().startsWith("\"") && head.getValue().endsWith("\""));
    String etag = head.getValue();
    // If-None-Match tests
    // we set a non matching ETag
    get = getSelectMethod(method);
    get.addHeader("If-None-Match", "\"xyz123456\"");
    response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("If-None-Match: Got no response code 200 in response to non matching ETag", 200, response.getStatusLine().getStatusCode());
    // now we set matching ETags
    get = getSelectMethod(method);
    get.addHeader("If-None-Match", "\"xyz1223\"");
    get.addHeader("If-None-Match", "\"1231323423\", \"1211211\",   " + etag);
    response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("If-None-Match: Got no response 304 to matching ETag", 304, response.getStatusLine().getStatusCode());
    // we now set the special star ETag
    get = getSelectMethod(method);
    get.addHeader("If-None-Match", "*");
    response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("If-None-Match: Got no response 304 for star ETag", 304, response.getStatusLine().getStatusCode());
    // If-Match tests
    // we set a non matching ETag
    get = getSelectMethod(method);
    get.addHeader("If-Match", "\"xyz123456\"");
    response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("If-Match: Got no response code 412 in response to non matching ETag", 412, response.getStatusLine().getStatusCode());
    // now we set matching ETags
    get = getSelectMethod(method);
    get.addHeader("If-Match", "\"xyz1223\"");
    get.addHeader("If-Match", "\"1231323423\", \"1211211\",   " + etag);
    response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("If-Match: Got no response 200 to matching ETag", 200, response.getStatusLine().getStatusCode());
    // now we set the special star ETag
    get = getSelectMethod(method);
    get.addHeader("If-Match", "*");
    response = getClient().execute(get);
    checkResponseBody(method, response);
    replacedertEquals("If-Match: Got no response 200 to star ETag", 200, response.getStatusLine().getStatusCode());
}

19 Source : CacheHeaderTest.java
with Apache License 2.0
from apache

@Override
protected void doCacheControl(String method) throws Exception {
    if ("POST".equals(method)) {
        HttpRequestBase m = getSelectMethod(method);
        HttpResponse response = getClient().execute(m);
        checkResponseBody(method, response);
        Header head = response.getFirstHeader("Cache-Control");
        replacedertNull("We got a cache-control header in response to POST", head);
        head = response.getFirstHeader("Expires");
        replacedertNull("We got an Expires  header in response to POST", head);
    } else {
        HttpRequestBase m = getSelectMethod(method);
        HttpResponse response = getClient().execute(m);
        checkResponseBody(method, response);
        Header head = response.getFirstHeader("Cache-Control");
        replacedertNotNull("We got no cache-control header", head);
        head = response.getFirstHeader("Expires");
        replacedertNotNull("We got no Expires header in response", head);
    }
}

18 Source : RangeFileAsyncHttpResponseHandler.java
with Apache License 2.0
from yiwent

@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            // already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else {
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                }
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEnreplacedy()));
            }
        }
    }
}

18 Source : Warcs.java
with MIT License
from webis-de

private static HttpEnreplacedy getEnreplacedy(final HttpResponse response, final SessionInputBuffer input) throws HttpException {
    // Adapted from the org.apache.http.impl.BHttpConnectionBase
    final BasicHttpEnreplacedy enreplacedy = new BasicHttpEnreplacedy();
    final long len = new LaxContentLengthStrategy().determineLength(response);
    final InputStream instream = Warcs.createInputStream(len, input);
    if (len == ContentLengthStrategy.CHUNKED) {
        enreplacedy.setChunked(true);
        enreplacedy.setContentLength(-1);
        enreplacedy.setContent(instream);
    } else if (len == ContentLengthStrategy.IDENreplacedY) {
        enreplacedy.setChunked(false);
        enreplacedy.setContentLength(-1);
        enreplacedy.setContent(instream);
    } else {
        enreplacedy.setChunked(false);
        enreplacedy.setContentLength(len);
        enreplacedy.setContent(instream);
    }
    final Header contentTypeHeader = response.getFirstHeader(HTTP.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        enreplacedy.setContentType(contentTypeHeader);
    }
    final Header contentEncodingHeader = response.getFirstHeader(HTTP.CONTENT_ENCODING);
    if (contentEncodingHeader != null) {
        enreplacedy.setContentEncoding(contentEncodingHeader);
    }
    return enreplacedy;
}

18 Source : DownloadCache.java
with GNU General Public License v3.0
from tranleduy2000

/**
 * Saves part of the HTTP Response to the info file.
 */
private void saveInfo(@NonNull String urlString, @NonNull HttpResponse response, @NonNull File info) throws IOException {
    Properties props = new Properties();
    // we don't need the status code & URL right now.
    // Save it in case we want to have it later (e.g. to differentiate 200 and 404.)
    props.setProperty(KEY_URL, urlString);
    props.setProperty(KEY_STATUS_CODE, Integer.toString(response.getStatusLine().getStatusCode()));
    for (String name : INFO_HTTP_HEADERS) {
        Header h = response.getFirstHeader(name);
        if (h != null) {
            props.setProperty(name, h.getValue());
        }
    }
    // $NON-NLS-1$
    mFileOp.saveProperties(info, props, "## Meta data for SDK Manager cache. Do not modify.");
}

18 Source : HttpClientTools.java
with Apache License 2.0
from sedmelluq

public static String getRawContentType(HttpResponse response) {
    Header header = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
    return header != null ? header.getValue() : null;
}

18 Source : SimpleConfidentialRedirectTestCase.java
with Apache License 2.0
from quarkusio

private void sendRequest(TestHttpClient client, String uri) throws IOException {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + uri);
    HttpResponse result = client.execute(get);
    replacedert.replacedertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    replacedert.replacedertEquals("https", result.getFirstHeader("scheme").getValue());
    replacedert.replacedertEquals(uri, result.getFirstHeader("uri").getValue());
    HttpClientUtils.readResponse(result);
}

18 Source : PreCompressedResourceTestCase.java
with Apache License 2.0
from quarkusio

/**
 * Series of replacedertions checking response code, headers and response content
 */
private String replacedertResponse(HttpResponse response, boolean encoding, String compareWith, String extension) throws IOException {
    replacedert.replacedertEquals(StatusCodes.OK, response.getStatusLine().getStatusCode());
    String body = HttpClientUtils.readResponse(response);
    Header[] headers = response.getHeaders(HttpHeaderNames.CONTENT_TYPE);
    replacedert.replacedertEquals("text/html", headers[0].getValue());
    if (encoding) {
        // no other nice way to be sure we get back gzipped content
        replacedert response.getEnreplacedy() instanceof DecompressingEnreplacedy;
    } else {
        replacedert.replacedertNull(response.getFirstHeader(HttpHeaderNames.CONTENT_ENCODING));
    }
    if (compareWith != null) {
        // ignore line ending differences and change inside of html page
        replacedert.replacedertEquals(compareWith.replace("\r", "").replace("web", extension), body.replace("\r", ""));
    }
    return body;
}

18 Source : HttpResponseResource.java
with BSD 2-Clause "Simplified" License
from PushFish

public long getLastModified() {
    Header responseHeader = response.getFirstHeader("last-modified");
    if (responseHeader == null) {
        return 0;
    }
    try {
        return DateUtils.parseDate(responseHeader.getValue()).getTime();
    } catch (Exception e) {
        return 0;
    }
}

18 Source : HttpResponseResource.java
with BSD 2-Clause "Simplified" License
from PushFish

public String getContentType() {
    final Header header = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
    return header == null ? null : header.getValue();
}

18 Source : HttpClientResponseBuilderTest.java
with MIT License
from PawelAdamski

@Test
public void should_return_json_with_right_header() throws IOException {
    HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");
    httpClientMock.onGet("/login").doReturnJSON("{foo:1}", StandardCharsets.UTF_8);
    HttpResponse login = httpClientMock.execute(httpGet("http://localhost:8080/login"));
    replacedertThat(login, hasContent("{foo:1}"));
    replacedertThat(login.getFirstHeader("Content-type").getValue(), equalTo(APPLICATION_JSON.toString()));
}

18 Source : HttpClientResponseBuilderTest.java
with MIT License
from PawelAdamski

@Test
public void should_support_response_with_different_contentType() throws IOException {
    HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");
    httpClientMock.onGet("/json").doReturn("{\"a\":1}", Charset.defaultCharset(), APPLICATION_JSON);
    httpClientMock.onGet("/xml").doReturn("<a>1</a>", Charset.defaultCharset(), APPLICATION_XML);
    HttpResponse jsonResponse = httpClientMock.execute(httpGet("http://localhost:8080/json"));
    HttpResponse xmlResponse = httpClientMock.execute(httpGet("http://localhost:8080/xml"));
    replacedertThat(jsonResponse, hasContent("{\"a\":1}"));
    replacedertThat(jsonResponse.getFirstHeader("Content-type").getValue(), equalTo(APPLICATION_JSON.toString()));
    replacedertThat(ContentType.get(jsonResponse.getEnreplacedy()).toString(), equalTo(APPLICATION_JSON.toString()));
    replacedertThat(xmlResponse, hasContent("<a>1</a>"));
    replacedertThat(xmlResponse.getFirstHeader("Content-type").getValue(), equalTo(APPLICATION_XML.toString()));
    replacedertThat(ContentType.get(xmlResponse.getEnreplacedy()).toString(), equalTo(APPLICATION_XML.toString()));
}

18 Source : StandardProvidersTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests putting and then getting a Reader.
 */
@Test
public void testPutReader() throws Exception {
    HttpPut put = new HttpPut(readerTestUri);
    StringEnreplacedy enreplacedy = new StringEnreplacedy("wxyz", "UTF-8");
    enreplacedy.setContentType("char/array");
    put.setEnreplacedy(enreplacedy);
    HttpResponse resp = httpClient.execute(put);
    replacedertEquals(204, resp.getStatusLine().getStatusCode());
    HttpGet get = new HttpGet(readerTestUri);
    resp = httpClient.execute(get);
    replacedertEquals(200, resp.getStatusLine().getStatusCode());
    String str = replacedtring(resp);
    replacedertEquals("wxyz", str);
    String contentType = (resp.getFirstHeader("Content-Type") == null) ? null : resp.getFirstHeader("Content-Type").getValue();
    replacedertEquals("application/octet-stream", contentType);
    Header contentLengthHeader = resp.getFirstHeader("Content-Length");
    replacedertEquals("4", contentLengthHeader.getValue());
}

18 Source : StandardProvidersTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 */
@Test
public void testReaderAcceptMatchesReturnedContentType() throws Exception {
    HttpPut put = new HttpPut(readerTestUri);
    StringEnreplacedy enreplacedy = new StringEnreplacedy("wxyz", "UTF-8");
    enreplacedy.setContentType("char/array");
    put.setEnreplacedy(enreplacedy);
    HttpResponse resp = httpClient.execute(put);
    replacedertEquals(204, resp.getStatusLine().getStatusCode());
    HttpGet get = new HttpGet(readerTestUri);
    get.addHeader("Accept", "mytype/subtype");
    resp = httpClient.execute(get);
    replacedertEquals(200, resp.getStatusLine().getStatusCode());
    String str = replacedtring(resp);
    replacedertEquals("wxyz", str);
    replacedertEquals("mytype/subtype", resp.getFirstHeader("Content-Type").getValue());
    Header contentLengthHeader = get.getFirstHeader("Content-Length");
    replacedertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
}

18 Source : StandardProvidersTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests putting and then getting a /multivaluedmap.
 */
// @Test
// TODO: This test isn't working: defect 60975 opened to investigate.
public void testMulitValPutReader() throws Exception {
    HttpPut put = new HttpPut(multivalTestUri);
    StringEnreplacedy enreplacedy = new StringEnreplacedy("username=user1&preplacedword=user1preplacedword", "UTF-8");
    // enreplacedy.setContentType("application/x-www-form-urlencoded");
    System.out.println("testMulitValPutReader sending PUT and GET to " + multivalTestUri);
    try {
        HttpResponse resp = httpClient.execute(put);
        // TODO: The HTTP status returned right now is a 415. Investigate why.
        System.out.println("Status code from PUT = " + resp.getStatusLine().getStatusCode());
    // replacedertEquals(204, resp.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
        httpClient = new DefaultHttpClient();
    }
    HttpGet get = new HttpGet(multivalTestUri);
    get.addHeader("Accept", "application/x-www-form-urlencoded");
    HttpResponse getResp = httpClient.execute(get);
    replacedertEquals(200, getResp.getStatusLine().getStatusCode());
    String str = replacedtring(getResp);
    System.out.println("str = " + str);
    replacedertTrue(str, "username=user1&preplacedword=user1preplacedword".equals(str) || "preplacedword=user1preplacedword&username=user1".equals(str));
    replacedertEquals("application/x-www-form-urlencoded", getResp.getFirstHeader("Content-Type").getValue());
    Header contentLengthHeader = getResp.getFirstHeader("Content-Length");
    if (contentLengthHeader != null) {
        // some of the containers can be "smarter" and set the
        // content-length for us if the payload is small
        replacedertEquals("37", contentLengthHeader.getValue());
    }
}

18 Source : StandardProvidersTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests putting and then getting a source.
 */
@Test
public void testPutSource() throws Exception {
    HttpPut put = new HttpPut(srcTestUri);
    StringEnreplacedy enreplacedy = new StringEnreplacedy("<?xml version=\"1.0\" encoding=\"UTF-8\"?><message><user>user1</user><preplacedword>user1pwd</preplacedword></message>", "UTF-8");
    enreplacedy.setContentType("application/xml");
    put.setEnreplacedy(enreplacedy);
    HttpResponse resp = httpClient.execute(put);
    replacedertEquals(204, resp.getStatusLine().getStatusCode());
    HttpGet get = new HttpGet(srcTestUri);
    resp = httpClient.execute(get);
    replacedertEquals(200, resp.getStatusLine().getStatusCode());
    String str = replacedtring(resp);
    replacedertTrue(str, str.contains("<message><user>user1</user><preplacedword>user1pwd</preplacedword></message>"));
    String contentType = (resp.getFirstHeader("Content-Type") == null) ? null : resp.getFirstHeader("Content-Type").getValue();
    replacedertEquals("text/xml", contentType);
    Header contentLengthHeader = resp.getFirstHeader("Content-Length");
    replacedertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
}

18 Source : UserGroupManagementApiTest.java
with Apache License 2.0
from openequella

@Test
public void addAndDeleteGroupTest() throws Exception {
    String token = requestToken(OAUTH_CLIENT_ID);
    String stringified = "{\"name\":\"" + this.getClreplaced().getSimpleName() + "-grp1\"}";
    HttpPost post = getPost(context.getBaseUrl() + API_PATH_GROUP, stringified);
    HttpResponse response = execute(post, true, token);
    // 201 - creation accepted
    replacedertEquals(response.getStatusLine().getStatusCode(), 201, "Unexpected HTTP response from POST");
    Header loc = response.getFirstHeader("Location");
    replacedert.replacedertNotNull(loc, "No location header on group creation response");
    // get all groups created by this test
    JsonNode eponymousGroups = doQuerySearch(API_PATH_GROUP, this.getClreplaced().getSimpleName(), null, token);
    int howManyGroupsToDelete = eponymousGroups.get("available").asInt();
    JsonNode results = eponymousGroups.get("results");
    int deleted = 0;
    while (deleted < howManyGroupsToDelete) {
        JsonNode group = results.get(deleted);
        // sanity check
        replacedert.replacedertTrue(group.get("name").asText().contains(this.getClreplaced().getSimpleName()), "Group search returned a result it shouldn't have!");
        String selfLink = group.get("links").get("self").asText();
        HttpResponse deletionResponse = deleteResource(selfLink, token);
        int deletionCode = deletionResponse.getStatusLine().getStatusCode();
        // 204 : NO_CONTENT - to indicate deletion accepted
        replacedertTrue(deletionCode == 204, "Failed to delete group with name: " + group.get("name").asText() + " - " + deletionCode + " (" + deletionResponse.getStatusLine().getReasonPhrase() + ")");
        ++deleted;
    }
    replacedertTrue(deleted > 0, "Expected to delete " + howManyGroupsToDelete + " groups");
}

18 Source : ScrapbookApiTest.java
with Apache License 2.0
from openequella

private String createScrapbookItem(String type, String filename) throws ClientProtocolException, IOException {
    String stagingUuid = null;
    if (type.equals(TYPE_FILE)) {
        String[] stagingParams = createStaging();
        stagingUuid = stagingParams[0];
        String stagingDirUrl = stagingParams[1];
        uploadFile(stagingDirUrl, filename, Attachments.get(filename));
    }
    ObjectNode node = buildScrapbookItem(type, filename, stagingUuid);
    HttpResponse response = postEnreplacedy(node.toString(), context.getBaseUrl() + "api/scrapbook", getToken(), true);
    replacedertResponse(response, 201, "failed to create scrapbook item");
    return response.getFirstHeader("Location").getValue();
}

18 Source : ItemApiRelationTest.java
with Apache License 2.0
from openequella

private ObjectNode createItem(String token) throws IOException {
    ObjectNode item = mapper.createObjectNode();
    item.with("collection").put("uuid", "9a1ddb24-6bf5-db3d-d8fe-4fca20ecf69c");
    HttpResponse response = posreplacedem(item.toString(), token);
    replacedertResponse(response, 201, "Should be able to create item");
    String itemUri = response.getFirstHeader("Location").getValue();
    return gereplacedem(itemUri, null, token);
}

18 Source : FileListingApiTest.java
with Apache License 2.0
from openequella

private Header getHeaders(String uri, String token, String headerName, Object... params) throws IOException {
    HttpResponse response = execute(new HttpHead(appendQueryString(uri, queryString(params))), false, token);
    return response.getFirstHeader(headerName);
}

18 Source : CourseApiTest.java
with Apache License 2.0
from openequella

/*
  	@Test(dependsOnMethods={"testCannotRePOSTSameCode"})
  	public void testPUTCannotOverwriteCodeInUse() throws Exception
  	{
  		String token = requestToken(OAUTH_CLIENT_ID);
  		URI targetUri = new URI(context.getBaseUrl() + API_TASK_PATH);

  		JsonNode youAgainNode = createAndVerifyCourse(token, COURSE_CODE_SRM114,
  				"in order to attempt to edit", targetUri);

  		replacedertTrue(youAgainNode != null && youAgainNode.get("code").asText().equals(COURSE_CODE_SRM114));

  		JsonNode innocentBystanderCourse = createAndVerifyCourse(token, COURSE_CODE_INNOCENT,
  				"in order to attempt to edit", targetUri);

  		String innocentTrueUuid = innocentBystanderCourse.get("uuid").asText();

  		// we going to use the 'edit' API but sending a JSON object which purports to set a
  		// different uuid, (which would be legal) but attempting to use a code which we know
  		// already exists
  		ObjectNode innocentNodeReally = (ObjectNode)innocentBystanderCourse;
  		innocentNodeReally.put("code", COURSE_CODE_SRM114);
  		innocentNodeReally.put("name", "something seen nowhere else");
  		innocentNodeReally.put("description", "Oh it was gorgeousness and gorgeosity made flesh. "
  				+ "The trombones crunched redgold under my bed, and behind my gulliver the trumpets three-wise silverflamed, "
  				+ "and there by the door the timps rolling through my guts and out again crunched like candy thunder. "
  				+ "Oh, it was wonder of wonders. And then, a bird of like rarest spun heavenmetal, "
  				+ "or like silvery wine flowing in a spaceship, gravity all nonsense now, came the violin solo above all the other strings, "
  				+ "and those strings were like a cage of silk round my bed. Then flute and oboe bored, like worms of like platinum, "
  				+ "into the thick thick toffee gold and silver. I was in such bliss, my brothers."); // Anthony Burgess: A clockwork orange
  		innocentNodeReally.put("from", "2010-03-31");
  		innocentNodeReally.put("until", "2010-12-25");
  		innocentNodeReally.put("students", 31);
  		innocentNodeReally.put("uuid", "deadbeef-f00d-cafe-feed-f0fffadef0ff");

  		String editUrl = targetUri.toString();
  		// I'm purporting to edit the Course created with the code COURSE_CODE_INNOCENT,
  		// by identifying it with its UUID. When editing I attempt to change its code to one I know
  		// already exists (the COURSE_CODE_SRM114). This should fail.
  		editUrl += "/" + innocentTrueUuid;
  		HttpResponse didIorDidntI = getPut(editUrl, innocentBystanderCourse, token);
  		int postResponseCode = didIorDidntI.getStatusLine().getStatusCode();
  		// 400 (bad request) 500 (internal server error)
  		replacedertTrue(postResponseCode == 400 || postResponseCode == 500, "unexpected (" + postResponseCode + ") post response");

  		int purged = purge(token);
  		replacedertEquals( purged, 2, "Expected to purge 2.");
  	}
  */
private JsonNode createAndVerifyCourse(String token, String code, String name, URI uri) throws Exception {
    String jsonStr = buildJsonCourse(code, name, "2014-03-31", "2014-12-25", 31, KNOWN_USER_UUID, null);
    HttpResponse postResponse = postEnreplacedy(jsonStr, uri.toString(), token, true);
    int postResponseCode = postResponse.getStatusLine().getStatusCode();
    // 200 (success) or 201 (created)
    replacedertTrue(postResponseCode == 200 || postResponseCode == 201, "nonsuccess (" + postResponseCode + ") in post response.");
    String loc = postResponse.getFirstHeader("Location").getValue();
    return getEnreplacedy(loc, token);
}

See More Examples