Java Code Examples for org.apache.http.HttpRequest#getHeaders()

The following examples show how to use org.apache.http.HttpRequest#getHeaders() . 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: HttpBasicPassTicketSchemeTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
void givenJwtInCookie_whenApplyToRequest_thenJwtIsRemoved() {
    AuthenticationCommand command = getPassTicketCommand();
    HttpRequest httpRequest = new HttpGet();
    httpRequest.setHeader("cookie",
        authConfigurationProperties.getCookieProperties().getCookieName() + "=jwt;" +
        "abc=def"
    );

    command.applyToRequest(httpRequest);

    Header[] headers = httpRequest.getHeaders("cookie");
    assertNotNull(headers);
    assertEquals(1, headers.length);
    assertEquals("abc=def", headers[0].getValue());
}
 
Example 2
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
private boolean explicitFreshnessRequest(HttpRequest request,
		HttpCacheEntry entry, Date now) {
	for (Header h : request.getHeaders("Cache-Control")) {
		for (HeaderElement elt : h.getElements()) {
			if ("max-stale".equals(elt.getName())) {
				try {
					int maxstale = Integer.parseInt(elt.getValue());
					long age = validityPolicy.getCurrentAgeSecs(entry, now);
					long lifetime = validityPolicy
							.getFreshnessLifetimeSecs(entry);
					if (age - lifetime > maxstale)
						return true;
				} catch (NumberFormatException nfe) {
					return true;
				}
			} else if ("min-fresh".equals(elt.getName())
					|| "max-age".equals(elt.getName())) {
				return true;
			}
		}
	}
	return false;
}
 
Example 3
Source File: ApacheHttpClientTagAdapter.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable List<String> getHeaderMultipleValue(@Nullable HttpRequest request, @NotNull String headerKey) {
    if (request == null) {
        return null;
    }

    Header[] matchingHeaders = request.getHeaders(headerKey);

    if (matchingHeaders == null || matchingHeaders.length == 0) {
        return null;
    }

    List<String> returnList = new ArrayList<>(matchingHeaders.length);
    for (Header header : matchingHeaders) {
        returnList.add(header.getValue());
    }

    return returnList;
}
 
Example 4
Source File: HttpRequestHelper.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the target host as defined in the Host header or extracted from the request URI.
 * 
 * Usefull to generate Host header in a HttpRequest
 * 
 * @param request
 * @return the host formatted as host:port
 */
public static HttpHost getHost(HttpRequest request) {
    HttpHost httpHost = UriUtils.extractHost(request.getRequestLine().getUri());
    String scheme = httpHost.getSchemeName();
    String host = httpHost.getHostName();
    int port = httpHost.getPort();
    Header[] headers = request.getHeaders(HttpHeaders.HOST);
    if (headers != null && headers.length != 0) {
        String headerValue = headers[0].getValue();
        String[] splitted = headerValue.split(":");
        host = splitted[0];
        if (splitted.length > 1) {
            port = Integer.parseInt(splitted[1]);
        } else {
            port = -1;
        }
    }
    return new HttpHost(host, port, scheme);
}
 
Example 5
Source File: CachedResponseSuitabilityChecker.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Check entry against If-None-Match
 * 
 * @param request
 * @param entry
 * @return
 */
private boolean etagValidtorMatches(HttpRequest request,
		HttpCacheEntry entry) {
	Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
	String etag = (etagHeader != null) ? etagHeader.getValue() : null;
	Header[] ifNoneMatch = request
			.getHeaders(HeaderConstants.IF_NONE_MATCH);
	if (ifNoneMatch != null) {
		for (Header h : ifNoneMatch) {
			for (HeaderElement elt : h.getElements()) {
				String reqEtag = elt.toString();
				if (("*".equals(reqEtag) && etag != null)
						|| reqEtag.equals(etag)) {
					return true;
				}
			}
		}
	}
	return false;
}
 
Example 6
Source File: RequestProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private void add100ContinueHeaderIfMissing(HttpRequest request) {
	boolean hasHeader = false;

	for (Header h : request.getHeaders(HTTP.EXPECT_DIRECTIVE)) {
		for (HeaderElement elt : h.getElements()) {
			if (HTTP.EXPECT_CONTINUE.equalsIgnoreCase(elt.getName())) {
				hasHeader = true;
			}
		}
	}

	if (!hasHeader) {
		request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
	}
}
 
Example 7
Source File: HttpUtility.java    From datasync with MIT License 5 votes vote down vote up
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    // Do not retry if over max retry count
    if (executionCount >= maxRetries) {
        return false;
    }

    // Do not retry calls to the github api
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    for (Header header : request.getHeaders("Host")) {
        if (header.getValue().contains("github"))
            return false;
    }

    // Do not retry calls that are not idempotent - posts in our case
    // currently, we make 2 types of posts:
    //  1) posting blobs - this is idempotent
    //  2) posting commit of blob ids - this is not idempotent and we need to fall back to the logic
    //     in DeltaImporter2Publisher.commitBlobPostings
    boolean idempotent = !(request.getRequestLine().getUri().contains("commit"));
    if (idempotent) { // Retry if the request is considered idempotent
        double wait = Math.pow(retryDelayFactor, executionCount);
        System.err.println("Request failed. Retrying request in " + Math.round(wait) + " seconds");
        try {
            Thread.sleep((long) wait*1000);
            return true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}
 
Example 8
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private boolean mayCallBackend(HttpRequest request) {
	for (Header h : request.getHeaders("Cache-Control")) {
		for (HeaderElement elt : h.getElements()) {
			if ("only-if-cached".equals(elt.getName())) {
				return false;
			}
		}
	}
	return true;
}
 
Example 9
Source File: CachedResponseSuitabilityChecker.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private boolean hasValidDateField(HttpRequest request, String headerName) {
	for (Header h : request.getHeaders(headerName)) {
		try {
			DateUtils.parseDate(h.getValue());
			return true;
		} catch (DateParseException dpe) {
			// ignore malformed dates
		}
	}
	return false;
}
 
Example 10
Source File: CachedResponseSuitabilityChecker.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private long getMaxStale(HttpRequest request) {
	long maxstale = -1;
	for (Header h : request.getHeaders("Cache-Control")) {
		for (HeaderElement elt : h.getElements()) {
			if ("max-stale".equals(elt.getName())) {
				if ((elt.getValue() == null || "".equals(elt.getValue()
						.trim())) && maxstale == -1) {
					maxstale = Long.MAX_VALUE;
				} else {
					try {
						long val = Long.parseLong(elt.getValue());
						if (val < 0)
							val = 0;
						if (maxstale == -1 || val < maxstale) {
							maxstale = val;
						}
					} catch (NumberFormatException nfe) {
						// err on the side of preserving semantic
						// transparency
						maxstale = 0;
					}
				}
			}
		}
	}
	return maxstale;
}
 
Example 11
Source File: ResponseCachingPolicy.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if the {@link HttpResponse} gotten from the origin is a
 * cacheable response.
 * 
 * @param request
 *            the {@link HttpRequest} that generated an origin hit
 * @param response
 *            the {@link HttpResponse} from the origin
 * @return <code>true</code> if response is cacheable
 */
public boolean isResponseCacheable(HttpRequest request,
		HttpResponse response) {
	if (requestProtocolGreaterThanAccepted(request)) {
		log.debug("Response was not cacheable.");
		return false;
	}
	String[] uncacheableRequestDirectives = { "no-store" };
	if (hasCacheControlParameterFrom(request, uncacheableRequestDirectives)) {
		return false;
	}

	if (request.getRequestLine().getUri().contains("?")
			&& !isExplicitlyCacheable(response)) {
		log.debug("Response was not cacheable.");
		return false;
	}

	if (sharedCache) {
		Header[] authNHeaders = request.getHeaders("Authorization");
		if (authNHeaders != null && authNHeaders.length > 0) {
			String[] authCacheableParams = { "s-maxage", "must-revalidate",
					"public" };
			return hasCacheControlParameterFrom(response,
					authCacheableParams);
		}
	}

	String method = request.getRequestLine().getMethod();
	return isResponseCacheable(method, response);
}
 
Example 12
Source File: RequestProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private RequestProtocolError requestContainsNoCacheDirectiveWithFieldName(
		HttpRequest request) {
	for (Header h : request.getHeaders("Cache-Control")) {
		for (HeaderElement elt : h.getElements()) {
			if ("no-cache".equalsIgnoreCase(elt.getName())
					&& elt.getValue() != null) {
				return RequestProtocolError.NO_CACHE_DIRECTIVE_WITH_FIELD_NAME;
			}
		}
	}
	return null;
}
 
Example 13
Source File: RequestHeaderAccessor.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public <S> void forEach(String headerName, HttpRequest carrier, S state, HeaderConsumer<String, S> consumer) {
    Header[] headers = carrier.getHeaders(headerName);
    if (headers != null) {
        for (Header header : headers) {
            consumer.accept(header.getValue(), state);
        }
    }
}
 
Example 14
Source File: HttpClient4CookieExtractor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getCookie(HttpRequest cookie) {
    final org.apache.http.Header[] cookies = cookie.getHeaders("Cookie");
    for (org.apache.http.Header header : cookies) {
        final String value = header.getValue();
        if (StringUtils.hasLength(value)) {
            return value;
        }
    }
    return null;
}
 
Example 15
Source File: TSDBHttpAsyncCallbackExecutor.java    From aliyun-tsdb-java-sdk with Apache License 2.0 5 votes vote down vote up
private void tryCloseConnection(HttpRequest request) {
	Header[] headers = request.getHeaders("Connection");
	if (headers != null && headers.length > 0) {
		for (Header h : headers) {
			request.removeHeader(h);
		}
	}

	request.addHeader("Connection", "close");
}
 
Example 16
Source File: HttpClientAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object[] enter(final Object arg0, final Object arg1, final Object arg2) {
  final HttpRequest request = arg0 instanceof HttpRequest ? (HttpRequest)arg0 : arg1 instanceof HttpRequest ? (HttpRequest)arg1 : null;
  if (request == null)
    return null;

  if (request.getHeaders("amz-sdk-invocation-id").length > 0) {
    // skip embedded Apache HttpClient in AWS SDK Client, because it breaks
    // request signature and AWS SDK gets traced by the aws-sdk rule
    return null;
  }

  final LocalSpanContext context = LocalSpanContext.get(COMPONENT_NAME);
  if (context != null) {
    context.increment();
    return null;
  }

  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(request.getRequestLine().getMethod())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_METHOD, request.getRequestLine().getMethod())
    .withTag(Tags.HTTP_URL, request.getRequestLine().getUri()).start();

  for (final ApacheClientSpanDecorator decorator : Configuration.spanDecorators)
    decorator.onRequest(request, arg0 instanceof HttpHost ? (HttpHost)arg0 : null, span);

  LocalSpanContext.set(COMPONENT_NAME, span, null);

  tracer.inject(span.context(), Builtin.HTTP_HEADERS, new HttpHeadersInjectAdapter(request));
  if (arg1 instanceof ResponseHandler)
    return new Object[] {WrapperProxy.wrap(arg1, new TracingResponseHandler<>((ResponseHandler<?>)arg1, span))};

  if (arg2 instanceof ResponseHandler)
    return new Object[] {null, WrapperProxy.wrap(arg2, new TracingResponseHandler<>((ResponseHandler<?>)arg2, span))};

  return null;
}
 
Example 17
Source File: CacheableRequestPolicy.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Determines if an HttpRequest can be served from the cache.
 * 
 * @param request
 *            an HttpRequest
 * @return boolean Is it possible to serve this request from cache
 */
public boolean isServableFromCache(HttpRequest request) {
	String method = request.getRequestLine().getMethod();

	ProtocolVersion pv = request.getRequestLine().getProtocolVersion();
	if (HttpVersion.HTTP_1_1.compareToVersion(pv) != 0) {
		log.debug("Request was not serveable from cache");
		return false;
	}

	if (!method.equals(HeaderConstants.GET_METHOD)) {
		log.debug("Request was not serveable from cache");
		return false;
	}

	if (request.getHeaders(HeaderConstants.PRAGMA).length > 0) {
		log.debug("Request was not serveable from cache");
		return false;
	}

	Header[] cacheControlHeaders = request
			.getHeaders(HeaderConstants.CACHE_CONTROL);
	for (Header cacheControl : cacheControlHeaders) {
		for (HeaderElement cacheControlElement : cacheControl.getElements()) {
			if (HeaderConstants.CACHE_CONTROL_NO_STORE
					.equalsIgnoreCase(cacheControlElement.getName())) {
				log.debug("Request was not serveable from Cache");
				return false;
			}

			if (HeaderConstants.CACHE_CONTROL_NO_CACHE
					.equalsIgnoreCase(cacheControlElement.getName())) {
				log.debug("Request was not serveable from cache");
				return false;
			}
		}
	}

	log.debug("Request was serveable from cache");
	return true;
}
 
Example 18
Source File: CatalogOsgiLibraryTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * See https://issues.apache.org/jira/browse/BROOKLYN-421.
 * 
 * TODO java.net.URLEncoder.encode() gets it wrong for:
 * <ul>
 *   <li>" " (i.e. space - char %20). It turns that into "+" in the url.
 *   <li>"*" (i.e char %2A) is not escaped - this is wrong according to https://en.wikipedia.org/wiki/Percent-encoding (RFC 3986).
 * </ul>
 */
protected void runLibraryUrlUsingExternalizedConfigForCredentials(boolean includeUrlEncoderBrokenChars) throws Exception {
    StringBuilder passwordBuilder = new StringBuilder();
    for (int i = 1; i < 128; i++) {
        if (!includeUrlEncoderBrokenChars && (i == 32 || i == 42)) continue;
        passwordBuilder.append((char)i);
    }
    String username = "[email protected]";
    String password = passwordBuilder.toString();
    
    // Add an externalized config provider, which will return us a username + password
    Map<String, String> externalConfig = ImmutableMap.of("username", username, "password", password);
    ExternalConfigSupplierRegistry externalConfigProviderRegistry = ((ManagementContextInternal)mgmt()).getExternalConfigProviderRegistry();
    externalConfigProviderRegistry.addProvider("myprovider", new MyExternalConfigSupplier(mgmt(), "myprovider", externalConfig));

    addCatalogItems(
            "brooklyn.catalog:",
            "  id: simple-osgi-library",
            "  version: \"1.0\"",
            "  itemType: template",
            "  libraries:",
            "  - $brooklyn:formatString:",
            "    - http://%s:%s@" + jarUrl.getHost() + ":" + jarUrl.getPort() + jarUrl.getPath(),
            "    - $brooklyn:urlEncode:",
            "      - $brooklyn:external(\"myprovider\", \"username\")",
            "    - $brooklyn:urlEncode:",
            "      - $brooklyn:external(\"myprovider\", \"password\")",
            "  item:",
            "    services:",
            "    - type: org.apache.brooklyn.test.osgi.entities.SimpleApplication");

    // Expect basic-auth used when retrieving jar
    HttpRequest req = requestInterceptor.getLastRequest();
    Header[] authHeaders = req.getHeaders("Authorization");
    assertEquals(authHeaders.length, 1, "authHeaders=" + Arrays.toString(authHeaders));
    String authHeader = authHeaders[0].getValue();
    String expectedHeader = "Basic " + BaseEncoding.base64().encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));
    assertEquals(authHeader, expectedHeader, "headers=" + Arrays.toString(req.getAllHeaders()));

    // Expect url to have been correctly escaped
    String escapedUsername = "myuser%40mydomain.com";
    String escapedPassword;
    if (includeUrlEncoderBrokenChars) {
        escapedPassword = "%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E%7F";
    } else {
        escapedPassword = "%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%21%22%23%24%25%26%27%28%29%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E%7F";
    }
    String expectedUrl = "http://" + escapedUsername + ":" + escapedPassword+ "@" + jarUrl.getHost() + ":" + jarUrl.getPort() + jarUrl.getPath();
    
    RegisteredType item = mgmt().getTypeRegistry().get("simple-osgi-library", "1.0");
    assertCatalogLibraryUrl(item, expectedUrl);
}