Java Code Examples for org.apache.http.client.methods.HttpUriRequest#getFirstHeader()

The following examples show how to use org.apache.http.client.methods.HttpUriRequest#getFirstHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
    try {
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        CloseableHttpResponse response = client.execute(request);
        Assert.assertNotNull(response.getStatusLine());

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }
        }

        Assert.assertEquals(expectedStatusCode, responseStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 2
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
    try {
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        CloseableHttpResponse response = client.execute(request);
        assertThat(response.getStatusLine()).isNotNull();

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }
        }

        assertThat(responseStatusCode).isEqualTo(expectedStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 3
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
    CloseableHttpResponse response = null;
    try {
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        response = client.execute(request);
        assertThat(response.getStatusLine()).isNotNull();

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null && response.getEntity().getContent() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }
        }

        assertThat(responseStatusCode).isEqualTo(expectedStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 4
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
    try {
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        CloseableHttpResponse response = client.execute(request);
        assertThat(response.getStatusLine()).isNotNull();

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }
        }

        assertThat(responseStatusCode).isEqualTo(expectedStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 5
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
    CloseableHttpResponse response = null;
    try {
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        response = client.execute(request);
        assertThat(response.getStatusLine()).isNotNull();

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }
        }

        assertThat(responseStatusCode).isEqualTo(expectedStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 6
Source File: Utils.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(Object obj) {
    if (!(obj instanceof HttpUriRequest)) {
        return false;
    }
    HttpUriRequest req = (HttpUriRequest) obj;
    for (Header header : headers) {
        Header reqHeader = req.getFirstHeader(header.getName());
        if (reqHeader == null || !reqHeader.getValue().equals(header.getValue())) {
            return false;
        }
    }
    return true;
}
 
Example 7
Source File: RequestDealThread.java    From MediaPlayerProxy with Apache License 2.0 5 votes vote down vote up
private int getRangeStart(HttpUriRequest request) {
	Header rangeHeader = request.getFirstHeader(Constants.RANGE);
	if (rangeHeader != null) {
		String value = rangeHeader.getValue();
		return Integer.valueOf(value.substring(value.indexOf("bytes=") + 6, value.indexOf("-")));
	}
	return 0;
}
 
Example 8
Source File: BaselineClientIdentityTokenResolver.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public List<IdentityToken> resolve(HttpUriRequest input, X509Certificate[] certificateChain) {
    List<IdentityToken> credentials = new ArrayList<IdentityToken>();

    for (SimpleIdentityTokenName securityToken : SimpleIdentityTokenName.values()) {

        Header authHeaderValue = input.getFirstHeader(TOKEN_PREFIX + securityToken.name());
        if (authHeaderValue != null) {
            credentials.add(new IdentityToken(securityToken.name(), authHeaderValue.getValue()));
        }
    }

    return credentials;
}
 
Example 9
Source File: NiFiRequestUtil.java    From knox with Apache License 2.0 4 votes vote down vote up
static HttpUriRequest modifyOutboundRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest) throws IOException {
  // preserve trailing slash from inbound request in the outbound request
  if (inboundRequest.getPathInfo().endsWith("/")) {
    String[] split = outboundRequest.getURI().toString().split("\\?");
    if (!split[0].endsWith("/")) {
      outboundRequest = RequestBuilder.copy(outboundRequest).setUri(split[0] + "/" + (split.length == 2 ? "?" + split[1] : "")).build();
    }
  }
  // update the X-Forwarded-Context header to include the Knox-specific context path
  final Header originalXForwardedContextHeader = outboundRequest.getFirstHeader(NiFiHeaders.X_FORWARDED_CONTEXT);
  if (originalXForwardedContextHeader != null) {
    String xForwardedContextHeaderValue = originalXForwardedContextHeader.getValue();
    if (xForwardedContextHeaderValue != null && !xForwardedContextHeaderValue.isEmpty()) {
      // Inspect the inbound request and outbound request to determine the additional context path from the rewrite
      // rules that needs to be added to the X-Forwarded-Context header to allow proper proxying to NiFi.
      //
      // NiFi does its own URL rewriting, and will not work with the context path provided by Knox
      // (ie, "/gateway/sandbox").
      //
      // For example, if Knox has a rewrite rule "*://*:*/**/nifi-app/{**}?{**}", "/nifi-app" needs to be added
      // to the existing value of the X-Forwarded-Context header, which ends up being "/gateway/sandbox/nifi-app".
      String inboundRequestPathInfo = inboundRequest.getPathInfo();
      String outboundRequestUriPath = outboundRequest.getURI().getPath();
      String outboundRequestUriPathNoTrailingSlash = StringUtils.removeEnd(outboundRequestUriPath, "/");
      String knoxRouteContext = null;
      int index = inboundRequestPathInfo.lastIndexOf(outboundRequestUriPathNoTrailingSlash);
      if (index >= 0) {
        knoxRouteContext = inboundRequestPathInfo.substring(0, index);
      } else {
        Logger.getLogger(NiFiRequestUtil.class.getName()).error(String.format(Locale.ROOT, "Unable to find index of %s in %s", outboundRequestUriPathNoTrailingSlash, inboundRequestPathInfo));
      }
      outboundRequest.setHeader(NiFiHeaders.X_FORWARDED_CONTEXT, xForwardedContextHeaderValue + knoxRouteContext);
    }
  }

  // NiFi requires the header "X-ProxiedEntitiesChain" to be set with the identity or identities of the authenticated requester.
  // The effective principal (identity) in the requester subject must be added to "X-ProxiedEntitiesChain".
  // If the request already has a populated "X-ProxiedEntitiesChain" header, the identities must be appended to it.
  // If the user proxied through Knox is anonymous, the "Anonymous" identity needs to be represented in X-ProxiedEntitiesChain
  // as empty angle brackets "<>".
  final Subject subject = SubjectUtils.getCurrentSubject();
  String effectivePrincipalName = SubjectUtils.getEffectivePrincipalName(subject);
  String proxiedEntitesChainHeader = inboundRequest.getHeader(NiFiHeaders.X_PROXIED_ENTITIES_CHAIN);
  if(proxiedEntitesChainHeader == null) {
    proxiedEntitesChainHeader = "";
  }
  outboundRequest.setHeader(NiFiHeaders.X_PROXIED_ENTITIES_CHAIN, proxiedEntitesChainHeader +
      String.format(Locale.ROOT, "<%s>", "anonymous".equalsIgnoreCase(effectivePrincipalName) ? "" : effectivePrincipalName));

  // Make sure headers named "Cookie" are removed from the request to NiFi, since NiFi does not use cookies.
  Header[] cookieHeaders = outboundRequest.getHeaders("Cookie");
  for (Header cookieHeader : cookieHeaders) {
    outboundRequest.removeHeader(cookieHeader);
  }
  return outboundRequest;
}