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.geosdi.geoplatform.experimental.openam.support.config.connector.crud.OpenAMCrudConnector.java

/**
 * @param openAMUser//from w  ww . j  a v a2  s  .  c om
 * @return {@link IOpenAMUserResponse}
 * @throws Exception
 */
@Override
public IOpenAMUserResponse updateUser(IOpenAMUser openAMUser) throws Exception {
    Preconditions.checkNotNull(openAMUser, "The OpenAMUser must not be null");
    Preconditions.checkArgument((openAMUser.getUserName() != null) && !(openAMUser.getUserName().isEmpty()),
            "The OpenAm UserName must not be null or an Empty String.");
    logger.debug(
            "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TRYING TO Update USER {}  WITH "
                    + "OPENAM_CONNECTOR_SETTINGS : {} \n",
            openAMUser.getUserName(), this.openAMConnectorSettings);

    OpenAMUpdateUserRequest updateUserRequest = this.openAMRequestMediator.getRequest(UPDATE_USER);
    URIBuilder updateURIBuilder = this.buildURI(this.openAMConnectorSettings,
            updateUserRequest.setExtraPathParam(openAMUser.getUserName()));

    logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@OPENAM_UPDATE_USER_CONNECTOR_URI : {}\n",
            URLDecoder.decode(updateURIBuilder.toString(), "UTF-8"));

    IOpenAMAuthenticate openAMAuthenticate = super.authenticate();
    logger.debug("::::::::::::::::::::::::::::::AUTHENTICATE_FOR_UPDATE_USER : {}\n", openAMAuthenticate);

    String openAMUserAsString = this.openAMReader.writeValueAsString(openAMUser);
    logger.debug("::::::::::::::::::::::::::OPENAM_UPDATE_USER_AS_STRING : {}\n", openAMUserAsString);

    HttpPut httpPut = new HttpPut(updateURIBuilder.build());
    httpPut.addHeader("Content-Type", "application/json");
    httpPut.addHeader(this.openAMCookieInfo.getOpenAMCookie(), openAMAuthenticate.getTokenId());
    httpPut.setEntity(new StringEntity(openAMUserAsString, ContentType.APPLICATION_JSON));

    CloseableHttpResponse response = this.httpClient.execute(httpPut);

    if (response.getStatusLine().getStatusCode() != 200) {
        IOpenAMErrorResponse openAMErrorResponse = this.openAMReader
                .readValue(response.getEntity().getContent(), OpenAMErrorResponse.class);
        throw new IllegalStateException(
                "OpenAMUpdateUser Error Code : " + openAMErrorResponse.getCode() + " - Reason : "
                        + openAMErrorResponse.getReason() + " - Message : " + openAMErrorResponse.getMessage());
    }
    this.logout(openAMAuthenticate.getTokenId());
    return this.openAMReader.readValue(response.getEntity().getContent(), OpenAMUserResponse.class);
}

From source file:de.zazaz.iot.bosch.indego.IndegoController.java

/**
 * This sends a PUT request to the server and unmarshals the JSON result.
 * /* w  w w  . jav a 2 s .  c  o  m*/
 * @param urlSuffix the path, to which the request should be sent
 * @param request the data, which should be sent to the server (mapped to JSON)
 * @param returnType the class to which the JSON result should be mapped; if null,
 *       no mapping is tried and null is returned.
 * @return the mapped result of the request
 * @throws IndegoException in case of any unexpected event
*/
private <T> T doPutRequest(String urlSuffix, Object request, Class<? extends T> returnType)
        throws IndegoException {
    try {
        HttpPut httpRequest = new HttpPut(baseUrl + urlSuffix);
        httpRequest.setHeader("x-im-context-id", session.getContextId());
        String json = mapper.writeValueAsString(request);
        httpRequest.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
        CloseableHttpResponse response = httpClient.execute(httpRequest);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new IndegoInvalidCommandException(
                    "The request failed with error: " + response.getStatusLine().toString());
        }
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new IndegoAuthenticationException(
                    "The request failed with error: " + response.getStatusLine().toString());
        }
        String responseContents = EntityUtils.toString(response.getEntity());
        if (returnType == null) {
            return null;
        } else {
            T result = mapper.readValue(responseContents, returnType);
            return result;
        }
    } catch (IOException ex) {
        throw new IndegoException(ex);
    }
}

From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java

/**
 * ????.//from   www.j  a  v a 2 s  .c  o  m
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx
 * Entity: "test"
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testWrite001() {
    StringBuilder builder = new StringBuilder();
    builder.append(DCONNECT_MANAGER_URI);
    builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME);
    builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE);
    builder.append("?");
    builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId());
    builder.append("&");
    builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt");
    builder.append("&");
    builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken());
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("media", new StringBody("test"));
        HttpPut request = new HttpPut(builder.toString());
        request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\"");
        request.setEntity(entity);
        JSONObject root = sendRequest(request);
        Assert.assertNotNull("root is null.", root);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        fail("Exception in StringBody." + e.getMessage());
    }
}

From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java

/**
 * ????./*from  www . j  a  v a 2 s.  c o m*/
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx&position=xxx
 * Entity: "test"
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testWrite002() {
    StringBuilder builder = new StringBuilder();
    builder.append(DCONNECT_MANAGER_URI);
    builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME);
    builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE);
    builder.append("?");
    builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId());
    builder.append("&");
    builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt");
    builder.append("&");
    builder.append(FileDescriptorProfileConstants.PARAM_POSITION + "=0");

    builder.append("&");
    builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken());
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("media", new StringBody("test"));
        HttpPut request = new HttpPut(builder.toString());
        request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\"");
        request.setEntity(entity);
        JSONObject root = sendRequest(request);
        Assert.assertNotNull("root is null.", root);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        fail("Exception in StringBody." + e.getMessage());
    }
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

public <T> T put(URI uri, String body, Function<Reader, T> function) {
    HttpPut request = new HttpPut(uri);
    request.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
    return execute(request, function);
}

From source file:org.bishoph.oxdemo.util.CreateTaskAction.java

@Override
protected JSONObject doInBackground(Object... params) {
    try {//w w  w  .j a  v  a2 s .com
        String uri = (String) params[0];
        String title = (String) params[1];
        if (title == null && folder_id > 0) {
            Log.v("OXDemo", "Either title or folder_id missing. Done nothing!");
            return null;
        }

        Log.v("OXDemo", "Attempting to create task " + title + " on " + uri);

        JSONObject jsonobject = new JSONObject();
        jsonobject.put("folder_id", folder_id);
        jsonobject.put("title", title);
        jsonobject.put("status", 1);
        jsonobject.put("priority", 0);
        jsonobject.put("percent_completed", 0);
        jsonobject.put("recurrence_type", 0);
        jsonobject.put("private_flag", false);
        jsonobject.put("notification", false);

        Log.v("OXDemo", "Body = " + jsonobject.toString());
        HttpPut httpput = new HttpPut(uri);
        StringEntity stringentity = new StringEntity(jsonobject.toString(), HTTP.UTF_8);
        stringentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        httpput.setHeader("Accept", "application/json, text/javascript");
        httpput.setHeader("Content-type", "application/json");
        httpput.setEntity(stringentity);

        HttpResponse response = httpclient.execute(httpput, localcontext);
        Log.v("OXDemo", "Created task " + title);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n");
        JSONObject jsonObj = new JSONObject(result);
        jsonObj.put("title", title);
        return jsonObj;
    } catch (JSONException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackend.java

/**
 * Does a Http request given a method, a relative URL, a list of headers and
 * the payload Protected method due to it's used by the tests.
 * /*from  ww w  . j  a  v  a  2  s.  co  m*/
 * @param method
 * @param url
 * @param headers
 * @param entity
 * @return The result of the request
 * @throws CygnusRuntimeError
 * @throws CygnusPersistenceError
 */

protected JsonResponse doRequest(String method, String url, ArrayList<Header> headers, StringEntity entity)
        throws CygnusRuntimeError, CygnusPersistenceError {
    HttpResponse httpRes = null;
    HttpRequestBase request;

    switch (method) {

    case "PUT":
        HttpPut reqPut = new HttpPut(url);

        if (entity != null) {
            reqPut.setEntity(entity);
        } // if

        request = reqPut;
        break;
    case "POST":
        HttpPost reqPost = new HttpPost(url);

        if (entity != null) {
            reqPost.setEntity(entity);
        } // if

        request = reqPost;
        break;
    case "GET":
        request = new HttpGet(url);
        break;
    case "DELETE":
        request = new HttpDelete(url);
        break;
    default:
        throw new CygnusRuntimeError("Http '" + method + "' method not supported");
    } // switch

    if (headers != null) {
        for (Header header : headers) {
            request.setHeader(header);
        } // for
    } // if

    LOGGER.debug("Http request: " + request.toString());

    try {
        httpRes = httpClient.execute(request);
    } catch (IOException e) {
        request.releaseConnection();
        throw new CygnusPersistenceError("Request error", "IOException", e.getMessage());
    } // try catch

    JsonResponse response = createJsonResponse(httpRes);
    request.releaseConnection();
    return response;
}

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

@Deployment(resources = { "org/activiti/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testUpdateModelNoFields() throws Exception {

    Model model = null;/*from  w w w. jav a2  s  .c o m*/
    try {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.MILLISECOND, 0);
        processEngineConfiguration.getClock().setCurrentTime(now.getTime());

        model = repositoryService.newModel();
        model.setCategory("Model category");
        model.setKey("Model key");
        model.setMetaInfo("Model metainfo");
        model.setName("Model name");
        model.setVersion(2);
        model.setDeploymentId(deploymentId);
        repositoryService.saveModel(model);

        // Use empty request-node, nothing should be changed after update
        ObjectNode requestNode = objectMapper.createObjectNode();

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
        httpPut.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("Model name", responseNode.get("name").textValue());
        assertEquals("Model key", responseNode.get("key").textValue());
        assertEquals("Model category", responseNode.get("category").textValue());
        assertEquals(2, responseNode.get("version").intValue());
        assertEquals("Model metainfo", responseNode.get("metaInfo").textValue());
        assertEquals(deploymentId, responseNode.get("deploymentId").textValue());
        assertEquals(model.getId(), responseNode.get("id").textValue());

        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("createTime").textValue()).getTime());
        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("lastUpdateTime").textValue()).getTime());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId())));
        assertTrue(responseNode.get("deploymentUrl").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, deploymentId)));

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}

From source file:org.flowable.rest.service.api.repository.ModelResourceTest.java

@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testUpdateModelNoFields() throws Exception {

    Model model = null;// w w w  .  j  a v  a 2  s.  co m
    try {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.MILLISECOND, 0);
        processEngineConfiguration.getClock().setCurrentTime(now.getTime());

        model = repositoryService.newModel();
        model.setCategory("Model category");
        model.setKey("Model key");
        model.setMetaInfo("Model metainfo");
        model.setName("Model name");
        model.setVersion(2);
        model.setDeploymentId(deploymentId);
        repositoryService.saveModel(model);

        // Use empty request-node, nothing should be changed after update
        ObjectNode requestNode = objectMapper.createObjectNode();

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
        httpPut.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("Model name", responseNode.get("name").textValue());
        assertEquals("Model key", responseNode.get("key").textValue());
        assertEquals("Model category", responseNode.get("category").textValue());
        assertEquals(2, responseNode.get("version").intValue());
        assertEquals("Model metainfo", responseNode.get("metaInfo").textValue());
        assertEquals(deploymentId, responseNode.get("deploymentId").textValue());
        assertEquals(model.getId(), responseNode.get("id").textValue());

        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("createTime").textValue()).getTime());
        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("lastUpdateTime").textValue()).getTime());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId())));
        assertTrue(responseNode.get("deploymentUrl").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, deploymentId)));

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

public HttpResponse put(URI uri, Message msg) throws IOException {
    HttpPut put = new HttpPut(uri);
    put.setEntity(new ByteArrayEntity(asByteArray(msg)));
    return execute(put);
}