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.kairosdb.plugin.announce.AnnounceService.java

/**
 * Announces service//from   www.ja  v  a2 s. c o m
 */
private HttpResponse announce(String discoveryURL) throws JSONException, IOException {
    JSONObject announce = new JSONObject();
    HttpClient client = new DefaultHttpClient();

    announce.put("environment", m_environment);
    announce.put("pool", m_pool);
    announce.put("location", "/" + m_nodeId);

    JSONArray services = new JSONArray();
    announce.put("services", services);

    JSONObject service = new JSONObject();
    services.put(service);

    service.put("id", m_announceId.toString());
    service.put("type", "reporting");

    JSONObject props = new JSONObject();

    if (m_httpPort > 0)
        props.put("http", "http://" + m_hostIp + ":" + m_httpPort);
    if (m_httpsPort > 0)
        props.put("https", "https://" + m_hostname + ":" + m_httpsPort);
    if (m_telnetPort > 0)
        props.put("telnet", m_hostIp + ":" + m_telnetPort);

    service.put("properties", props);

    HttpPut post = new HttpPut(discoveryURL + "/v1/announcement/" + m_nodeId);
    post.setHeader("User-Agent", m_nodeId.toString());
    post.setHeader("Content-Type", "application/json");

    post.setEntity(new StringEntity(announce.toString()));

    return client.execute(post);
}

From source file:eu.hansolo.accs.RestClient.java

private JSONObject putSpecific(final URIBuilder BUILDER, final Location LOCATION) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPut put = new HttpPut(BUILDER.build());
        put.setHeader("Content-type", "application/json");
        put.setHeader("accept", "application/json");
        put.setEntity(new StringEntity(LOCATION.toJSONString()));

        return handleResponse(httpClient.execute(put));
    } catch (URISyntaxException | IOException e) {
        return new JSONObject();
    }//from  ww w .ja va  2 s  . c o  m
}

From source file:at.ac.tuwien.dsg.elasticdaasclient.utils.RestfulWSClient.java

public String callPutMethod(String xmlString) {
    String rs = "";

    try {/* w  w  w. j  a  v  a2 s. c  o m*/

        //HttpGet method = new HttpGet(url);
        StringEntity inputKeyspace = new StringEntity(xmlString);

        //   Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url);

        HttpPut request = new HttpPut(url);
        request.addHeader("content-type", "application/xml; charset=utf-8");
        request.addHeader("Accept", "application/xml, multipart/related");
        request.setEntity(inputKeyspace);

        HttpResponse methodResponse = this.getHttpClient().execute(request);

        int statusCode = methodResponse.getStatusLine().getStatusCode();

        //  Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        rs = result.toString();
        // System.out.println("Response String: " + result.toString());
    } catch (Exception ex) {

    }
    return rs;
}

From source file:io.gs2.AbstractGs2Client.java

/**
 * POST?//w  w w .j  av a2s. c o  m
 * 
 * @param url URL
 * @param credential ?
 * @param service 
 * @param module 
 * @param function 
 * @param body 
 * @return 
 */
protected HttpPut createHttpPut(String url, IGs2Credential credential, String service, String module,
        String function, String body) {
    Long timestamp = System.currentTimeMillis() / 1000;
    url = StringUtils.replace(url, "{service}", service);
    url = StringUtils.replace(url, "{region}", region.getName());
    HttpPut put = new HttpPut(url);
    put.setHeader("Content-Type", "application/json");
    credential.authorized(put, service, module, function, timestamp);
    put.setEntity(new StringEntity(body, "UTF-8"));
    return put;
}

From source file:at.ac.tuwien.dsg.esperstreamprocessing.utils.RestfulWSClient.java

public void callPutMethod(String xmlString) {

    try {//from ww  w .  j  a  v a2s  . co m

        //HttpGet method = new HttpGet(url);
        StringEntity inputKeyspace = new StringEntity(xmlString);

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url);
        HttpPut request = new HttpPut(url);
        request.addHeader("content-type", "application/xml; charset=utf-8");
        request.addHeader("Accept", "application/xml, multipart/related");
        request.setEntity(inputKeyspace);

        HttpResponse methodResponse = this.getHttpClient().execute(request);

        int statusCode = methodResponse.getStatusLine().getStatusCode();

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode);

        BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        // System.out.println("Response String: " + result.toString());
    } catch (Exception ex) {

    }

}

From source file:com.cloverstudio.spikademo.couchdb.ConnectionHandler.java

/**
 * Forming a PUT request/* w w  w.j a  v a 2s .c  o  m*/
 * 
 * @param url
 * @param create
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
private static InputStream httpPutRequest(String url, JSONObject create, String userId)
        throws ClientProtocolException, IOException {

    HttpPut httpput = new HttpPut(url);

    httpput.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    httpput.setHeader("Content-Type", "application/json");
    httpput.setHeader("Encoding", "utf-8");
    httpput.setHeader("database", Const.DATABASE);

    if (userId != null && userId.length() > 0)
        httpput.setHeader("user_id", userId);
    else {
        String userIdSaved = SpikaApp.getPreferences().getUserId();
        if (userIdSaved != null)
            httpput.setHeader("user_id", userIdSaved);
    }

    String token = SpikaApp.getPreferences().getUserToken();
    if (token != null && token.length() > 0)
        httpput.setHeader("token", token);

    StringEntity stringEntity = new StringEntity(create.toString(), HTTP.UTF_8);

    httpput.setEntity(stringEntity);

    HttpResponse response = HttpSingleton.getInstance().execute(httpput);
    HttpEntity entity = response.getEntity();

    return entity.getContent();
}

From source file:org.zaizi.alfresco.publishing.marklogic.MarkLogicChannelType.java

@Override
public void publish(final NodeRef nodeToPublish, final Map<QName, Serializable> channelProperties) {
    LOG.info("publish() invoked...");
    final ContentReader reader = contentService.getReader(nodeToPublish, ContentModel.PROP_CONTENT);
    if (reader.exists()) {
        File contentFile;/* w w w  .  j av  a  2 s  .com*/
        boolean deleteContentFileOnCompletion = false;
        if (FileContentReader.class.isAssignableFrom(reader.getClass())) {
            // Grab the content straight from the content store if we can...
            contentFile = ((FileContentReader) reader).getFile();
        } else {
            // ...otherwise copy it to a temp file and use the copy...
            final File tempDir = TempFileProvider.getLongLifeTempDir("marklogic");
            contentFile = TempFileProvider.createTempFile("marklogic", "", tempDir);
            reader.getContent(contentFile);
            deleteContentFileOnCompletion = true;
        }

        HttpClient httpclient = new DefaultHttpClient();
        try {
            final String mimeType = reader.getMimetype();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Publishing node: " + nodeToPublish);
                LOG.debug("ContentFile_MIMETYPE: " + mimeType);
            }

            URI uriPut = publishingHelper.getPutURIFromNodeRefAndChannelProperties(nodeToPublish,
                    channelProperties);

            final HttpPut httpput = new HttpPut(uriPut);
            final FileEntity filenEntity = new FileEntity(contentFile, mimeType);
            httpput.setEntity(filenEntity);

            final HttpResponse response = httpclient.execute(httpput,
                    publishingHelper.getHttpContextFromChannelProperties(channelProperties));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Response Status: " + response.getStatusLine().getStatusCode() + " - Message: "
                        + response.getStatusLine().getReasonPhrase() + " - NodeRef: "
                        + nodeToPublish.toString());
            }
            if (response.getStatusLine().getStatusCode() != STATUS_DOCUMENT_INSERTED) {
                throw new AlfrescoRuntimeException(response.getStatusLine().getReasonPhrase());
            }
        } catch (IllegalStateException illegalEx) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", illegalEx);
            }
            throw new AlfrescoRuntimeException(illegalEx.getLocalizedMessage());
        } catch (IOException ioex) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", ioex);
            }
            throw new AlfrescoRuntimeException(ioex.getLocalizedMessage());
        } catch (URISyntaxException uriSynEx) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", uriSynEx);
            }
            throw new AlfrescoRuntimeException(uriSynEx.getLocalizedMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
            if (deleteContentFileOnCompletion) {
                contentFile.delete();
            }
        }
    }
}

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

/**
 * Test executing an illegal action on an execution.
 *//*from  www.  jav a  2  s  . c o  m*/
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ExecutionResourceTest.process-with-subprocess.bpmn20.xml" })
public void testIllegalExecutionAction() throws Exception {
    Execution execution = runtimeService.startProcessInstanceByKey("processOne");
    assertNotNull(execution);

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

    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_EXECUTION, execution.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_BAD_REQUEST);
    closeResponse(response);
}

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

/**
 * Test executing an illegal action on an execution.
 *///from   w  w  w . j a  va2s  .c  o  m
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ExecutionResourceTest.process-with-subprocess.bpmn20.xml" })
public void testIllegalExecutionAction() throws Exception {
    Execution execution = runtimeService.startProcessInstanceByKey("processOne");
    assertNotNull(execution);

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

    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_EXECUTION, execution.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_BAD_REQUEST);
    closeResponse(response);
}

From source file:org.yaoha.ApiConnector.java

public HttpResponse putNode(String changesetId, OsmNode node)
        throws ClientProtocolException, IOException, ParserConfigurationException, TransformerException,
        OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException {
    URI uri = null;/*from w  w  w  .  jav a  2  s.  com*/
    try {
        uri = new URI("http", apiUrl, "/api/0.6/node/" + String.valueOf(node.getID()), null);
    } catch (URISyntaxException e) {
        Log.e(ApiConnector.class.getSimpleName(),
                "Uploading node " + String.valueOf(node.getID()) + " failed:");
        Log.e(ApiConnector.class.getSimpleName(), e.getMessage());
    }
    HttpPut request = new HttpPut(uri);
    request.setHeader(userAgentHeader);
    String requestString = "";
    requestString = node.serialize(changesetId);
    HttpEntity entity = new StringEntity(requestString, HTTP.UTF_8);
    request.setEntity(entity);
    consumer.sign(request);
    return client.execute(request);
}