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:org.sonatype.nexus.testsuite.security.SimpleSessionCookieIT.java

@Test
public void authenticatedContentCRUDActionsShouldNotCreateSession() throws Exception {
    final String target = resolveUrl(nexusUrl, "content/repositories/releases/test.txt").toExternalForm();

    final HttpPut put = new HttpPut(target);
    put.setEntity(new StringEntity("text content"));
    try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider())
            .build()) {/*from  w  w  w . j ava  2s  . com*/
        try (CloseableHttpResponse response = client.execute(put, clientContext())) {
            assertThat(response.getStatusLine().getStatusCode(), is(201));
            assertResponseHasNoSessionCookies(response);
        }
    }

    final HttpHead head = new HttpHead(target);
    try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider())
            .build()) {
        try (CloseableHttpResponse response = client.execute(head, clientContext())) {
            assertThat(response.getStatusLine().getStatusCode(), is(200));
            assertResponseHasNoSessionCookies(response);
        }
    }

    final HttpGet get = new HttpGet(target);
    try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider())
            .build()) {
        try (CloseableHttpResponse response = client.execute(get, clientContext())) {
            assertThat(response.getStatusLine().getStatusCode(), is(200));
            assertResponseHasNoSessionCookies(response);
        }
    }

    final HttpDelete delete = new HttpDelete(target);
    try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider())
            .build()) {
        try (CloseableHttpResponse response = client.execute(delete, clientContext())) {
            assertThat(response.getStatusLine().getStatusCode(), is(204));
            assertResponseHasNoSessionCookies(response);
        }
    }
}

From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java

public HttpResponse executePutRequest(final String request, String body, Header... header) throws Exception {
    HttpPut uriRequest = new HttpPut(getHttpServerUri() + "/" + request);
    if (!Strings.isNullOrEmpty(body)) {
        uriRequest.setEntity(new StringEntity(body));
    }/*from w  w  w . j  av  a2s  .com*/
    return executeRequest(uriRequest, header);
}

From source file:org.activiti.rest.service.api.identity.UserPictureResourceTest.java

public void testUpdatePictureWithCustomMimeType() throws Exception {
    User savedUser = null;//from  ww w .  j av  a2 s  .co  m
    try {
        User newUser = identityService.newUser("testuser");
        newUser.setFirstName("Fred");
        newUser.setLastName("McDonald");
        newUser.setEmail("no-reply@activiti.org");
        identityService.saveUser(newUser);
        savedUser = newUser;

        Map<String, String> additionalFields = new HashMap<String, String>();
        additionalFields.put("mimeType", MediaType.IMAGE_PNG.toString());

        HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_PICTURE, newUser.getId()));
        httpPut.setEntity(HttpMultipartHelper.getMultiPartEntity("myPicture.png", "image/png",
                new ByteArrayInputStream("this is the picture raw byte stream".getBytes()), additionalFields));
        closeResponse(executeBinaryRequest(httpPut, HttpStatus.SC_NO_CONTENT));

        Picture picture = identityService.getUserPicture(newUser.getId());
        assertNotNull(picture);
        assertEquals("image/png", picture.getMimeType());
        assertEquals("this is the picture raw byte stream", new String(picture.getBytes()));

    } finally {

        // Delete user after test passes or fails
        if (savedUser != null) {
            identityService.deleteUser(savedUser.getId());
        }
    }
}

From source file:com.restqueue.framework.client.messageupdate.BasicMessageUpdater.java

/**
 * This method updates the message given the headers and body that you want to update have been set.
 * @return The result of the operation giving you access to the http response code and error information
 *//* w  ww .  jav  a2 s.c om*/
public ConditionalPutResult updateMessage() {
    Object messageBody = null;
    if (stringBody == null && objectBody == null) {
        throw new IllegalArgumentException("String body and Object body cannot both be null.");
    } else {
        if (stringBody != null) {
            messageBody = stringBody;
        }
        if (objectBody != null) {
            messageBody = objectBody;
        }
    }

    if (urlLocation == null) {
        throw new IllegalArgumentException("The Channel Endpoint must be set.");
    }
    if (eTag == null) {
        throw new ChannelClientException("Must set the eTag value to update a message.",
                ChannelClientException.ExceptionType.MISSING_DATA);
    }

    if (messageBody instanceof String && asType == null) {
        throw new IllegalArgumentException("The type must be set when using a String body.");
    }

    final HttpPut httpPut = new HttpPut(urlLocation);

    try {
        if (messageBody instanceof String) {
            httpPut.setEntity(new StringEntity((String) messageBody));
            httpPut.setHeader(HttpHeaders.CONTENT_TYPE, asType.toString());
        } else {
            httpPut.setEntity(
                    new StringEntity(new Serializer().toType(messageBody, MediaType.APPLICATION_JSON)));
            httpPut.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        }
    } catch (UnsupportedEncodingException e) {
        httpPut.setEntity(new BasicHttpEntity());
    }

    for (Map.Entry<CustomHeaders, List<String>> entry : headerMap.entrySet()) {
        for (String headerValue : entry.getValue()) {
            httpPut.addHeader(entry.getKey().getName(), headerValue);
        }
    }

    httpPut.addHeader(CustomHeaders.IF_MATCH.getName(), eTag);

    DefaultHttpClient client = new DefaultHttpClient(params);
    try {
        final HttpResponse response = client.execute(httpPut);
        return new ResultsFactory().conditionalPutResultFromHttpPutResponse(response);
    } catch (HttpHostConnectException e) {
        throw new ChannelClientException(
                "Exception connecting to server. "
                        + "Ensure server is running and configured using the right ip address and port.",
                e, ChannelClientException.ExceptionType.CONNECTION);
    } catch (ClientProtocolException e) {
        throw new ChannelClientException("Exception communicating with server.", e,
                ChannelClientException.ExceptionType.TRANSPORT_PROTOCOL);
    } catch (Exception e) {
        throw new ChannelClientException("Unknown exception occurred when trying to update the message:", e,
                ChannelClientException.ExceptionType.UNKNOWN);
    }

}

From source file:org.activiti.rest.service.api.repository.ModelResourceSourceTest.java

public void testSetModelSourceUnexistingModel() throws Exception {
    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL_SOURCE, "unexisting"));
    httpPut.setEntity(new StringEntity(""));
    closeResponse(executeBinaryRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceResourceTest.java

/**
 * Test suspending a single process instance.
 *//*w  w w .  j a  v a  2s.  co  m*/
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testSuspendProcessInstance() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");

    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("action", "suspend");

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    // Check engine id instance is suspended
    assertEquals(1, runtimeService.createProcessInstanceQuery().suspended()
            .processInstanceId(processInstance.getId()).count());

    // Check resulting instance is suspended
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals(processInstance.getId(), responseNode.get("id").textValue());
    assertTrue(responseNode.get("suspended").booleanValue());

    // Suspending again should result in conflict
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceResourceTest.java

/**
 * Test suspending a single process instance.
 *///from w  ww.j  a  v a 2 s.  c o m
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testActivateProcessInstance() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");
    runtimeService.suspendProcessInstanceById(processInstance.getId());

    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("action", "activate");

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    // Check engine id instance is suspended
    assertEquals(1, runtimeService.createProcessInstanceQuery().active()
            .processInstanceId(processInstance.getId()).count());

    // Check resulting instance is suspended
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals(processInstance.getId(), responseNode.get("id").textValue());
    assertFalse(responseNode.get("suspended").booleanValue());

    // Activating again should result in conflict
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceResourceTest.java

/**
 * Test suspending a single process instance.
 *///from  w  w w  .  j a v a2  s . co m
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testSuspendProcessInstance() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");

    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("action", "suspend");

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    // Check engine id instance is suspended
    assertEquals(1, runtimeService.createProcessInstanceQuery().suspended()
            .processInstanceId(processInstance.getId()).count());

    // Check resulting instance is suspended
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals(processInstance.getId(), responseNode.get("id").textValue());
    assertTrue(responseNode.get("suspended").booleanValue());

    // Suspending again should result in conflict
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}

From source file:com.amazonaws.devicefarm.DeviceFarmUploader.java

/**
 * Upload a single file, waits for upload to complete.
 * @param file the file//from   www  . j  av  a 2  s .  com
 * @param project the project
 * @param uploadType the upload type
 * @return upload object
 */
public Upload upload(final File file, final Project project, final UploadType uploadType) {

    if (!(file.exists() && file.canRead())) {
        throw new DeviceFarmException(String.format("File %s does not exist or is not readable", file));
    }

    final CreateUploadRequest appUploadRequest = new CreateUploadRequest().withName(file.getName())
            .withProjectArn(project.getArn()).withContentType("application/octet-stream")
            .withType(uploadType.toString());
    final Upload upload = api.createUpload(appUploadRequest).getUpload();

    final CloseableHttpClient httpClient = HttpClients.createDefault();
    final HttpPut httpPut = new HttpPut(upload.getUrl());
    httpPut.setHeader("Content-Type", upload.getContentType());

    final FileEntity entity = new FileEntity(file);
    httpPut.setEntity(entity);

    writeToLog(String.format("Uploading %s to S3", file.getName()));

    final HttpResponse response;
    try {
        response = httpClient.execute(httpPut);
    } catch (IOException e) {
        throw new DeviceFarmException(String.format("Error uploading artifact %s", file), e);
    }

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new DeviceFarmException(String.format("Upload returned non-200 responses: %s",
                response.getStatusLine().getStatusCode()));
    }

    waitForUpload(file, upload);

    return upload;
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceResourceTest.java

/**
 * Test suspending a single process instance.
 *//*from   ww  w.j a va  2  s  .c om*/
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testActivateProcessInstance() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");
    runtimeService.suspendProcessInstanceById(processInstance.getId());

    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("action", "activate");

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    // Check engine id instance is suspended
    assertEquals(1, runtimeService.createProcessInstanceQuery().active()
            .processInstanceId(processInstance.getId()).count());

    // Check resulting instance is suspended
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals(processInstance.getId(), responseNode.get("id").textValue());
    assertFalse(responseNode.get("suspended").booleanValue());

    // Activating again should result in conflict
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}