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

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

Introduction

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

Prototype

public HttpPut(final String uri) 

Source Link

Usage

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 w w.j  a v a  2  s. c  o 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:org.kairosdb.plugin.announce.AnnounceService.java

/**
 * Announces service/*  w  ww.java2  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:org.apache.activemq.transport.discovery.http.HTTPDiscoveryAgent.java

synchronized private void doRegister(String service) {
    String url = registryURL;/*from   w  w  w .  j a v  a  2 s  . c  om*/
    try {
        HttpPut method = new HttpPut(url);
        method.addHeader("service", service);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String responseBody = httpClient.execute(method, handler);
        LOG.debug("PUT to " + url + " got a " + responseBody);
    } catch (Exception e) {
        LOG.debug("PUT to " + url + " failed with: " + e);
    }
}

From source file:com.sinacloud.scs.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request/*from w ww.  ja  v  a2  s .c o  m*/
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 *
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();

    /*
     * HttpClient cannot handle url in pattern of "http://host//path", so we
     * have to escape the double-slash between endpoint and resource-path
     * into "/%2F"
     */
    String uri = HttpUtils.appendUri(endpoint.toString(), request.getResourcePath(), true);
    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * Enable 100-continue support for PUT operations, since this is
         * where we're potentially uploading large amounts of data and want
         * to find out as early as possible if an operation will fail. We
         * don't want to do this for all operations since it will cause
         * extra latency in the network interaction.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new SCSClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}

From source file:com.impetus.client.couchdb.utils.CouchDBTestUtils.java

/**
 * Creates the database./*from  w  w w  .ja  v a 2  s  .  co m*/
 * 
 * @param databaseName
 *            the database name
 * @param client
 *            the client
 * @param httpHost
 *            the http host
 */
public static void createDatabase(String databaseName, HttpClient client, HttpHost httpHost) {
    HttpResponse response = null;
    try {
        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SEPARATOR + databaseName, null, null);
        HttpPut put = new HttpPut(uri);
        response = client.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
    } catch (URISyntaxException e) {

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    } finally {
        CouchDBUtils.closeContent(response);
    }
}

From source file:com.google.dataconnector.client.fetchrequest.HttpFetchStrategy.java

/**
 * Based on the inbound request type header, determine the correct http
 * method to use.  If a method cannot be determined (or not specified),
 * HTTP GET is attempted.// ww  w. j ava2  s .  c  om
 */
HttpRequestBase getMethod(FetchRequest request) {
    String method = null;
    for (MessageHeader h : request.getHeadersList()) {
        if ("x-sdc-http-method".equalsIgnoreCase(h.getKey())) {
            method = h.getValue().toUpperCase();
        }
    }

    LOG.info(request.getId() + ": method=" + method + ", resource=" + request.getResource()
            + ((request.hasContents()) ? ", payload_size=" + request.getContents().size() : ""));

    if (method == null) {
        LOG.info(request.getId() + ": No http method specified. Default to GET.");
        method = "GET";
    }

    if ("GET".equals(method)) {
        return new HttpGet(request.getResource());
    }
    if ("POST".equals(method)) {
        HttpPost httpPost = new HttpPost(request.getResource());
        if (request.hasContents()) {
            LOG.debug(request.getId() + ": Content = " + new String(request.getContents().toByteArray()));
            httpPost.setEntity(new ByteArrayEntity(request.getContents().toByteArray()));
        }
        return httpPost;
    }
    if ("PUT".equals(method)) {
        HttpPut httpPut = new HttpPut(request.getResource());
        if (request.hasContents()) {
            LOG.debug(request.getId() + ": Content = " + new String(request.getContents().toByteArray()));
            httpPut.setEntity(new ByteArrayEntity(request.getContents().toByteArray()));
        }
        return httpPut;
    }
    if ("DELETE".equals(method)) {
        return new HttpDelete(request.getResource());
    }
    if ("HEAD".equals(method)) {
        return new HttpHead(request.getResource());
    }
    LOG.info(request.getId() + ": Unknown method " + method);
    return null;
}

From source file:com.basho.riak.client.http.util.ClientHelper.java

/**
 * See/*  w w w.ja v  a 2  s .  c o m*/
 * {@link RiakClient#setBucketSchema(String, com.basho.riak.client.http.RiakBucketInfo, RequestMeta)}
 */
public HttpResponse setBucketSchema(String bucket, JSONObject schema, RequestMeta meta) {
    if (schema == null) {
        schema = new JSONObject();
    }
    if (meta == null) {
        meta = new RequestMeta();
    }

    meta.setHeader(Constants.HDR_ACCEPT, Constants.CTYPE_JSON);

    HttpPut put = new HttpPut(ClientUtils.makeURI(config, bucket));
    ByteArrayEntity entity = new ByteArrayEntity(utf8StringToBytes(schema.toString()));
    entity.setContentType(Constants.CTYPE_JSON_UTF8);
    put.setEntity(entity);

    return executeMethod(bucket, null, put, meta);
}

From source file:org.bedework.util.http.HttpUtil.java

/** Specify the next method by name.
 *
 * @param name of the method/*from   w  w  w .  ja  v a2 s . co  m*/
 * @param uri target
 * @return method object or null for unknown
 */
public static HttpRequestBase findMethod(final String name, final URI uri) {
    final String nm = name.toUpperCase();

    if ("PUT".equals(nm)) {
        return new HttpPut(uri);
    }

    if ("GET".equals(nm)) {
        return new HttpGet(uri);
    }

    if ("DELETE".equals(nm)) {
        return new HttpDelete(uri);
    }

    if ("POST".equals(nm)) {
        return new HttpPost(uri);
    }

    if ("PROPFIND".equals(nm)) {
        return new HttpPropfind(uri);
    }

    if ("MKCALENDAR".equals(nm)) {
        return new HttpMkcalendar(uri);
    }

    if ("MKCOL".equals(nm)) {
        return new HttpMkcol(uri);
    }

    if ("OPTIONS".equals(nm)) {
        return new HttpOptions(uri);
    }

    if ("REPORT".equals(nm)) {
        return new HttpReport(uri);
    }

    if ("HEAD".equals(nm)) {
        return new HttpHead(uri);
    }

    return null;
}

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

public String setSystemProperty(String name, String value, boolean isSecure) throws IOException {
    String result;//from  w  w  w. ja v  a  2s .c o  m
    if ("".equals(name)) {
        throw new IOException("a required argument was not supplied");
    }

    String uri = url + "/cli/systemConfiguration/propValue?name=" + encodePath(name) + "&value="
            + encodePath(value) + "&isSecure=" + encodePath(String.valueOf(isSecure));

    HttpPut method = new HttpPut(uri);
    invokeMethod(method);
    if (isSecure) {
        result = name + "=****";
    } else {
        result = name + "=" + value;
    }
    return result;
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpPutCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;//from w ww .ja v a 2s  . co  m
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpPut putRequest = new HttpPut(url);
        putRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        putRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(putRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute PUT URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute PUT URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("PUT URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}