Java Code Examples for org.apache.http.HttpRequest

The following examples show how to use org.apache.http.HttpRequest. These examples are extracted from open source projects. 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
@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
@Override
public void process(HttpRequest request, HttpContext context)
    throws HttpException, IOException {


    Options options = Options.builder()
        .printSingleliner()
        .targetPlatform(Platform.UNIX)
        .useShortForm()
        .updateCurl(curl -> curl
            .removeHeader("Host")
            .removeHeader("User-Agent")
            .removeHeader("Connection"))
        .build();

  try {
    curlConsumer.accept(new Http2Curl(options).generateCurl(request));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }

}
 
Example 3
@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws IOException {
    lock.lock();
    try {
        HttpEntity entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
        String content = EntityUtils.toString(entity);

        replies.add(content);
        if (replies.size() == expected) {
            receivedExpectedMessages.signal();
        }

        httpResponse.setStatusCode(HttpStatus.SC_OK);
    } finally {
        lock.unlock();
    }
}
 
Example 4
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
Example 5
Source Project: esigate   Source File: DriverTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testForwardCookiesWithPorts() throws Exception {
    // Conf
    Properties properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080/") //
            .set(Parameters.PRESERVE_HOST, false) //
            .build();

    mockConnectionManager = new MockConnectionManager() {
        @Override
        public HttpResponse execute(HttpRequest httpRequest) {
            Assert.assertNotNull(httpRequest.getFirstHeader("Cookie"));
            Assert.assertEquals("JSESSIONID=926E1C6A52804A625DFB0139962D4E13", httpRequest.getFirstHeader("Cookie")
                    .getValue());
            return new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
        }
    };

    Driver driver = createMockDriver(properties, mockConnectionManager);

    BasicClientCookie cookie = new BasicClientCookie("_JSESSIONID", "926E1C6A52804A625DFB0139962D4E13");
    request = TestUtils.createIncomingRequest("http://127.0.0.1:8081/foobar.jsp").addCookie(cookie);

    driver.proxy("/foobar.jsp", request.build());
}
 
Example 6
Source Project: cloudstack   Source File: RESTServiceConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteCreateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    assertThat(object, notNullValue());
    assertThat(object, equalTo(newObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 7
Source Project: triplea   Source File: MartiDiceRoller.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(
    final HttpRequest request, final HttpResponse response, final HttpContext context)
    throws ProtocolException {
  final URI uri = getLocationURI(request, response, context);
  final String method = request.getRequestLine().getMethod();
  if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
    return new HttpHead(uri);
  } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
    return new HttpGet(uri);
  } else {
    final int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT
        || status == HttpStatus.SC_MOVED_PERMANENTLY
        || status == HttpStatus.SC_MOVED_TEMPORARILY) {
      return RequestBuilder.copy(request).setUri(uri).build();
    }
    return new HttpGet(uri);
  }
}
 
Example 8
Source Project: attic-polygene-java   Source File: WebRealmServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process( final HttpRequest request, final HttpContext context )
    throws HttpException, IOException
{
    AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE );
    CredentialsProvider credsProvider = (CredentialsProvider) context
        .getAttribute( ClientContext.CREDS_PROVIDER );
    HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST );

    // If not auth scheme has been initialized yet
    if( authState.getAuthScheme() == null )
    {
        AuthScope authScope = new AuthScope( targetHost.getHostName(),
                                             targetHost.getPort() );
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials( authScope );
        // If found, generate BasicScheme preemptively
        if( creds != null )
        {
            authState.setAuthScheme( new BasicScheme() );
            authState.setCredentials( creds );
        }
    }
}
 
Example 9
/**
 * Ctor.
 *
 * @param request The http request
 * @throws IllegalStateException if the request's payload cannot be read
 */
public ArrayPayloadOf(final HttpRequest request) {
    try (JsonReader reader = Json.createReader(
        ((HttpEntityEnclosingRequest) request).getEntity().getContent())) {
        if (request instanceof HttpEntityEnclosingRequest) {
            this.resources =
                reader.readArray().getValuesAs(JsonObject.class).iterator();
        } else {
            this.resources = new ArrayList<JsonObject>().iterator();
        }
    } catch (final IOException ex) {
        throw new IllegalStateException(
            "Cannot read request payload", ex
        );
    }
}
 
Example 10
Source Project: cosmic   Source File: ClusterServiceServletHttpHandler.java    License: Apache License 2.0 6 votes vote down vote up
private String handleDeliverPduMethodCall(final HttpRequest req) {
    s_logger.debug("Handling method Deliver PDU with request: " + req);

    final String pduSeq = (String) req.getParams().getParameter("pduSeq");
    final String pduAckSeq = (String) req.getParams().getParameter("pduAckSeq");
    final String sourcePeer = (String) req.getParams().getParameter("sourcePeer");
    final String destPeer = (String) req.getParams().getParameter("destPeer");
    final String agentId = (String) req.getParams().getParameter("agentId");
    final String gsonPackage = (String) req.getParams().getParameter("gsonPackage");
    final String stopOnError = (String) req.getParams().getParameter("stopOnError");
    final String pduType = (String) req.getParams().getParameter("pduType");

    final ClusterServicePdu pdu = new ClusterServicePdu();
    pdu.setSourcePeer(sourcePeer);
    pdu.setDestPeer(destPeer);
    pdu.setAgentId(Long.parseLong(agentId));
    pdu.setSequenceId(Long.parseLong(pduSeq));
    pdu.setAckSequenceId(Long.parseLong(pduAckSeq));
    pdu.setJsonPackage(gsonPackage);
    pdu.setStopOnError("1".equals(stopOnError));
    pdu.setPduType(Integer.parseInt(pduType));

    manager.OnReceiveClusterServicePdu(pdu);
    return "true";
}
 
Example 11
/**
 * Creates absolute request URI with full path from passed in context.
 */
@Nonnull
private URI getRequestURI(final HttpContext context) {
  final HttpClientContext clientContext = HttpClientContext.adapt(context);
  final HttpRequest httpRequest = clientContext.getRequest();
  final HttpHost target = clientContext.getTargetHost();
  try {
    URI uri;
    if (httpRequest instanceof HttpUriRequest) {
      uri = ((HttpUriRequest) httpRequest).getURI();
    }
    else {
      uri = URI.create(httpRequest.getRequestLine().getUri());
    }
    return uri.isAbsolute() ? uri : URIUtils.resolve(URI.create(target.toURI()), uri);
  }
  catch (Exception e) {
    log.warn("Could not create absolute request URI", e);
    return URI.create(target.toURI());
  }
}
 
Example 12
Source Project: onos   Source File: OpenstackNetworkingUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Deserializes raw payload into HttpRequest object.
 *
 * @param rawData raw http payload
 * @return HttpRequest object
 */
public static HttpRequest parseHttpRequest(byte[] rawData) {
    SessionInputBufferImpl sessionInputBuffer =
            new SessionInputBufferImpl(
                    new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
    sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
    DefaultHttpRequestParser requestParser =
                            new DefaultHttpRequestParser(sessionInputBuffer);
    try {
        return requestParser.parse();
    } catch (IOException | HttpException e) {
        log.warn("Failed to parse HttpRequest, due to {}", e);
    }

    return null;
}
 
Example 13
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
	Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
	if (params == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to parse POST parameters.");
	}
	String indexString = params.get("index");
	if (indexString == null || !NumberUtility.isNonNegativeInteger(indexString)) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Index must be provided as non-negative integer.");
	}
	Language language = Language.identify(Integer.parseInt(indexString));
	if (language == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Language index " + indexString + " unknown.");
	}

	try {
		JsonNode data = taskSourceCodeFragmentHandler.render(language);
		backEndHolder.setCompilingLanguage(language);
		return HttpServerUtilities.prepareJsonResponse(exchange, 200, data);
	} catch (RenderException e) {
		return HttpServerUtilities.prepareTextResponse(exchange, 500, "Failed to render page: " + e.getMessage());
	}
}
 
Example 14
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
	if (params == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 500, "Unable to get POST paramters.");
	}

	IIPCService service = CommonTask.getIPCService(params);
	if (service == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 500, "Unable to get IPC service.");
	}

	service.setLaunchAtStartup(!service.isLaunchAtStartup());
	return renderedIpcServices(exchange);
}
 
Example 15
public RequestEntityRestStorageService(final S3Session session, final HttpClientBuilder configuration) {
    super(null, new PreferencesUseragentProvider().get(), null, toProperties(session.getHost(), session.getSignatureVersion()));
    this.session = session;
    this.properties = this.getJetS3tProperties();
    // Client configuration
    configuration.disableContentCompression();
    configuration.setRetryHandler(new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry")));
    configuration.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
            if(response.containsHeader("x-amz-bucket-region")) {
                final String host = ((HttpUriRequest) request).getURI().getHost();
                if(!StringUtils.equals(session.getHost().getHostname(), host)) {
                    regionEndpointCache.putRegionForBucketName(
                        StringUtils.split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0],
                        response.getFirstHeader("x-amz-bucket-region").getValue());
                }
            }
            return super.getRedirect(request, response, context);
        }
    });
    this.setHttpClient(configuration.build());
}
 
Example 16
Source Project: hawkular-agent   Source File: JolokiaClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Header authenticate(Credentials credentials, HttpRequest request, HttpContext context)
        throws AuthenticationException {
    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");

    // the bearer token is stored in the password field, not credentials.getUserPrincipal().getName()
    String bearerToken = credentials.getPassword();

    CharArrayBuffer buffer = new CharArrayBuffer(64);
    if (isProxy()) {
        buffer.append("Proxy-Authorization");
    } else {
        buffer.append("Authorization");
    }
    buffer.append(": Bearer ");
    buffer.append(bearerToken);

    return new BufferedHeader(buffer);
}
 
Example 17
private void setRequestUri(HttpRequest request, URI uri) {
    if (request instanceof HttpRequestWrapper) {
        setRequestUri(((HttpRequestWrapper) request).getOriginal(), uri);
    } else if (request instanceof RequestWrapper) {
        setRequestUri(((RequestWrapper) request).getOriginal(), uri);
    } else {
        ((HttpRequestBase) request).setURI(uri);
    }
}
 
Example 18
private void ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(
		HttpRequest request, HttpResponse response) {
	if (!request.getRequestLine().getMethod()
			.equalsIgnoreCase(HeaderConstants.OPTIONS_METHOD)) {
		return;
	}

	if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
		return;
	}

	if (response.getFirstHeader(HTTP.CONTENT_LEN) == null) {
		response.addHeader(HTTP.CONTENT_LEN, "0");
	}
}
 
Example 19
Source Project: logbook   Source File: LocalRequestTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldReturnContentTypesCharsetIfGiven() {
    final HttpRequest delegate = get("/");
    delegate.addHeader("Content-Type", "text/plain;charset=ISO-8859-1");
    final LocalRequest unit = unit(delegate);
    assertThat(unit.getCharset(), is(StandardCharsets.ISO_8859_1));
}
 
Example 20
public SSLTestHttpServerConnection(final int buffersize, final int fragmentSizeHint,
		final CharsetDecoder chardecoder, final CharsetEncoder charencoder,
		final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy,
		final ContentLengthStrategy outgoingContentStrategy,
		final HttpMessageParserFactory<HttpRequest> requestParserFactory,
		final HttpMessageWriterFactory<HttpResponse> responseWriterFactory) {
	super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints, incomingContentStrategy,
			outgoingContentStrategy, requestParserFactory, responseWriterFactory);
}
 
Example 21
Source Project: Repeat   Source File: ActionMoveTaskGroupUpHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
	if (params == null) {
		return HttpServerUtilities.prepareTextResponse(exchange, 400, "Failed to parse POST data.");
	}
	String id = CommonTask.getTaskGroupIdFromRequest(backEndHolder, params);
	if (id == null || id.isEmpty()) {
		return HttpServerUtilities.prepareTextResponse(exchange, 400, "Cannot find task group from request data.");
	}

	backEndHolder.moveTaskGroupUp(id);
	return renderedTaskGroups(exchange);
}
 
Example 22
protected void handleSsoRequest(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    if ("GET".equalsIgnoreCase(request.getRequestLine().getMethod())) {
        handleSsoGetRequestBase(request);
    } else {
        response.setStatusCode(405);
    }

}
 
Example 23
Source Project: onboard   Source File: ApiProxyServlet.java    License: Apache License 2.0 5 votes vote down vote up
private void setXForwardedForHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest) {
    String headerName = "X-Forwarded-For";
    if (doForwardIP) {
        String newHeader = servletRequest.getRemoteAddr();
        String existingHeader = servletRequest.getHeader(headerName);
        if (existingHeader != null) {
            newHeader = existingHeader + ", " + newHeader;
        }
        proxyRequest.setHeader(headerName, newHeader);
    }
}
 
Example 24
Source Project: Repeat   Source File: HttpServerUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public static JsonNode parsePostParameters(HttpRequest request) {
	byte[] content = getPostContent(request);
	if (content == null) {
		LOGGER.warning("Failed to get POST content.");
		return null;
	}

	return getPostParameters(content);
}
 
Example 25
Source Project: multiapps-controller   Source File: CsrfHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a request has failed due to an expired session(token is not valid anymore) and regenerates the token if needed.
 */
private boolean isRetryNeeded(HttpRequest request, HttpResponse response) throws IOException {
    if (!isProtectionRequired(request)) {
        // The request was not protected so the error was not caused by
        // missing token.
        return false;
    }

    // The token was initialized but probably the session has expired. If it
    // is so, then the token needs to be regenerated and request retried.
    if (isTokenInitialized && (response.getStatusLine()
                                       .getStatusCode() == HttpStatus.SC_FORBIDDEN)) {

        Header csrfTokenHeader = response.getFirstHeader(CSRF_TOKEN_HEADER_NAME);

        // Check if the 403(FORBIDDEN) error is caused by missing token
        if ((csrfTokenHeader != null) && CSRF_TOKEN_HEADER_REQUIRED_VALUE.equals(csrfTokenHeader.getValue())) {
            EntityUtils.consume(response.getEntity());
            // this means that we have previously initialized the token, but
            // server side session has expired and our token is no more
            // valid.
            initializeToken(true);
            // If the new token is null there is no point retrying the
            // request
            return csrfToken != null;
        }
    }
    return false;
}
 
Example 26
public SSLTestHttpServerConnection(final int buffersize, final int fragmentSizeHint,
        final CharsetDecoder chardecoder, final CharsetEncoder charencoder,
        final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy,
        final ContentLengthStrategy outgoingContentStrategy,
        final HttpMessageParserFactory<HttpRequest> requestParserFactory,
        final HttpMessageWriterFactory<HttpResponse> responseWriterFactory) {
    super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints, incomingContentStrategy,
            outgoingContentStrategy, requestParserFactory, responseWriterFactory);
}
 
Example 27
public void verifyArgs(
    Span expectedSpan, HttpRequest expectedRequest, HttpTagAndSpanNamingAdapter expectedAdapter
) {
    assertThat(span).isSameAs(expectedSpan);
    assertThat(request).isSameAs(expectedRequest);
    assertThat(adapter).isSameAs(expectedAdapter);
}
 
Example 28
Source Project: vividus   Source File: HttpClientInterceptorTests.java    License: Apache License 2.0 5 votes vote down vote up
private void testNoHttpRequestBodyIsAttached(HttpRequest httpRequest,
        Matcher<Collection<? extends LoggingEvent>> loggingEventsMatcher)
{
    HttpContext httpContext = mock(HttpContext.class);
    verifyNoInteractions(httpContext);
    httpClientInterceptor.process(httpRequest, httpContext);
    verifyPublishAttachment(REQUEST);
    verifyNoMoreInteractions(attachmentPublisher);
    assertThat(logger.getLoggingEvents(), loggingEventsMatcher);
}
 
Example 29
Source Project: jkube   Source File: AwsSigner4Request.java    License: Eclipse Public License 2.0 5 votes vote down vote up
AwsSigner4Request(String region, String service, HttpRequest request, Date signingTime) {
    this.region = region;
    this.service = service;
    this.request = request;

    signingDateTime = getSigningDateTime(request, signingTime);
    signingDate = signingDateTime.substring(0, 8);
    scope = signingDate + '/' + region + '/' + service + "/aws4_request";
    method = request.getRequestLine().getMethod();
    uri = getUri(request);

    Map<String, String> headers = getOrderedHeadersToSign(request.getAllHeaders());
    signedHeaders = StringUtils.join(headers.keySet(), ';');
    canonicalHeaders = canonicalHeaders(headers);
}
 
Example 30
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
            ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        Credentials creds = credsProvider.getCredentials(authScope);
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}