Example usage for org.apache.http.client.methods HttpPut setEntity

List of usage examples for org.apache.http.client.methods HttpPut setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPut setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:de.escidoc.bwelabs.deposit.DepositServiceSpec.java

private HttpResponse saveConfiguration(OutputStream os)
        throws URISyntaxException, IOException, ClientProtocolException {
    LOG.debug("Configuration as String: " + os.toString());
    HttpClient client = new DefaultHttpClient();

    HttpPut put = new HttpPut(new URI(CONFIGURATION_DEPOSIT_URI));
    put.setEntity(new StringEntity(os.toString()));
    HttpResponse response = client.execute(put);
    return response;
}

From source file:com.flipkart.bifrost.http.HttpCallCommand.java

private HttpUriRequest generateRequestObject() throws BifrostException {
    try {/* w w  w  .ja v  a2 s  . c o m*/
        switch (requestType) {
        case HTTP_GET:
            return new HttpGet(url);
        case HTTP_POST:
            HttpPost post = new HttpPost(url);
            post.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(request),
                    ContentType.create(contentType, CharsetUtils.lookup("utf-8"))));
            return post;
        case HTTP_PUT:
            HttpPut put = new HttpPut(url);
            put.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(request),
                    ContentType.create(contentType, CharsetUtils.lookup("utf-8"))));
            return put;
        case HTTP_DELETE:
            return new HttpDelete(url);
        }
    } catch (JsonProcessingException e) {
        throw new BifrostException(BifrostException.ErrorCode.SERIALIZATION_ERROR,
                "Could not serialize request body");
    }
    throw new BifrostException(BifrostException.ErrorCode.UNSUPPORTED_REQUEST_TYPE,
            String.format("Request type %s is not supported", requestType.name()));
}

From source file:org.sourcepit.docker.watcher.ConsulForwarder.java

private void register(ConsulService service) {

    final HttpPut put = new HttpPut(uri + "/v1/agent/service/register");
    put.setEntity(new StringEntity(service.toString(), ContentType.APPLICATION_JSON));
    try {/* w  ww .jav a 2s .  co m*/
        HttpResponse response = client.execute(put);
        closeQuietly(response);
    } catch (IOException e) {
        e.printStackTrace();
    }

    final TtlCheck check = new TtlCheck();
    check.serviceId = id(service);
    check.name = getTtlCheckName(service);
    check.id = getTtlCheckName(service);
    check.ttl = "90s";

    final HttpPut put2 = new HttpPut(uri + "/v1/agent/check/register");
    put2.setEntity(new StringEntity(check.toString(), ContentType.APPLICATION_JSON));
    try {
        HttpResponse response = client.execute(put2);
        closeQuietly(response);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

/**
 * @see mx.openpay.client.core.HttpServiceClient#put(java.lang.String, java.lang.String)
 *///  w  ww .  java 2  s .c o  m
@Override
public HttpServiceResponse put(final String url, final String json) throws ServiceUnavailableException {
    HttpPut request = new HttpPut(URI.create(url));
    request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    return this.executeOperation(request);
}

From source file:org.commonjava.tensor.maven.plugin.LogProjectBuildroot.java

@Override
public void execute() throws MojoExecutionException {
    if (isThisTheExecutionRoot()) {
        final ModuleAssociations moduleAssoc = new ModuleAssociations(
                new ProjectVersionRef(project.getGroupId(), project.getArtifactId(), project.getVersion()));
        for (final MavenProject p : projects) {
            moduleAssoc.addModule(new ProjectVersionRef(p.getGroupId(), p.getArtifactId(), p.getVersion()));
        }/*from   w w w .ja va  2  s . com*/

        final TensorSerializerProvider prov = new TensorSerializerProvider(
                new EGraphManager(new JungEGraphDriver()), new GraphWorkspaceHolder());

        final JsonSerializer serializer = prov.getTensorSerializer();

        final String json = serializer.toString(moduleAssoc);
        final DefaultHttpClient client = new DefaultHttpClient();

        try {
            final HttpPut request = new HttpPut(getUrl());
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            request.setEntity(new StringEntity(json));

            final HttpResponse response = client.execute(request);

            final StatusLine sl = response.getStatusLine();
            if (sl.getStatusCode() != HttpStatus.SC_CREATED) {
                throw new MojoExecutionException("Failed to publish module-artifact association data: "
                        + sl.getStatusCode() + " " + sl.getReasonPhrase());
            }
        } catch (final UnsupportedEncodingException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; invalid encoding for JSON: "
                            + e.getMessage(),
                    e);
        } catch (final ClientProtocolException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; http request failed: "
                            + e.getMessage(),
                    e);
        } catch (final IOException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; http request failed: "
                            + e.getMessage(),
                    e);
        }
    }
}

From source file:net.fischboeck.discogs.BaseOperations.java

<T> T doPutRequest(String url, Object body, Class<T> type) throws ClientException {
    log.debug("[doPutRequest] url={}", url);

    CloseableHttpResponse response = null;

    try {/*from  w  ww .jav  a 2 s. c  o m*/
        HttpPut request = new HttpPut(url);
        request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(body), ContentType.APPLICATION_JSON));
        response = doHttpRequest(request);
        HttpEntity entity = response.getEntity();
        return mapper.readValue(entity.getContent(), type);
    } catch (JsonProcessingException jpe) {
        throw new ClientException(jpe.getMessage());
    } catch (IOException ioe) {
        throw new ClientException(ioe.getMessage());
    } catch (EntityNotFoundException enfe) {
        return null;
    } finally {
        closeSafe(response);
    }
}

From source file:org.talend.dataprep.api.service.command.preparation.PreparationUpdateAction.java

private HttpRequestBase onExecute(String preparationId, String stepId, AppendStep updatedStep) {
    try {//from  w  w w . j ava2s  .c om
        final String url = preparationServiceUrl + "/preparations/" + preparationId + "/actions/" + stepId;

        final List<StepDiff> diff = objectMapper.readValue(getInput(), new TypeReference<List<StepDiff>>() {
        });
        updatedStep.setDiff(diff.get(0));
        final String stepAsString = objectMapper.writeValueAsString(updatedStep);

        final HttpPut actionAppend = new HttpPut(url);
        final InputStream stepInputStream = new ByteArrayInputStream(stepAsString.getBytes());

        actionAppend.setHeader(new BasicHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE));
        actionAppend.setEntity(new InputStreamEntity(stepInputStream));
        return actionAppend;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}

From source file:ch.cyberduck.core.googledrive.DriveWriteFeature.java

@Override
public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status,
        final ConnectionCallback callback) throws BackgroundException {
    final DelayedHttpEntityCallable<Void> command = new DelayedHttpEntityCallable<Void>() {
        @Override//from  w  ww  . j a  va 2s  .co  m
        public Void call(final AbstractHttpEntity entity) throws BackgroundException {
            try {
                final String base = session.getClient().getRootUrl();
                // Initiate a resumable upload
                final HttpEntityEnclosingRequestBase request;
                if (status.isExists()) {
                    final String fileid = new DriveFileidProvider(session).getFileid(file,
                            new DisabledListProgressListener());
                    request = new HttpPatch(
                            String.format("%s/upload/drive/v3/files/%s?supportsTeamDrives=true", base, fileid));
                    if (StringUtils.isNotBlank(status.getMime())) {
                        request.setHeader(HttpHeaders.CONTENT_TYPE, status.getMime());
                    }
                    // Upload the file
                    request.setEntity(entity);
                } else {
                    request = new HttpPost(String.format(
                            String.format(
                                    "%%s/upload/drive/v3/files?uploadType=resumable&supportsTeamDrives=%s",
                                    PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")),
                            base));
                    request.setEntity(new StringEntity(
                            "{\"name\": \"" + file.getName() + "\", \"parents\": [\""
                                    + new DriveFileidProvider(session).getFileid(file.getParent(),
                                            new DisabledListProgressListener())
                                    + "\"]}",
                            ContentType.create("application/json", "UTF-8")));
                    if (StringUtils.isNotBlank(status.getMime())) {
                        // Set to the media MIME type of the upload data to be transferred in subsequent requests.
                        request.addHeader("X-Upload-Content-Type", status.getMime());
                    }
                }
                request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
                final HttpClient client = session.getHttpClient();
                final HttpResponse response = client.execute(request);
                try {
                    switch (response.getStatusLine().getStatusCode()) {
                    case HttpStatus.SC_OK:
                        break;
                    default:
                        throw new DriveExceptionMappingService()
                                .map(new HttpResponseException(response.getStatusLine().getStatusCode(),
                                        response.getStatusLine().getReasonPhrase()));
                    }
                } finally {
                    EntityUtils.consume(response.getEntity());
                }
                if (!status.isExists()) {
                    if (response.containsHeader(HttpHeaders.LOCATION)) {
                        final String putTarget = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
                        // Upload the file
                        final HttpPut put = new HttpPut(putTarget);
                        put.setEntity(entity);
                        final HttpResponse putResponse = client.execute(put);
                        try {
                            switch (putResponse.getStatusLine().getStatusCode()) {
                            case HttpStatus.SC_OK:
                            case HttpStatus.SC_CREATED:
                                break;
                            default:
                                throw new DriveExceptionMappingService().map(
                                        new HttpResponseException(putResponse.getStatusLine().getStatusCode(),
                                                putResponse.getStatusLine().getReasonPhrase()));
                            }
                        } finally {
                            EntityUtils.consume(putResponse.getEntity());
                        }
                    } else {
                        throw new DriveExceptionMappingService()
                                .map(new HttpResponseException(response.getStatusLine().getStatusCode(),
                                        response.getStatusLine().getReasonPhrase()));
                    }
                }
                return null;
            } catch (IOException e) {
                throw new DriveExceptionMappingService().map("Upload failed", e, file);
            }
        }

        @Override
        public long getContentLength() {
            return status.getLength();
        }
    };
    return this.write(file, status, command);
}

From source file:com.github.kristofa.test.http.MockHttpServerTestNG.java

@Test
public void testShouldHandlePutRequests() throws IOException {
    // Given a mock server configured to respond to a DELETE /test
    responseProvider.expect(Method.PUT, "/test", "text/plain; charset=UTF-8", "Hello World").respondWith(200,
            "text/plain", "Welcome");

    // When a request for DELETE /test arrives
    final HttpPut req = new HttpPut(baseUrl + "/test");
    req.setEntity(new StringEntity("Hello World", UTF_8));
    final HttpResponse response = client.execute(req);

    final String responseBody = IOUtils.toString(response.getEntity().getContent());
    final int statusCode = response.getStatusLine().getStatusCode();

    // Then the response status is 204
    Assert.assertEquals(200, statusCode);
    Assert.assertEquals("Welcome", responseBody);
}

From source file:com.noelportugal.amazonecho.SmartThings.java

public String setApp(String url, String body) {
    String output = "";
    try {/*from  ww  w.  j a  v a2s  .  c  om*/

        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPut.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + bearer);

        StringEntity xmlEntity = new StringEntity(body);
        httpPut.setEntity(xmlEntity);

        HttpResponse httpResponse = httpclient.execute(httpPut);
        httpResponse.getEntity();
        output = new BasicResponseHandler().handleResponse(httpResponse);

        if (xmlEntity != null) {
            EntityUtils.consume(xmlEntity);
        }

    } catch (Exception e) {
        System.err.println("setApp Error: " + e.getMessage());
    }

    return output;

}