Example usage for org.apache.http.client.fluent Request Post

List of usage examples for org.apache.http.client.fluent Request Post

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request Post.

Prototype

public static Request Post(final String uri) 

Source Link

Usage

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T> T post(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:on

    Response resp = null;/*from   w  ww.j av a2s  . c  o m*/
    try {
        logOp("POST", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        logAndFail("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:org.kie.remote.tests.base.RestUtil.java

public static <T> T post(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:on

    Response resp = null;/*from www  .j  ava2  s  .  co  m*/
    try {
        logOp("POST", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        failAndLog("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.qwazr.search.index.IndexSingleClient.java

@Override
public BackupStatus doBackup(String schema_name, String index_name, Integer keep_last_count) {
    UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/backup")
            .setParameterObject("keep_last", keep_last_count);
    Request request = Request.Post(uriBuilder.build());
    return commonServiceRequest(request, null, null, BackupStatus.class, 200);
}

From source file:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java

@When("^\"([^\"]*)\" asks for a token for attachment \"([^\"]*)\"$")
public void postDownload(String username, String attachmentId) throws Throwable {
    String blobId = blobIdByAttachmentId.get(attachmentId);
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    response = Request.Post(mainStepdefs.baseUri().setPath("/download/" + blobId).build())
            .addHeader("Authorization", accessToken.serialize()).execute().returnResponse();
}

From source file:me.vertretungsplan.parser.BaseParser.java

@SuppressWarnings("SameParameterValue")
protected String httpPost(String url, String encoding, String body, ContentType contentType,
        Map<String, String> headers) throws IOException, CredentialInvalidException {
    Request request = Request.Post(url).bodyString(body, contentType).connectTimeout(15000)
            .socketTimeout(15000);/*  w  w w. j av  a  2s . c  o m*/
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }
    return executeRequest(encoding, request);
}

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T> T postForm(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Map<String, String> formParams, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    // form content
    Form formContent = Form.form();//from w w  w.  j a  v  a2 s. co  m
    for (Entry<String, String> entry : formParams.entrySet()) {
        formContent.add(entry.getKey(), entry.getValue());
    }

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password))
            .bodyForm(formContent.build());
    // @formatter:on

    Response resp = null;
    try {
        logOp("POST", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);
    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        logAndFail("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.qwazr.search.index.IndexSingleClient.java

@Override
public Response postMappedDocuments(String schema_name, String index_name,
        Collection<Map<String, Object>> documents) {
    try {//w  w w .  ja  v  a2  s .  c  om
        UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/docs");
        Request request = Request.Post(uriBuilder.build());
        HttpResponse response = execute(request, documents, null);
        HttpUtils.checkStatusCodes(response, 200);
        return Response.status(response.getStatusLine().getStatusCode()).build();
    } catch (HttpResponseEntityException e) {
        throw e.getWebApplicationException();
    } catch (IOException e) {
        throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.kie.remote.tests.base.RestUtil.java

public static <T> T postForm(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Map<String, String> formParams, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    // form content
    Form formContent = Form.form();/* w  w  w.j  a va 2 s .com*/
    for (Entry<String, String> entry : formParams.entrySet()) {
        formContent.add(entry.getKey(), entry.getValue());
    }

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password))
            .bodyForm(formContent.build());
    // @formatter:on

    Response resp = null;
    long before = 0, after = 0;
    try {
        logOp("POST", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);
    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        failAndLog("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:io.cos.cas.authentication.handler.support.OpenScienceFrameworkPrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java

/**
 * Securely notify the OSF of a Remote Principal Authentication credential. Allows the OSF the opportunity
 * to create a verified user account and/or assign institutional affiliation to the user's account.
 *
 * @param credential the credential object bearing the authentication headers from the idp
 * @return the username from the idp and setup on the OSF
 * @throws AccountException a account exception
 *//*  w w w  . java2s . c om*/
private PrincipalAuthenticationResult notifyRemotePrincipalAuthenticated(
        final OpenScienceFrameworkCredential credential) throws AccountException {
    try {
        final JSONObject normalized = this.normalizeRemotePrincipal(credential);
        final JSONObject provider = normalized.getJSONObject("provider");
        final String institutionId = provider.getString("id");
        final String username = provider.getJSONObject("user").getString("username");
        final String payload = normalized.toString();

        logger.info("Notify Remote Principal Authenticated: username={}, institution={}", username,
                institutionId);
        logger.debug("Notify Remote Principal Authenticated [{}, {}] Normalized Payload '{}'", username,
                institutionId, payload);

        // Build a JWT and wrap it with JWE for secure transport to the OSF API.
        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(username).claim("data", payload)
                .expirationTime(new Date(new Date().getTime() + SIXTY_SECONDS)).build();

        final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);

        final JWSSigner signer = new MACSigner(this.institutionsAuthJwtSecret.getBytes());
        signedJWT.sign(signer);

        final JWEObject jweObject = new JWEObject(
                new JWEHeader.Builder(JWEAlgorithm.DIR, EncryptionMethod.A256GCM).contentType("JWT").build(),
                new Payload(signedJWT));
        jweObject.encrypt(new DirectEncrypter(this.institutionsAuthJweSecret.getBytes()));
        final String jweString = jweObject.serialize();

        // A call is made to the OSF CAS Institution Login Endpoint to create a registered user (if
        // one does not already exist) and apply institutional affiliation.
        final HttpResponse httpResponse = Request.Post(this.institutionsAuthUrl)
                .addHeader(new BasicHeader("Content-Type", "text/plain"))
                .bodyString(jweString, ContentType.APPLICATION_JSON).execute().returnResponse();
        final int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.info("Notify Remote Principal Authenticated [OSF API] Response: <{}> Status Code {}", username,
                statusCode);
        // The institutional authentication endpoint should always respond with a 204 No Content when successful.
        if (statusCode != HttpStatus.SC_NO_CONTENT) {
            final String responseString = new BasicResponseHandler().handleResponse(httpResponse);
            logger.error("Notify Remote Principal Authenticated [OSF API] Response Body: '{}'", responseString);
            throw new RemoteUserFailedLoginException("Invalid Status Code from OSF API Endpoint");
        }

        // return the username for the credential build.
        return new PrincipalAuthenticationResult(username, institutionId);
    } catch (final JOSEException | IOException | ParserConfigurationException | TransformerException e) {
        logger.error("Notify Remote Principal Authenticated Exception: {}", e.getMessage());
        logger.trace("Notify Remote Principal Authenticated Exception: {}", e);
        throw new RemoteUserFailedLoginException("Unable to Build Message for OSF API Endpoint");
    }
}

From source file:com.qwazr.search.index.IndexSingleClient.java

@Override
public Response updateMappedDocValues(String schema_name, String index_name, Map<String, Object> document) {
    try {/*w ww  .  ja v  a 2s.c  om*/
        UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/doc/values");
        Request request = Request.Post(uriBuilder.build());
        HttpResponse response = execute(request, document, null);
        HttpUtils.checkStatusCodes(response, 200);
        return Response.status(response.getStatusLine().getStatusCode()).build();
    } catch (HttpResponseEntityException e) {
        throw e.getWebApplicationException();
    } catch (IOException e) {
        throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR);
    }
}