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:photosharing.api.conx.RecommendationDefinition.java

/**
 * unlike a file/*from   w ww  .j  a v  a 2  s .c  om*/
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=off&lid=f8ad2a54
 * -4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727
 * maps to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
         
 * 
 * @param bearer
 * @param lid
 * @param uid
 * @param nonce
 * @param response
 */
public void unlike(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

        // Generate the
        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("X-METHOD-OVERRIDE", "DELETE");
        post.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(recommendation.getBytes("UTF-8"));
        post.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(post);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Default to SC_NO_CONTENT (204)
        else {
            response.setStatus(HttpStatus.SC_NO_CONTENT);

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
    }
}

From source file:com.baifendian.swordfish.common.storm.StormRestUtil.java

/**
 * ?//from ww w.  ja  va2  s .c  om
 */
public static void topologyDeactivate(String topologyId) throws Exception {
    String res = Request.Post(getTopologyDeactivateUrl(topologyId)).execute().returnContent().toString();

    TopologyOperationDto topologyOperation = JsonUtil.parseObject(res, TopologyOperationDto.class);

    if (topologyOperation == null) {
        throw new Exception("Deactivate not result return!");
    }

    if (!StringUtils.equalsIgnoreCase(topologyOperation.getStatus(), "success")) {
        String msg = MessageFormat.format("Deactivate status not equal success: {0}",
                topologyOperation.getStatus());
        throw new Exception(msg);
    }
}

From source file:de.elomagic.carafile.client.CaraCloud.java

private void createFile(final Path path) throws IOException, GeneralSecurityException {
    LOG.debug("Creating file \"" + path + "\" file at " + client.getRegistryURI());

    URI uri;/* www  .j  a v a2  s .co m*/

    if (Files.isDirectory(path)) {
        registerDefaultWatch(path);
        uri = CaraFileUtils.buildURI(client.getRegistryURI(), "cloud", "create", getSubPath(path));
    } else {
        MetaData md = client.uploadFile(path, path.getFileName().toString());
        uri = CaraFileUtils.buildURI(client.getRegistryURI(), "cloud", "create", getSubPath(path), md.getId());
    }

    HttpResponse response = client.executeRequest(Request.Post(uri)).returnResponse();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException();
    }
}

From source file:de.elomagic.carafile.server.bl.RegistryClientBean.java

/**
 * Register this peer at the registry./*  w  ww.ja  v  a  2 s  .c o m*/
 * <p/>
 * To registry a peer is very important. Otherwise no other peers will find you.
 *
 * @throws IOException Thrown when unable to call REST service at the registry
 * @throws java.net.URISyntaxException When unable to read URI
 */
public void registerPeer() throws IOException, URISyntaxException {
    LOG.debug("Registering this peer " + ownPeerURI + " at registry " + registryURI);

    PeerData peerData = new PeerData();
    peerData.setPeerURI(UriBuilder.fromUri(ownPeerURI).build());

    if (ownPeerURI.equalsIgnoreCase(registryURI)) {
        registryBean.registerPeer(peerData);
    } else {
        URI registry = UriBuilder.fromUri(registryURI).path(REGISTRY).path("registerPeer").build();
        HttpResponse response = Request.Post(registry)
                .bodyString(JsonUtil.write(peerData), ContentType.APPLICATION_JSON).execute().returnResponse();

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            LOG.debug("Peer registration successful");
        } else {
            LOG.error("Unable to registry peer at registry. Status Code "
                    + response.getStatusLine().getStatusCode() + ";Phrase="
                    + response.getStatusLine().getReasonPhrase());
        }
    }
}

From source file:eu.eubrazilcc.lvl.oauth2.rest.LinkedInAuthz.java

@GET
@Path("callback")
public Response authorize(final @Context HttpServletRequest request) {
    final String code = parseQuery(request, "code");
    final String state = parseQuery(request, "state");
    final AtomicReference<String> redirectUriRef = new AtomicReference<String>(),
            callbackRef = new AtomicReference<String>();
    if (!LINKEDIN_STATE_DAO.isValid(state, redirectUriRef, callbackRef)) {
        throw new NotAuthorizedException(status(UNAUTHORIZED).build());
    }//from  ww  w.  ja va 2 s .  c om
    URI callback_uri = null;
    Map<String, String> map = null;
    try {
        final List<NameValuePair> form = form().add("grant_type", "authorization_code").add("code", code)
                .add("redirect_uri", redirectUriRef.get()).add("client_id", CONFIG_MANAGER.getLinkedInAPIKey())
                .add("client_secret", CONFIG_MANAGER.getLinkedInSecretKey()).build();
        // exchange authorization code for a request token
        final long issuedAt = currentTimeMillis() / 1000l;
        String response = Request.Post("https://www.linkedin.com/uas/oauth2/accessToken")
                .addHeader("Accept", "application/json").bodyForm(form).execute().returnContent().asString();
        map = JSON_MAPPER.readValue(response, new TypeReference<HashMap<String, String>>() {
        });
        final String accessToken = map.get("access_token");
        final long expiresIn = parseLong(map.get("expires_in"));
        checkState(isNotBlank(accessToken), "Uninitialized or invalid access token: " + accessToken);
        checkState(expiresIn > 0l, "Uninitialized or invalid expiresIn: " + expiresIn);
        // retrieve user profile data
        final URIBuilder uriBuilder = new URIBuilder(
                "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,positions,email-address)");
        uriBuilder.addParameter("format", "json");
        response = Request.Get(uriBuilder.build()).addHeader("Authorization", "Bearer " + accessToken).execute()
                .returnContent().asString();
        final LinkedInMapper linkedInMapper = createLinkedInMapper().readObject(response);
        final String userId = linkedInMapper.getUserId();
        final String emailAddress = linkedInMapper.getEmailAddress();
        // register or update user in the database
        final String ownerid = toResourceOwnerId(LINKEDIN_IDENTITY_PROVIDER, userId);
        ResourceOwner owner = RESOURCE_OWNER_DAO.find(ownerid);
        if (owner == null) {
            final User user = User.builder().userid(userId).provider(LINKEDIN_IDENTITY_PROVIDER)
                    .email(emailAddress).password("password").firstname(linkedInMapper.getFirstName())
                    .lastname(linkedInMapper.getLastName()).industry(linkedInMapper.getIndustry().orNull())
                    .positions(linkedInMapper.getPositions().orNull()).roles(newHashSet(USER_ROLE))
                    .permissions(asPermissionSet(userPermissions(ownerid))).build();
            owner = ResourceOwner.builder().user(user).build();
            RESOURCE_OWNER_DAO.insert(owner);
        } else {
            owner.getUser().setEmail(emailAddress);
            owner.getUser().setFirstname(linkedInMapper.getFirstName());
            owner.getUser().setLastname(linkedInMapper.getLastName());
            owner.getUser().setIndustry(linkedInMapper.getIndustry().orNull());
            owner.getUser().setPositions(linkedInMapper.getPositions().orNull());
            RESOURCE_OWNER_DAO.update(owner);
        }
        // register access token in the database
        final AccessToken accessToken2 = AccessToken.builder().token(accessToken).issuedAt(issuedAt)
                .expiresIn(expiresIn).scope(asPermissionList(oauthScope(owner, false))).ownerId(ownerid)
                .build();
        TOKEN_DAO.insert(accessToken2);
        // redirect to default portal endpoint
        callback_uri = new URI(callbackRef.get() + "?email=" + urlEncodeUtf8(emailAddress) + "&access_token="
                + urlEncodeUtf8(accessToken));
    } catch (Exception e) {
        String errorCode = null, message = null, status = null;
        if (e instanceof IllegalStateException && map != null) {
            errorCode = map.get("errorCode");
            message = map.get("message");
            status = map.get("status");
        }
        LOGGER.error("Failed to authorize LinkedIn user [errorCode=" + errorCode + ", status=" + status
                + ", message=" + message + "]", e);
        throw new WebApplicationException(status(INTERNAL_SERVER_ERROR)
                .header("WWW-Authenticate", "Bearer realm='" + RESOURCE_NAME + "', error='invalid-code'")
                .build());
    } finally {
        LINKEDIN_STATE_DAO.delete(state);
    }
    return Response.seeOther(callback_uri).build();
}

From source file:org.vas.test.rest.RestImpl.java

protected Request httpPost(String uri) {
    Request request = Request.Post(uri);
    configureRequest(request);

    return request;
}

From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //from   ww w  .  java  2  s  .co m
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
* @param filterBy filter validation issues by the error/warning level
* @param maxErrs errors threshold - max no. critical errors to collect before quitting
*                (warnings not counted; null/0/negative value means unlimited)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out validation report data output stream
 * @throws IOException when there is an I/O error
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");
    //TODO add extra options (normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource, normalizer.xmlBase)?
    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    //execute the query and get results as string
    HttpEntity httpEntity = meb.build();
    //       httpEntity.writeTo(System.err);
    String content = Executor.newInstance()//Executor.newInstance(httpClient)
            .execute(Request.Post(url).body(httpEntity)).returnContent().asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

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

public static <T> T postEntity(URL deploymentUrl, String relativeUrl, int status, String user, String password,
        Class[] classes, Object entity, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    String mediaType = MediaType.APPLICATION_XML;
    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);
    XmlResponseHandler xrh = (XmlResponseHandler) rh;

    xrh.addExtraJaxbClasses(classes);/*from  w  ww . ja  va  2 s.  co  m*/
    String entityStr = xrh.serialize(entity);

    HttpEntity bodyEntity = null;
    try {
        bodyEntity = new StringEntity(entityStr);
    } catch (UnsupportedEncodingException uee) {
        logAndFail("Unable to encode serialized " + entity.getClass().getSimpleName() + " entity", uee);
    }

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

    Response resp = null;
    try {
        logOp("POST", entity, 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:com.qwazr.database.TableSingleClient.java

@Override
public TableRequestResult queryRows(String table_name, TableRequest tableRequest) {
    UBuilder uriBuilder = new UBuilder("/table/", table_name, "/query");
    Request request = Request.Post(uriBuilder.build());
    return commonServiceRequest(request, tableRequest, null, TableRequestResult.class, 200);
}

From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Override
public Request post(String partialUrl) {
    String url = baseUrl + partialUrl;
    return Request.Post(url);
}