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.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ReSTDelegateImpl.java

private void sendPutRequest(GenericItem item, ReSTChangeConfig changeConfig)
        throws ClientProtocolException, IOException {

    byte[] content = creator.create(item, changeConfig.getValue(), config.getCharset());
    URI uri = createURI(item, changeConfig.getUrl());
    HttpPut request = new HttpPut(uri);
    ContentType contentType = createContentType();
    request.setEntity(new ByteArrayEntity(content, contentType));

    try {//ww w  .j ava2 s .  c o m
        HttpResponse response = httpClient.execute(request);

        auditLogger.auditReSTRequest(request.getMethod(), uri.toString(),
                new String(content, config.getCharset()), response.getStatusLine().toString());

        expectAnyStatusCode(response, HttpStatus.SC_OK, HttpStatus.SC_NO_CONTENT);

    } finally {
        request.releaseConnection();
    }
}

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;// w  w w . j av  a 2s  . c  o  m
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

From source file:org.trancecode.xproc.step.RequestParser.java

private HttpRequestBase constructMethod(final String method, final URI hrefUri) {
    final HttpEntity httpEntity = request.getEntity();
    final HeaderGroup headers = request.getHeaders();
    if (StringUtils.equalsIgnoreCase(HttpPost.METHOD_NAME, method)) {
        final HttpPost httpPost = new HttpPost(hrefUri);
        for (final Header h : headers.getAllHeaders()) {
            if (!StringUtils.equalsIgnoreCase("Content-Type", h.getName())) {
                httpPost.addHeader(h);//  w w  w. ja  va 2 s. c  o m
            }
        }
        httpPost.setEntity(httpEntity);
        return httpPost;
    } else if (StringUtils.equalsIgnoreCase(HttpPut.METHOD_NAME, method)) {
        final HttpPut httpPut = new HttpPut(hrefUri);
        httpPut.setEntity(httpEntity);
        return httpPut;
    } else if (StringUtils.equalsIgnoreCase(HttpDelete.METHOD_NAME, method)) {
        final HttpDelete httpDelete = new HttpDelete(hrefUri);
        httpDelete.setHeaders(headers.getAllHeaders());
        return httpDelete;
    } else if (StringUtils.equalsIgnoreCase(HttpGet.METHOD_NAME, method)) {
        final HttpGet httpGet = new HttpGet(hrefUri);
        httpGet.setHeaders(headers.getAllHeaders());
        return httpGet;

    } else if (StringUtils.equalsIgnoreCase(HttpHead.METHOD_NAME, method)) {
        final HttpHead httpHead = new HttpHead(hrefUri);
        httpHead.setHeaders(headers.getAllHeaders());
        return httpHead;
    }
    return null;
}

From source file:com.example.internetofthingsxively.MainActivity.java

@Override
protected Boolean doInBackground(Integer... values) {

    Log.d("TEST", "Ejecutando AsyncTask");

    try {//  ww  w.  j  ava  2s  .c om

        // Objeto JSON para enviar a Xively.
        JSONObject dataJSON = new JSONObject();
        dataJSON.put("version", "1.0.0");

        // Objeto JSON que representa el channel de voltaje
        JSONObject voltajeValue = new JSONObject();
        voltajeValue.put("id", "voltaje");
        voltajeValue.put("current_value", "" + values[0]);

        // Objeto JSON que representa el channel de amperios
        JSONObject amperiosValue = new JSONObject();
        amperiosValue.put("id", "amperios");
        amperiosValue.put("current_value", "" + values[1]);

        // Objeto JSON que representa el channel de watios
        JSONObject watiosValue = new JSONObject();
        watiosValue.put("id", "watio");
        watiosValue.put("current_value", "" + values[2]);

        // Los juntamos todos dentro de otro objeto JSON llamado datastreams
        JSONArray datastreamsJSON = new JSONArray();
        datastreamsJSON.put(voltajeValue);
        datastreamsJSON.put(amperiosValue);
        datastreamsJSON.put(watiosValue);
        // Agragamos todo lo que hemos creado al JSON que enviaremos a Xively.
        dataJSON.put("datastreams", datastreamsJSON);

        Log.d("TEST", dataJSON.toString());

        // Conectar a Xively y enviar.
        HttpClient httpClient = new DefaultHttpClient();
        HttpPut httpPut = new HttpPut("https://api.xively.com/v2/feeds/" + XIVELY_FEED);
        httpPut.setHeader("X-ApiKey", XIVELY_APIKEY);
        httpPut.setHeader("content-type", "application/json");

        StringEntity entity = new StringEntity(dataJSON.toString());
        httpPut.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPut);
        String responseString = EntityUtils.toString(httpResponse.getEntity());
        Log.d("TEST", "" + httpResponse.getStatusLine().getStatusCode());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:at.sti2.spark.handler.ImpactoriumHandler.java

@Override
public void invoke(Match match) throws SparkwaveHandlerException {

    /*/*  w ww .j a  va2 s.  c om*/
     * TODO Remove this. This is an ugly hack to stop Impactorium handler of sending thousands of matches regarding the same event. 
     *
     ******************************************************/
    long timestamp = (new Date()).getTime();
    if (timestamp - twoMinutesPause < 120000)
        return;

    twoMinutesPause = timestamp;
    /* *****************************************************/

    String baseurl = handlerProperties.getValue("baseurl");
    logger.info("Invoking impactorium at base URL " + baseurl);

    //Define report id value 
    String reportId = "" + (new Date()).getTime();

    //HTTP PUT the info-object id
    HttpClient httpclient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(baseurl + "/info-object");

    try {
        StringEntity infoObjectEntityRequest = new StringEntity(
                "<info-object name=\"Report " + reportId + " \"/>", "UTF-8");
        httpPut.setEntity(infoObjectEntityRequest);
        HttpResponse response = httpclient.execute(httpPut);

        logger.info("[CREATING REPORT] Status code " + response.getStatusLine());

        //First invocation succeeded
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

            HttpEntity infoObjectEntityResponse = response.getEntity();

            //Something has been returned, let's see what is in it
            if (infoObjectEntityResponse != null) {
                String infoObjectResponse = EntityUtils.toString(infoObjectEntityResponse);
                logger.debug("InfoObject response " + infoObjectResponse);

                //Extract info-object identifier
                String infoObjectReportId = extractInfoObjectIdentifier(infoObjectResponse);
                if (infoObjectReportId == null) {
                    logger.error("Info object report id " + infoObjectReportId);
                } else {
                    logger.info("Info object report id " + infoObjectReportId);

                    //Format the output for the match
                    final List<TripleCondition> conditions = handlerProperties.getTriplePatternGraph()
                            .getConstruct().getConditions();
                    final String ntriplesOutput = match.outputNTriples(conditions);

                    //HTTP PUT the data 
                    httpPut = new HttpPut(baseurl + "/info-object/" + infoObjectReportId + "/data/data.nt");
                    StringEntity dataEntityRequest = new StringEntity(ntriplesOutput, "UTF-8");
                    httpPut.setEntity(dataEntityRequest);
                    response = httpclient.execute(httpPut);

                    logger.info("[STORING DATA] Status code " + response.getStatusLine());

                    //First invocation succeeded
                    if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK))
                        throw new SparkwaveHandlerException("Could not write data.");
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java

@Test
public void testPutConsumer() throws Exception {
    HttpPut put = new HttpPut(
            "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers");
    StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    put.setEntity(entity);
    HttpClient httpclient = new DefaultHttpClient();

    try {/* w ww  . j  av  a2  s  . c o  m*/
        HttpResponse response = httpclient.execute(put);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.fcrepo.auth.roles.basic.integration.AbstractBasicRolesIT.java

protected HttpPut putDSMethod(final String objectPath, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPut put = new HttpPut(serverAddress + objectPath + "/" + ds + "/fcr:content");
    put.setEntity(new StringEntity(content));
    logger.debug("PUT: {}", put.getURI());
    return put;//from w ww  .j a  v a2  s .com
}

From source file:com.urbancode.ud.client.ComponentClient.java

public void setComponentProcessRequestProperty(String processId, String name, String value, boolean isSecure)
        throws IOException, JSONException {
    if (StringUtils.isEmpty(processId)) {
        throw new IOException("processId was not supplied");
    }/*from  w  w  w . ja v  a 2s  . c  o m*/
    if (StringUtils.isEmpty(name)) {
        throw new IOException("name was not supplied");
    }

    String uri = url + "/rest/deploy/componentProcessRequest/" + encodePath(processId) + "/saveProperties";

    JSONArray props = new JSONArray();
    props.put(createNewPropertyJSON(name, value, isSecure));

    HttpPut method = new HttpPut(uri);
    method.setEntity(getStringEntity(props));
    invokeMethod(method);
}

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

public void testUpdateUnexistingModel() throws Exception {
    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, "unexisting"));
    httpPut.setEntity(new StringEntity(objectMapper.createObjectNode().toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}