org.apache.http.client.methods.RequestBuilder Java Examples

The following examples show how to use org.apache.http.client.methods.RequestBuilder. 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: OAuthClient.java    From rundeck-http-plugin with ISC License 6 votes vote down vote up
/**
 * As in doTokenValidate(), validate that the token is correct. In this case we
 * can specify that the token has _just_ been retrieved so that we don't try to
 * retrieve it again if validate fails.
 *
 * @param newToken True if this is a brand new token and we shouldn't try to get
 *                 a new on 401.a
 * @throws HttpResponseException
 * @throws IOException
 * @throws OAuthException
 */
void doTokenValidate(Boolean newToken) throws HttpResponseException, IOException, OAuthException {
    if(this.accessToken == null) {
        this.doTokenRequest();
    } else {
        if (this.validateEndpoint != null) {
            log.debug("Validating access token at " + this.validateEndpoint);

            HttpUriRequest request = RequestBuilder.create("GET")
                    .setUri(this.validateEndpoint)
                    .setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.accessToken)
                    .setHeader(HttpHeaders.ACCEPT, JSON_CONTENT_TYPE)
                    .build();

            HttpResponse response = this.httpClient.execute(request);

            if (response.getStatusLine().getStatusCode() == STATUS_SUCCESS) {
                JsonNode data = jsonParser.readTree(EntityUtils.toString(response.getEntity()));
                String clientId = data.get("client").asText();

                if (!this.clientId.equals(clientId)) {
                    throw new OAuthException("Token received for a client other than us.");
                }
            } else if (response.getStatusLine().getStatusCode() == STATUS_AUTHORIZATION_REQUIRED) {
                this.accessToken = null;

                if (newToken) {
                    throw new OAuthException("Newly acquired token is still not valid.");
                } else {
                    doTokenRequest();
                }
            } else {
                throw new HttpResponseException(response.getStatusLine().getStatusCode(), buildError(response));
            }
        } else {
            log.debug("No validate endpoint exists, skipping validation.");
        }
    }
}
 
Example #2
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void setcontent(RequestBuilder rb) {
  switch (this.methodkind) {
    case Put:
      if (this.content != null)
        rb.setEntity(this.content);
      break;
    case Post:
      if (this.content != null)
        rb.setEntity(this.content);
      break;
    case Head:
    case Get:
    case Options:
    default:
      break;
  }
  this.content = null; // do not reuse
}
 
Example #3
Source File: BasicHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
/**
 * This is how framework makes the KeyValue pair when "application/x-www-form-urlencoded" headers
 * is passed in the request.  In case you want to build or prepare the requests differently,
 * you can override this method via @UseHttpClient(YourCustomHttpClient.class).
 *
 * @param httpUrl
 * @param methodName
 * @param reqBodyAsString
 * @return
 * @throws IOException
 */
public RequestBuilder createFormUrlEncodedRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) throws IOException {
    RequestBuilder requestBuilder = RequestBuilder
            .create(methodName)
            .setUri(httpUrl);
    if (reqBodyAsString != null) {
        Map<String, Object> reqBodyMap = HelperJsonUtils.readObjectAsMap(reqBodyAsString);
        List<NameValuePair> reqBody = new ArrayList<>();
         for(String key : reqBodyMap.keySet()) {
             reqBody.add(new BasicNameValuePair(key, reqBodyMap.get(key).toString()));
         }
         HttpEntity httpEntity = new UrlEncodedFormEntity(reqBody);
         requestBuilder.setEntity(httpEntity);
        requestBuilder.setHeader(CONTENT_TYPE, APPLICATION_FORM_URL_ENCODED);
    }
    return requestBuilder;
}
 
Example #4
Source File: AsyncInternalClient.java    From fc-java-sdk with MIT License 6 votes vote down vote up
protected <Res> void asyncSend(HttpRequest request, AbstractResponseConsumer<Res> consumer, FutureCallback<Res> callback,
                               String contentType, HttpMethod method, boolean httpInvoke)
        throws ClientException {
    try{
        // try refresh credentials if CredentialProvider set
        config.refreshCredentials();

        // Add all needed headers
        if (!httpInvoke
                || !ANONYMOUS.equals(((HttpInvokeFunctionRequest) request).getAuthType())) {
            FcUtil.signRequest(config, request, contentType, method, httpInvoke);
        }

        // Construct HttpRequest
        PrepareUrl prepareUrl = FcUtil.prepareUrl(request.getPath(), request.getQueryParams(), this.config);
        RequestBuilder requestBuilder = RequestBuilder.create(method.name())
                .setUri(prepareUrl.getUrl());
        copyToRequest(request, requestBuilder);
        HttpUriRequest httpRequest = requestBuilder.build();

        HttpHost httpHost = URIUtils.extractHost(httpRequest.getURI());
        httpClient.execute(new FcRequestProducer(httpHost, httpRequest), consumer, callback);
    } catch (Exception e) {
        throw new ClientException(e);
    }
}
 
Example #5
Source File: HttpClientDownloader.java    From zongtui-webcrawler with GNU General Public License v2.0 6 votes vote down vote up
protected RequestBuilder selectRequestMethod(Request request) {
    String method = request.getMethod();
    if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) {
        //default get
        return RequestBuilder.get();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) {
        RequestBuilder requestBuilder = RequestBuilder.post();
        NameValuePair[] nameValuePair = (NameValuePair[]) request.getExtra("nameValuePair");
        if (nameValuePair != null && nameValuePair.length > 0) {
            requestBuilder.addParameters(nameValuePair);
        }
        return requestBuilder;
    } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) {
        return RequestBuilder.head();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) {
        return RequestBuilder.put();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) {
        return RequestBuilder.delete();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) {
        return RequestBuilder.trace();
    }
    throw new IllegalArgumentException("Illegal HTTP Method " + method);
}
 
Example #6
Source File: JSON.java    From validatar with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a HttpUriRequest based on the metadata configuration.
 * @param metadata The metadata configuration.
 * @return A configured request object.
 */
private HttpUriRequest createRequest(Map<String, String> metadata) {
    String verb = metadata.getOrDefault(VERB_KEY, DEFAULT_VERB);
    String url = metadata.get(URL_KEY);
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The " + URL_KEY + " must be provided and contain a valid url.");
    }
    RequestBuilder builder;
    if (GET.equals(verb)) {
        builder = RequestBuilder.get(url);
    } else if (POST.equals(verb)) {
        builder = RequestBuilder.post(url);
        String body = metadata.getOrDefault(BODY_KEY, EMPTY_BODY);
        builder.setEntity(new StringEntity(body, Charset.defaultCharset()));
    } else {
        throw new UnsupportedOperationException("This HTTP method is not currently supported: " + verb);
    }
    // Everything else is assumed to be a header
    metadata.entrySet().stream().filter(entry -> !KNOWN_KEYS.contains(entry.getKey()))
                                .forEach(entry -> builder.addHeader(entry.getKey(), entry.getValue()));
    return builder.build();
}
 
Example #7
Source File: NomadApiClient.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
InputStream executeRawStream(
        final RequestBuilder requestBuilder,
        @Nullable final RequestOptions requestOptions
)
        throws IOException, NomadException {

    final HttpUriRequest request = buildRequest(requestBuilder, requestOptions);
    CloseableHttpResponse response = httpClient.execute(request);
    try {
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw ErrorResponseException.signaledInStatus(request, response);
        }
        return response.getEntity().getContent();
    } catch (Throwable e) {
        response.close();
        throw e;
    }
}
 
Example #8
Source File: ApiBase.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
private <T> ServerQueryResponse<T> executeServerQueryRaw(
        @Nullable final QueryOptions<T> options,
        @Nullable final String wait,
        final ValueExtractor<T> valueExtractor,
        RequestBuilder requestBuilder
) throws IOException, NomadException {
    if (options != null) {
        if (options.getIndex() != null)
            requestBuilder.addParameter("index", options.getIndex().toString());
        if (wait != null)
            requestBuilder.addParameter("wait", wait);
        if (options.isAllowStale())
            requestBuilder.addParameter("stale", null);
    }
    return apiClient.execute(requestBuilder, new ServerQueryResponseAdapter<>(valueExtractor), options);
}
 
Example #9
Source File: DefaultZtsClient.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Override
public AwsTemporaryCredentials getAwsTemporaryCredentials(AthenzDomain athenzDomain, AwsRole awsRole, Duration duration, String externalId) {
    URI uri = ztsUrl.resolve(
            String.format("domain/%s/role/%s/creds", athenzDomain.getName(), awsRole.encodedName()));
    RequestBuilder requestBuilder = RequestBuilder.get(uri);

    // Add optional durationSeconds and externalId parameters
    Optional.ofNullable(duration).ifPresent(d -> requestBuilder.addParameter("durationSeconds", Long.toString(duration.getSeconds())));
    Optional.ofNullable(externalId).ifPresent(s -> requestBuilder.addParameter("externalId", s));

    HttpUriRequest request = requestBuilder.build();
    return execute(request, response -> {
        AwsTemporaryCredentialsResponseEntity entity = readEntity(response, AwsTemporaryCredentialsResponseEntity.class);
        return entity.credentials();
    });
}
 
Example #10
Source File: HttpclientSpringMvcBenchmark.java    From raptor with Apache License 2.0 6 votes vote down vote up
@Benchmark
public void test(Blackhole bh) {
    String body = "{\"name\":\"ppdai\"}";
    String url = "http://localhost:" + port + "/raptor/com.ppdai.framework.raptor.proto.Simple/sayHello";
    HttpUriRequest request = RequestBuilder.post(url)
            .addHeader("connection", "Keep-Alive")
            .setEntity(EntityBuilder.create().setText(body).setContentType(ContentType.APPLICATION_JSON).build())
            .build();
    String responseBody;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(100);
        response.getEntity().writeTo(bos);
        responseBody = new String(bos.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException("error", e);
    }
    bh.consume(responseBody);
}
 
Example #11
Source File: SalesforceRestWriter.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public void flush() {
  try {
    if (isRetry()) {
      //flushing failed and it should be retried.
      super.writeImpl(null);
      return;
    }

    if (batchRecords.isPresent() && batchRecords.get().size() > 0) {
      getLog().info("Flusing remaining subrequest of batch. # of subrequests: " + batchRecords.get().size());
      curRequest = Optional.of(newRequest(RequestBuilder.post().setUri(combineUrl(getCurServerHost(), batchResourcePath)),
                                              newPayloadForBatch()));
      super.writeImpl(null);
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #12
Source File: BasicHttpClientTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void createRequestBuilder() throws IOException {
    header.put("Content-Type", "application/x-www-form-urlencoded");
    String reqBodyAsString = "{\"Company\":\"Amazon\",\"age\":30,\"worthInBillion\":999.999}";
    RequestBuilder requestBuilder = basicHttpClient.createRequestBuilder("/api/v1/founder", "POST", header, reqBodyAsString);
    String nameValuePairString = EntityUtils.toString(requestBuilder.getEntity(), "UTF-8");
    assertThat(requestBuilder.getMethod(), is("POST"));
    assertThat(nameValuePairString, is("Company=Amazon&worthInBillion=999.999&age=30"));
}
 
Example #13
Source File: FhirResourceDelete.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceDelete(String resourceName)
    throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
  // "resource-id");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

  HttpUriRequest request =
      RequestBuilder.delete()
          .setUri(uriBuilder.build())
          .addHeader("Content-Type", "application/fhir+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  // Regardless of whether the operation succeeds or
  // fails, the server returns a 200 OK HTTP status code. To check that the
  // resource was successfully deleted, search for or get the resource and
  // see if it exists.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    String errorMessage =
        String.format(
            "Exception deleting FHIR resource: %s\n", response.getStatusLine().toString());
    System.err.print(errorMessage);
    responseEntity.writeTo(System.err);
    throw new RuntimeException(errorMessage);
  }
  System.out.println("FHIR resource deleted.");
  responseEntity.writeTo(System.out);
}
 
Example #14
Source File: FaviconServlet.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private byte[] getImage(String url) {
    // Try to get the favicon from the url using an HTTP connection from the pool
    // that also allows to configure timeout values (e.g. connect and get data)
    final RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(5000)
        .setSocketTimeout(5000)
        .build();
    final HttpUriRequest getRequest = RequestBuilder.get(url)
        .setConfig(requestConfig)
        .build();

    try(final CloseableHttpResponse response = client.execute(getRequest)) {
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            final byte[] result = EntityUtils.toByteArray(response.getEntity());

            // Prevent SSRF by checking result (OF-1885)
            if ( !GraphicsUtils.isImage( result ) ) {
                LOGGER.info( "Ignoring response to an HTTP request that should have returned an image (but returned something else): {}", url) ;
                return null;
            }
            return result;
        }
    } catch (final IOException ex) {
        LOGGER.debug( "An exception occurred while trying to obtain an image from: {}", url, ex );
    }

    return null;
}
 
Example #15
Source File: JSONTest.java    From validatar with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailingRequest() throws IOException {
    HttpClient client = mock(HttpClient.class);
    Mockito.doThrow(new IOException("Testing failure")).when(client).execute(Mockito.any(HttpUriRequest.class));

    HttpUriRequest request = RequestBuilder.get("fake").build();
    Query query = new Query();

    json.makeRequest(client, request, query);

    Assert.assertTrue(query.failed());
    Assert.assertTrue(query.getMessages().stream().anyMatch(s -> s.contains("Testing failure")));
}
 
Example #16
Source File: FhirResourceGetHistory.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceGetHistory(String resourceName, String versionId)
    throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
  // "resource-id");
  // String versionId = "version-uuid"

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s/_history/%s", client.getRootUrl(), resourceName, versionId);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

  HttpUriRequest request =
      RequestBuilder.get()
          .setUri(uriBuilder.build())
          .addHeader("Content-Type", "application/fhir+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    System.err.print(
        String.format(
            "Exception retrieving FHIR history: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.println("FHIR resource retrieved from version: ");
  responseEntity.writeTo(System.out);
}
 
Example #17
Source File: FhirResourceSearchGet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceSearchGet(String resourceName)
    throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

  HttpUriRequest request =
      RequestBuilder.get()
          .setUri(uriBuilder.build())
          .addHeader("Content-Type", "application/fhir+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    System.err.print(
        String.format(
            "Exception searching GET FHIR resources: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.println("FHIR resource search results: ");
  responseEntity.writeTo(System.out);
}
 
Example #18
Source File: FhirResourceCreate.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceCreate(String fhirStoreName, String resourceType)
    throws IOException, URISyntaxException {
  // String fhirStoreName =
  //    String.format(
  //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");
  // String resourceType = "Patient";

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();
  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s/fhir/%s", client.getRootUrl(), fhirStoreName, resourceType);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
  StringEntity requestEntity =
      new StringEntity("{\"resourceType\": \"" + resourceType + "\", \"language\": \"en\"}");

  HttpUriRequest request =
      RequestBuilder.post()
          .setUri(uriBuilder.build())
          .setEntity(requestEntity)
          .addHeader("Content-Type", "application/fhir+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
    System.err.print(
        String.format(
            "Exception creating FHIR resource: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.print("FHIR resource created: ");
  responseEntity.writeTo(System.out);
}
 
Example #19
Source File: MixerHttpClient.java    From beam-client-java with MIT License 5 votes vote down vote up
/**
 * Creates a {@link org.apache.http.HttpRequest} given a type, path, and optional content.
 *
 * @param requestType The type of HTTP/1.1 request to make (see {@link RequestType}
 *                    for more details.
 * @param uri The URI to request content from.
 * @param args The content of the request.  This parameter is optional and considered to be nullable.
 *
 * @return A request built from the specification above.
 */
private HttpUriRequest makeRequest(RequestType requestType, URI uri, Object... args) {
    RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT);
    config.setCookieSpec(CookieSpecs.BEST_MATCH);

    RequestBuilder requestBuilder = RequestBuilder.create(requestType.name())
                         .setUri(uri)
                         .setConfig(config.build())
                         .setEntity(this.makeEntity(args))
                         .setHeader("User-Agent", this.getUserAgent());

    if (this.oauthToken != null) {
        requestBuilder.addHeader("Authorization", "Bearer " + this.oauthToken);
    }
    if (this.jwt != null) {
        requestBuilder.addHeader("Authorization", "JWT " + this.jwtString);
    }

    if (this.oauthToken == null && this.jwt == null) {
        requestBuilder.addHeader("Client-Id", clientId);
    }
    if (this.csrfToken != null) {
        requestBuilder.addHeader(CSRF_TOKEN_HEADER, this.csrfToken);
    }

    return requestBuilder.build();
}
 
Example #20
Source File: DefaultHttpClient.java    From FcmJava with MIT License 5 votes vote down vote up
private <TRequestMessage> HttpUriRequest buildPostRequest(TRequestMessage requestMessage) {

        // Get the JSON representation of the given request message:
        String content = serializer.serialize(requestMessage);

        return RequestBuilder.post(settings.getFcmUrl())
                .addHeader(HttpHeaders.AUTHORIZATION, String.format("key=%s", settings.getApiKey()))
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .setEntity(new StringEntity(content, StandardCharsets.UTF_8))
                .build();
    }
 
Example #21
Source File: RDF4JProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected HttpUriRequest getUpdateMethod(QueryLanguage ql, String update, String baseURI, Dataset dataset,
		boolean includeInferred, int maxExecutionTime, Binding... bindings) {
	RequestBuilder builder = null;
	String transactionURL = getTransactionURL();
	if (transactionURL != null) {
		builder = RequestBuilder.put(transactionURL);
		builder.addHeader("Content-Type", Protocol.SPARQL_UPDATE_MIME_TYPE + "; charset=utf-8");
		builder.addParameter(Protocol.ACTION_PARAM_NAME, Action.UPDATE.toString());
		for (NameValuePair nvp : getUpdateMethodParameters(ql, null, baseURI, dataset, includeInferred,
				maxExecutionTime, bindings)) {
			builder.addParameter(nvp);
		}
		// in a PUT request, we carry the only actual update string as the
		// request body - the rest is sent as request parameters
		builder.setEntity(new StringEntity(update, UTF8));
		pingTransaction();
	} else {
		builder = RequestBuilder.post(getUpdateURL());
		builder.addHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8");

		builder.setEntity(new UrlEncodedFormEntity(getUpdateMethodParameters(ql, update, baseURI, dataset,
				includeInferred, maxExecutionTime, bindings), UTF8));
	}
	// functionality to provide custom http headers as required by the
	// applications
	for (Map.Entry<String, String> additionalHeader : getAdditionalHttpHeaders().entrySet()) {
		builder.addHeader(additionalHeader.getKey(), additionalHeader.getValue());
	}
	return builder.build();
}
 
Example #22
Source File: CrowdManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Authenticates a user with crowd. If authentication failed, raises a <code>RemoteException</code>
 * @param username the username
 * @param password the password
 * @throws RemoteException if an exception occurred communicating with the crowd server
 */
public void authenticate(String username, String password) throws RemoteException {
    username = JID.unescapeNode(username);
    LOG.debug("authenticate '" + String.valueOf(username) + "'");

    final AuthenticatePost authenticatePost = new AuthenticatePost();
    authenticatePost.value = password;
    final StringWriter writer = new StringWriter();
    JAXB.marshal(authenticatePost, writer);

    final HttpUriRequest postRequest = RequestBuilder.post(crowdServer.resolve("authentication?username=" + urlEncode(username)))
        .setConfig(requestConfig)
        .setEntity(new StringEntity(writer.toString(), StandardCharsets.UTF_8))
        .setHeader(HEADER_CONTENT_TYPE_APPLICATION_XML)
        .build();

    try(final CloseableHttpResponse response = client.execute(postRequest, clientContext)) {

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            handleHTTPError(response);
        }
        
    } catch (IOException ioe) {
        handleError(ioe);
    }
    
    LOG.info("authenticated user:" + username);
}
 
Example #23
Source File: BasicHttpClientTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void createRequestBuilder_spaceInKeyValue() throws IOException {
    header.put("Content-Type", "application/x-www-form-urlencoded");
    String reqBodyAsString = "{\"Name\":\"Larry Pg\",\"Company\":\"Amazon\",\"Title\":\"CEO\"}";
    RequestBuilder requestBuilder = basicHttpClient.createRequestBuilder("/api/v1/founder", "POST", header, reqBodyAsString);
    String nameValuePairString = EntityUtils.toString(requestBuilder.getEntity(), "UTF-8");
    assertThat(nameValuePairString, is("Company=Amazon&Title=CEO&Name=Larry+Pg"));
}
 
Example #24
Source File: HttpUriRequestBuilder.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public HttpUriRequest build() {
    validate();
    final RequestBuilder builder = RequestBuilder.create(method.toString()).setUri(buildUri());
    if (!methodParameters.isEmpty()) {
        for (final Entry<String, String> entry : methodParameters.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }
    }
    if (jsonPayload.isPresent()) {
        builder.addHeader(new BasicHeader(CONTENT_TYPE, JSON_CONTENT_TYPE))
            .setEntity(new StringEntity(jsonPayload.get(), ContentType.create(JSON_CONTENT_TYPE, Consts.UTF_8)));
    }
    return builder.build();
}
 
Example #25
Source File: DefaultZmsClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public List<AthenzDomain> getDomainList(String prefix) {
    HttpUriRequest request = RequestBuilder.get()
            .setUri(zmsUrl.resolve("domain"))
            .addParameter("prefix", prefix)
            .build();
    return execute(request, response -> {
        DomainListResponseEntity result = readEntity(response, DomainListResponseEntity.class);
        return result.domains.stream().map(AthenzDomain::new).collect(toList());
    });
}
 
Example #26
Source File: DefaultIdentityDocumentClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
private SignedIdentityDocument getIdentityDocument(String host, String type) {

        try (CloseableHttpClient client = createHttpClient(sslContextSupplier.get(), hostnameVerifier)) {
            URI uri = configserverUri
                    .resolve(IDENTITY_DOCUMENT_API)
                    .resolve(type + '/')
                    .resolve(host);
            HttpUriRequest request = RequestBuilder.get()
                    .setUri(uri)
                    .addHeader("Connection", "close")
                    .addHeader("Accept", "application/json")
                    .build();
            try (CloseableHttpResponse response = client.execute(request)) {
                String responseContent = EntityUtils.toString(response.getEntity());
                if (HttpStatus.isSuccess(response.getStatusLine().getStatusCode())) {
                    SignedIdentityDocumentEntity entity = objectMapper.readValue(responseContent, SignedIdentityDocumentEntity.class);
                    return EntityBindingsMapper.toSignedIdentityDocument(entity);
                } else {
                    throw new RuntimeException(
                            String.format(
                                    "Failed to retrieve identity document for host %s: %d - %s",
                                    host,
                                    response.getStatusLine().getStatusCode(),
                                    responseContent));
                }
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
 
Example #27
Source File: SimpleWebhookRunner.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private HttpUriRequest addGetParams(RequestBuilder requestBuilder, String login, String email, String name, String subject, String content) {
    requestBuilder.addParameter("login", login);
    requestBuilder.addParameter("email", email);
    requestBuilder.addParameter("name", name);
    requestBuilder.addParameter("subject", subject);
    requestBuilder.addParameter("content", content);
    return requestBuilder.build();
}
 
Example #28
Source File: DefaultZmsClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasAccess(AthenzResourceName resource, String action, AthenzIdentity identity) {
    URI uri = zmsUrl.resolve(String.format("access/%s/%s?principal=%s",
                                           action, resource.toResourceNameString(), identity.getFullName()));
    HttpUriRequest request = RequestBuilder.get()
            .setUri(uri)
            .build();
    return execute(request, response -> {
        AccessResponseEntity result = readEntity(response, AccessResponseEntity.class);
        return result.granted;
    });
}
 
Example #29
Source File: ChunkListRequestFactory.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public HttpUriRequest apply(ChunkServer.HostInfo hostInfo) {
    String uri = hostInfo.getScheme() + "://" + hostInfo.getHostname() + "/" + hostInfo.getUri();
    HttpUriRequest request = RequestBuilder.create(hostInfo.getMethod())
            .setUri(uri)
            .build();
    hostInfo.getHeadersList()
            .stream()
            .map(u -> new BasicHeader(u.getName(), u.getValue()))
            .forEach(request::addHeader);
    return request;
}
 
Example #30
Source File: HttpComponentsConnector.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
private HttpUriRequest toUriHttpRequest(final ClientRequest request) {
    final HttpEntity entity = this.getHttpEntity(request);
    return RequestBuilder
        .create(request.getMethod())
        .setUri(request.getUri())
        .setEntity(entity)
        .build();
}