Example usage for org.apache.http.entity ContentType APPLICATION_JSON

List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType APPLICATION_JSON.

Prototype

ContentType APPLICATION_JSON

To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.

Click Source Link

Usage

From source file:com.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
public void testPostRequest() {
    try {/*from  w ww  .ja  v a2  s  . c o  m*/
        response = WS.request(WS.OP.POST, uri + "/post", headers, "Hello World", ContentType.APPLICATION_JSON);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }
    Assert.assertTrue(response != null);
    // The field data will contain what ever we sent it
    Assert.assertEquals("Hello World", response.get("data"));
}

From source file:org.yamj.api.trakttv.TraktTvApi.java

private TokenResponse requestToken(StringEntity body) throws TraktTvException {
    try {/*  w  w w.  j a va  2s  . c om*/
        HttpPost httpPost = new HttpPost();
        httpPost.setURI(new URI(TRAKT_TOKEN_URL));
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        httpPost.setEntity(body);

        DigestedResponse digestedResponse = DigestedResponseReader.postContent(httpClient, httpPost, UTF8);
        switch (digestedResponse.getStatusCode()) {
        case 200:
        case 201:
            return objectMapper.readValue(digestedResponse.getContent(), TokenResponse.class);
        case 400:
            throw new TraktTvException(ApiExceptionType.MAPPING_FAILED, "Request couldn't be parsed", 400,
                    EMPTY_URL);
        case 401:
            throw new TraktTvException(ApiExceptionType.AUTH_FAILURE,
                    "The provided authorization grant is invalid, expired, revoked or does not match the redirection URI",
                    401, EMPTY_URL);
        case 403:
            throw new TraktTvException(ApiExceptionType.AUTH_FAILURE, "Invalid API key or unapproved app", 403,
                    EMPTY_URL);
        case 422:
            throw new TraktTvException(ApiExceptionType.MAPPING_FAILED, "Validation errors", 422, EMPTY_URL);
        case 500:
        case 503:
        case 520:
        case 521:
        case 522:
            throw new TraktTvException(ApiExceptionType.HTTP_503_ERROR, "Internal server error",
                    digestedResponse.getStatusCode(), EMPTY_URL);
        default:
            throw new TraktTvException(ApiExceptionType.UNKNOWN_CAUSE, "Unknown error",
                    digestedResponse.getStatusCode(), EMPTY_URL);
        }
    } catch (URISyntaxException | IOException e) {
        throw new TraktTvException(ApiExceptionType.CONNECTION_ERROR, "Request failed", 503, EMPTY_URL, e);
    }
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java

/**
 * We perform all requests to Elasticsearch as the "kibana" user, as this is the user that will be used
 * in a typical SAML deployment (where Kibana is providing the UI for the SAML Web SSO interactions).
 * Before we can use the Kibana user, we need to set its password to something we know.
 */// w w  w  .j  a v  a2 s.co  m
@Before
public void setKibanaPassword() throws IOException {
    final HttpEntity json = new StringEntity("{ \"password\" : \"" + KIBANA_PASSWORD + "\" }",
            ContentType.APPLICATION_JSON);
    final Response response = adminClient().performRequest("PUT", "/_xpack/security/user/kibana/_password",
            emptyMap(), json);
    assertOK(response);
}

From source file:org.obm.push.spushnik.resources.FolderSyncScenarioTest.java

private HttpResponse folderSyncScenarioWithRequest(String baseURL, String certificate) throws Exception {
    InputStream requestInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(certificate);
    byte[] requestContent = ByteStreams.toByteArray(requestInputStream);

    HttpPost httpPost = new HttpPost(buildRequestUrl(baseURL));
    httpPost.setEntity(new ByteArrayEntity(requestContent, ContentType.APPLICATION_JSON));
    return httpClient.execute(httpPost);
}

From source file:org.wso2.carbon.apimgt.impl.workflow.APIStateChangeWSWorkflowExecutor.java

@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing API State change Workflow.");
        log.debug("Execute workflowDTO " + workflowDTO.toString());
    }/*from  ww w  .  j  a  v  a  2s . c  o m*/

    if (stateList != null) {
        Map<String, List<String>> stateActionMap = getSelectedStatesToApprove();
        APIStateWorkflowDTO apiStateWorkFlowDTO = (APIStateWorkflowDTO) workflowDTO;

        if (stateActionMap.containsKey(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase())
                && stateActionMap.get(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase())
                        .contains(apiStateWorkFlowDTO.getApiLCAction())) {
            //set the auth application related info. This will be used to call the callback service
            setOAuthApplicationInfo(apiStateWorkFlowDTO);
            // build request payload
            String jsonPayload = buildPayloadForBPMNProcess(apiStateWorkFlowDTO);
            if (log.isDebugEnabled()) {
                log.debug("APIStateChange payload: " + jsonPayload);
            }
            if (serviceEndpoint == null) {
                // set the bps endpoint from the global configurations
                WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance()
                        .getAPIManagerConfigurationService().getAPIManagerConfiguration()
                        .getWorkflowProperties();
                serviceEndpoint = workflowProperties.getServerUrl();
            }

            URL serviceEndpointURL = new URL(serviceEndpoint);
            HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(),
                    serviceEndpointURL.getProtocol());
            HttpPost httpPost = new HttpPost(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH);
            //Generate the basic auth header using provided user credentials
            String authHeader = getBasicAuthHeader();
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
            StringEntity requestEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);

            httpPost.setEntity(requestEntity);
            try {
                HttpResponse response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                    String error = "Error while starting the process:  "
                            + response.getStatusLine().getStatusCode() + " "
                            + response.getStatusLine().getReasonPhrase();
                    log.error(error);
                    throw new WorkflowException(error);
                }
            } catch (ClientProtocolException e) {
                String errorMsg = "Error while creating the http client";
                log.error(errorMsg, e);
                throw new WorkflowException(errorMsg, e);
            } catch (IOException e) {
                String errorMsg = "Error while connecting to the BPMN process server from the WorkflowExecutor.";
                log.error(errorMsg, e);
                throw new WorkflowException(errorMsg, e);
            } finally {
                httpPost.reset();
            }

            super.execute(workflowDTO);
        } else {
            // For any other states, act as simpleworkflow executor.
            workflowDTO.setStatus(WorkflowStatus.APPROVED);
            // calling super.complete() instead of complete() to act as the simpleworkflow executor
            super.complete(workflowDTO);
        }
    } else {
        String msg = "State change list is not provided. Please check <stateList> element in ";
        log.error(msg);
        throw new WorkflowException(msg);
    }

    return new GeneralWorkflowResponse();
}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthGitFilter.java

private String generateRandomGerritPassword(String username, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse, FilterChain chain) throws IOException, ServletException {
    log.warn("User " + username + " has not a Gerrit HTTP password: "
            + "generating a random one in order to be able to use Git over HTTP");
    Cookie gerritCookie = getGerritLoginCookie(username, httpRequest, httpResponse, chain);
    String xGerritAuthValue = xGerritAuth.getAuthValue(gerritCookie);

    HttpPut putRequest = new HttpPut(
            getRequestUrlWithAlternatePath(httpRequest, "/accounts/self/password.http"));
    putRequest.setHeader("Cookie", gerritCookie.getName() + "=" + gerritCookie.getValue());
    putRequest.setHeader(XGerritAuth.X_GERRIT_AUTH, xGerritAuthValue);

    putRequest.setEntity(new StringEntity("{\"generate\":true}", ContentType.APPLICATION_JSON));
    HttpResponse putResponse = httpClientProvider.get().execute(putRequest);
    if (putResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ServletException("Cannot generate HTTP password for authenticating user " + username);
    }/*  www  . j  av  a2  s . com*/

    return accountCache.getByUsername(username).getPassword(username);
}

From source file:org.elasticsearch.smoketest.SmokeTestWatcherTestSuiteIT.java

private void indexWatch(String watchId, XContentBuilder builder) throws Exception {
    StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);

    Response response = client().performRequest("PUT", "_xpack/watcher/watch/" + watchId, emptyMap(), entity);
    assertOK(response);//from   w w  w  .  j a  v a 2s.  co m
    Map<String, Object> responseMap = entityAsMap(response);
    assertThat(responseMap, hasEntry("_id", watchId));
}

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

public static HttpResponse doPut(String url, Object payload, String user, String password) throws IOException {
    String restUrl = getRestEndPoint(url);
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(restUrl);
    put.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password), "UTF-8", false));
    put.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(put);
    return response;
}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.UserImpl.java

/**
 * This method updates a user in salesforce.com and returns a success message with updated user id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //ww w. j  av  a 2 s.  com
 * @param outMap 
 */
public Map<String, String> update() {

    final String SALESFORCE_UPDATE_USER_URL = args.get(INSTANCE_URL) + SALESFORCE_USER_URL + args.get(ID);
    Map<String, String> outMap = new HashMap<String, String>();
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));

    Map<String, Object> userAttrMap = new HashMap<String, Object>();
    userAttrMap.put(S_USERNAME, args.get(USERNAME));
    userAttrMap.put(S_FIRSTNAME, args.get(FIRSTNAME));
    userAttrMap.put(S_EMAIL, args.get(EMAIL));
    userAttrMap.put(S_ALIAS, args.get(ALIAS));
    userAttrMap.put(S_PROFILEID, args.get(PROFILEID));
    userAttrMap.put(S_LASTNAME, args.get(LASTNAME));
    userAttrMap.put(S_TIMEZONESIDKEY, args.get(TIMEZONESIDKEY));
    userAttrMap.put(S_LOCALESIDKEY, args.get(LOCALESIDKEY));
    userAttrMap.put(S_EMAILENCODINGKEY, args.get(EMAILENCODINGKEY));
    userAttrMap.put(S_LANGUAGELOCALEYKEY, args.get(LANGUAGELOCALEKEY));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_USER_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;

}