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:org.datagator.api.client.backend.DataGatorService.java

public CloseableHttpResponse patch(String endpoint, InputStream data) throws URISyntaxException, IOException {
    return patch(endpoint, data, ContentType.APPLICATION_JSON);
}

From source file:com.qwazr.graph.test.FullTest.java

private boolean nodeExists(int visiteNodeId) throws IOException {
    HttpResponse response = Request.Get(BASE_URL + '/' + TEST_BASE + "/node/v" + visiteNodeId)
            .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
    Assert.assertThat(response.getStatusLine().getStatusCode(), AnyOf.anyOf(Is.is(200), Is.is(404)));
    Assert.assertThat(response.getEntity().getContentType().getValue(),
            Is.is(ContentType.APPLICATION_JSON.toString()));
    return response.getStatusLine().getStatusCode() == 200;
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpAnnotationsEndToEndTest.java

private HttpResponse postEvent(String requestBody, String tenantId) throws Exception {
    URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1").setPort(httpPort)
            .setPath("/v2.0/" + tenantId + "/events");
    HttpPost post = new HttpPost(builder.build());
    HttpEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
    post.setEntity(entity);//from  w w w.jav a2  s . com
    post.setHeader(Event.FieldLabels.tenantId.name(), tenantId);
    post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
    HttpResponse response = client.execute(post);
    return response;
}

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

@When("^moving mailbox \"([^\"]*)\" to \"([^\"]*)\"$")
public void movingMailbox(String actualMailboxPath, String newParentMailboxPath) throws Throwable {
    String username = userStepdefs.lastConnectedUser;
    Mailbox mailbox = mainStepdefs.jmapServer.serverProbe().getMailbox("#private", username, actualMailboxPath);
    String mailboxId = mailbox.getMailboxId().serialize();
    Mailbox parent = mainStepdefs.jmapServer.serverProbe().getMailbox("#private", username,
            newParentMailboxPath);// w  ww  .j  a  v a  2s  .  co  m
    String parentId = parent.getMailboxId().serialize();

    String requestBody = "[" + "  [ \"setMailboxes\"," + "    {" + "      \"update\": {" + "        \""
            + mailboxId + "\" : {" + "          \"parentId\" : \"" + parentId + "\"" + "        }" + "      }"
            + "    }," + "    \"#0\"" + "  ]" + "]";

    Request.Post(mainStepdefs.baseUri().setPath("/jmap").build())
            .addHeader("Authorization", userStepdefs.tokenByUser.get(username).serialize())
            .bodyString(requestBody, ContentType.APPLICATION_JSON).execute().discardContent();
}

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public Future<Model> train(Dataset dataset, Algorithm algorithm, Map<String, Object> parameters,
        String predictionFeature, MetaInfo modelMeta, String taskId) {

    CompletableFuture<Model> futureModel = new CompletableFuture<>();

    TrainingRequest trainingRequest = new TrainingRequest();
    trainingRequest.setDataset(dataset);
    trainingRequest.setParameters(parameters);
    trainingRequest.setPredictionFeature(predictionFeature);
    //        String trainingRequestString = serializer.write(trainingRequest);

    final HttpPost request = new HttpPost(algorithm.getTrainingService());

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in;/* www .  j av  a 2  s.  c o  m*/
    try {
        in = new PipedInputStream(out);
    } catch (IOException ex) {
        futureModel.completeExceptionally(ex);
        return futureModel;
    }
    InputStreamEntity entity = new InputStreamEntity(in, ContentType.APPLICATION_JSON);
    entity.setChunked(true);

    request.setEntity(entity);
    request.addHeader("Accept", "application/json");

    Future futureResponse = client.execute(request, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(final HttpResponse response) {
            futureMap.remove(taskId);
            int status = response.getStatusLine().getStatusCode();
            try {
                InputStream responseStream = response.getEntity().getContent();

                switch (status) {
                case 200:
                case 201:
                    TrainingResponse trainingResponse = serializer.parse(responseStream,
                            TrainingResponse.class);
                    Model model = new Model();
                    model.setId(randomStringGenerator.nextString(20));
                    model.setActualModel(trainingResponse.getRawModel());
                    model.setPmmlModel(trainingResponse.getPmmlModel());
                    model.setAdditionalInfo(trainingResponse.getAdditionalInfo());
                    model.setAlgorithm(algorithm);
                    model.setParameters(parameters);
                    model.setDatasetUri(dataset != null ? dataset.getDatasetURI() : null);

                    //Check if independedFeatures of model exist in dataset
                    List<String> filteredIndependedFeatures = new ArrayList<String>();

                    if (dataset != null && dataset.getFeatures() != null
                            && trainingResponse.getIndependentFeatures() != null)
                        for (String feature : trainingResponse.getIndependentFeatures()) {
                            for (FeatureInfo featureInfo : dataset.getFeatures()) {
                                if (feature.equals(featureInfo.getURI()))
                                    filteredIndependedFeatures.add(feature);
                            }
                        }

                    model.setIndependentFeatures(filteredIndependedFeatures);
                    model.setDependentFeatures(Arrays.asList(predictionFeature));
                    model.setMeta(modelMeta);

                    List<String> predictedFeatures = new ArrayList<>();
                    for (String featureTitle : trainingResponse.getPredictedFeatures()) {
                        Feature predictionFeatureResource = featureHandler.findByTitleAndSource(featureTitle,
                                "algorithm/" + algorithm.getId());
                        if (predictionFeatureResource == null) {
                            // Create the prediction features (POST /feature)
                            String predFeatID = randomStringGenerator.nextString(12);
                            predictionFeatureResource = new Feature();
                            predictionFeatureResource.setId(predFeatID);
                            predictionFeatureResource.setPredictorFor(predictionFeature);
                            predictionFeatureResource.setMeta(MetaInfoBuilder.builder()
                                    .addSources(
                                            /*messageBody.get("base_uri") + */"algorithm/" + algorithm.getId())
                                    .addComments("Feature created to hold predictions by algorithm with ID "
                                            + algorithm.getId())
                                    .addTitles(featureTitle).addSeeAlso(predictionFeature)
                                    .addCreators(algorithm.getMeta().getCreators()).build());
                            /* Create feature */
                            featureHandler.create(predictionFeatureResource);
                        }
                        predictedFeatures.add(baseURI + "feature/" + predictionFeatureResource.getId());
                    }
                    model.setPredictedFeatures(predictedFeatures);
                    futureModel.complete(model);
                    break;
                case 400:
                    String message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new BadRequestException(message));
                    break;
                case 500:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new InternalServerErrorException(message));
                    break;
                default:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new InternalServerErrorException(message));
                }
            } catch (IOException | UnsupportedOperationException ex) {
                futureModel.completeExceptionally(ex);
            }
        }

        @Override
        public void failed(final Exception ex) {
            futureMap.remove(taskId);
            futureModel.completeExceptionally(ex);
        }

        @Override
        public void cancelled() {
            futureMap.remove(taskId);
            futureModel.cancel(true);
        }

    });

    serializer.write(trainingRequest, out);
    try {
        out.close();
    } catch (IOException ex) {
        futureModel.completeExceptionally(ex);
    }

    futureMap.put(taskId, futureResponse);
    return futureModel;
}

From source file:org.apache.reef.runtime.hdinsight.client.yarnrest.HDInsightInstance.java

/**
 * Issues a YARN kill command to the application.
 *
 * @param applicationId/*from w w  w .jav a 2  s.  c  o m*/
 */
public void killApplication(final String applicationId) throws IOException {
    final String url = this.getApplicationURL(applicationId) + "/state";
    final HttpPut put = preparePut(url);
    put.setEntity(new StringEntity(APPLICATION_KILL_MESSAGE, ContentType.APPLICATION_JSON));
    this.httpClient.execute(put, this.httpClientContext);
}

From source file:org.jboss.tools.feedhenry.ui.model.FeedHenry.java

private String doPostAPICall(String api, String payload, IProgressMonitor monitor) throws FeedHenryException {
    SubMonitor sm = SubMonitor.convert(monitor, 100);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpUtil.setupProxy(httpClient);//from   www  . ja v  a 2  s . c o m
    HttpPost post = new HttpPost(this.fhURL.toString() + "/" + api);
    post.addHeader("X-FH-AUTH-USER", this.apikey);
    post.addHeader("Content-Type", "application/json");
    post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
    HttpResponse response;
    try {
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        response = httpClient.execute(post);
        sm.worked(50);
        int status = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        Long contentLength = entity.getContentLength();
        sm.setWorkRemaining((int) (contentLength / 1024));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = stream.read(buffer)) != -1) {
            baos.write(buffer, 0, length);
            sm.worked(1);
        }
        String json = new String(baos.toByteArray());
        if (status != 200 && status != 201) {
            throw new FeedHenryException(status, response.getStatusLine().getReasonPhrase());
        }

        return json;

    } catch (IOException e) {
        FeedHenryException fe = new FeedHenryException(FHErrorHandler.ERROR_CONNECTION_API_CALL,
                NLS.bind("Unexpected error while communicating with {0}", fhURL.getHost()));
        fe.initCause(e);
        throw fe;
    }
}

From source file:org.kitodo.data.elasticsearch.KitodoRestClient.java

/**
 * Create new index with mapping./*from  www.  j av  a2 s . c  o m*/
 *
 * @param query
 *            contains mapping
 * @return true or false - can be used for displaying information to user if
 *         success
 */
public boolean createIndex(String query) throws IOException, CustomResponseException {
    if (query == null) {
        query = "{\"settings\" : {\"index\" : {\"number_of_shards\" : 1,\"number_of_replicas\" : 0}}}";
    }
    HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);
    Response indexResponse = client.performRequest(HttpMethod.PUT, "/" + index, Collections.emptyMap(), entity);
    int statusCode = processStatusCode(indexResponse.getStatusLine());
    return statusCode == 200 || statusCode == 201;
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized void authenticateClient() throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post;/* www.j  av a  2  s .c  om*/
    HttpResponse response = null;

    StringBuilder buildUrl = new StringBuilder();
    buildUrl.append("http://");
    buildUrl.append(this.endpoint);
    buildUrl.append(":");
    buildUrl.append(Constants.AUTH_PORT.toString());
    buildUrl.append(Constants.AUTH_URI.toString());

    post = new HttpPost(buildUrl.toString());

    String body = String.format(
            "{\"auth\": {\"tenantName\": \"%s\", \"passwordCredentials\": {\"username\": \"%s\", \"password\": \"%s\"}}}",
            this.tenant_id, this.username, this.password);

    post.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));

    response = httpClient.execute(post);
    mapper = new ObjectMapper();

    AuthenticationData auth = mapper.readValue(JavaStackUtils.convertHttpResponseToString(response),
            AuthenticationData.class);

    this.token_id = auth.getAccess().getToken().getId();
    this.tenant_id = auth.getAccess().getToken().getTenant().getId();
    this.isAuthenticated = true;

}

From source file:com.vmware.photon.controller.api.client.resource.ApiTestBase.java

@SuppressWarnings("unchecked")
public final void setupMocksForPagination(String serializedResponse, String serializedResponseForNextPage,
        String nextPageLink, int responseCode) throws IOException {
    this.asyncHttpClient = mock(CloseableHttpAsyncClient.class);
    this.httpClient = mock(HttpClient.class);

    doAnswer(new Answer<Object>() {
        @Override/*from   w  w w  . ja v  a 2  s  .co m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(this.asyncHttpClient).close();

    this.restClient = new RestClient("http://1.1.1.1", this.asyncHttpClient, this.httpClient);

    final HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(responseCode);
    when(httpResponse.getEntity())
            .thenReturn(new StringEntity(serializedResponse, ContentType.APPLICATION_JSON));

    final HttpResponse httpResponseForNextPage = mock(HttpResponse.class);
    StatusLine statusLineForNextPage = mock(StatusLine.class);
    when(httpResponseForNextPage.getStatusLine()).thenReturn(statusLineForNextPage);
    when(statusLineForNextPage.getStatusCode()).thenReturn(responseCode);
    when(httpResponseForNextPage.getEntity())
            .thenReturn(new StringEntity(serializedResponseForNextPage, ContentType.APPLICATION_JSON));

    final Future<HttpResponse> httpResponseFuture = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponse;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponse;
        }
    };

    final Future<HttpResponse> httpResponseFutureForNextPage = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponseForNextPage;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponseForNextPage;
        }
    };

    when(this.httpClient.execute(any(HttpUriRequest.class))).thenAnswer(new Answer<HttpResponse>() {
        @Override
        public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
            HttpUriRequest httpUriRequest = (HttpUriRequest) invocation.getArguments()[0];
            if (httpUriRequest.getURI().toString().contains(nextPageLink)) {
                return httpResponseForNextPage;
            }
            return httpResponse;
        }
    });

    when(this.asyncHttpClient.execute(any(HttpUriRequest.class), any(BasicHttpContext.class),
            any(FutureCallback.class))).thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    HttpUriRequest httpUriRequest = (HttpUriRequest) invocation.getArguments()[0];
                    if (httpUriRequest.getURI().toString().contains(nextPageLink)) {
                        if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                            ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                    .completed(httpResponseForNextPage);
                        }
                        return httpResponseFutureForNextPage;
                    }

                    if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                        ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
}