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:nl.esciencecenter.octopus.webservice.api.SandboxedJob.java

private void putState2Callback() throws IOException {
    if (request != null && request.status_callback_url != null) {
        String body = getStatusResponse().toJson();
        HttpPut put = new HttpPut(request.status_callback_url);
        HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
        put.setEntity(entity);/*w w  w . j  a v a2s .  c  o  m*/
        httpClient.execute(put);
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.rest.RequestHandlerImpl.java

private HttpUriRequest buildRequest(Request request) {
    String requestURL = URLUtil.buildURLForRequest(request);
    log.info("Request URL: " + requestURL);
    log.info("Request Type: " + request.getRequestType());
    HttpUriRequest httpUriRequest = null;
    switch (request.getRequestType()) {
    case GET://from w w  w. j  av  a  2 s . c om
        httpUriRequest = new HttpGet(requestURL);
        break;
    case POST:
        httpUriRequest = new HttpPost(requestURL);
        break;
    case PUT:
        httpUriRequest = new HttpPut(requestURL);
        break;
    case DELETE:
        httpUriRequest = new HttpDelete(requestURL);
        break;
    case HEAD:
        httpUriRequest = new HttpHead(requestURL);
        break;
    }
    return httpUriRequest;
}

From source file:io.vertx.ext.consul.dc.ConsulAgent.java

public String createAclToken(String rules) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://" + getHost() + ":" + getHttpPort() + "/v1/acl/create");
    put.addHeader("X-Consul-Token", masterToken);
    Map<String, String> tokenRequest = new HashMap<>();
    tokenRequest.put("Type", "client");
    tokenRequest.put("Rules", rules);
    put.setEntity(new StringEntity(mapper.writeValueAsString(tokenRequest)));
    HttpResponse response = client.execute(put);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Bad response");
    }//ww  w  .  ja  va2s . c  o m
    Map<String, String> tokenResponse = mapper.readValue(EntityUtils.toString(response.getEntity()),
            new TypeReference<Map<String, String>>() {
            });
    return tokenResponse.get("ID");
}

From source file:org.dspace.identifier.ezid.EZIDRequest.java

/**
 * Create an identifier with a given name. The name is the end of the
 * request path. Note: to "reserve" a given identifier, include "_status =
 * reserved" in {@link metadata}.//from  www.  j  a v  a 2s. co  m
 *
 * @param metadata ANVL-encoded key/value pairs.
 * @return
 */
public EZIDResponse create(String name, Map<String, String> metadata)
        throws IOException, IdentifierException, URISyntaxException {
    // PUT path [+metadata]
    HttpPut request;
    URI uri = new URI(scheme, host, ID_PATH + authority + '/' + name, null);
    log.debug("EZID create {}", uri.toASCIIString());
    request = new HttpPut(uri);
    if (null != metadata) {
        try {
            request.setEntity(new StringEntity(formatMetadata(metadata), UTF_8));
        } catch (UnsupportedEncodingException ex) {
            /* SNH */ }
    }
    HttpResponse response = client.execute(request);
    return new EZIDResponse(response);
}

From source file:com.aiven.seafox.controller.http.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*w w  w  .j av a2  s  .  c  o m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Request.Method.GET:
        return new HttpGet(request.getUrl());
    case Request.Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Request.Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Request.Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Request.Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:v2.service.generic.library.utils.HttpClientUtil.java

public static HttpResponsePOJO jsonRequest(String url, String json, String requestType,
        Map<String, String> headers) throws Exception {
    HttpClient httpclient = createHttpClient();
    //        HttpEntityEnclosingRequestBase request=null;
    HttpRequestBase request = null;/*from ww w .  jav  a 2 s .c  o  m*/
    if ("POST".equalsIgnoreCase(requestType)) {
        request = new HttpPost(url);
    } else if ("PUT".equalsIgnoreCase(requestType)) {
        request = new HttpPut(url);
    } else if ("GET".equalsIgnoreCase(requestType)) {
        request = new HttpGet(url);
    } else if ("DELETE".equalsIgnoreCase(requestType)) {
        request = new HttpDelete(url);
    }
    if (json != null) {
        if (!"GET".equalsIgnoreCase(requestType) && (!"DELETE".equalsIgnoreCase(requestType))) {
            StringEntity params = new StringEntity(json, "UTF-8");
            params.setContentType("application/json;charset=UTF-8");
            ((HttpEntityEnclosingRequestBase) request).setEntity(params);
        }
    }
    if (headers == null) {
        request.addHeader("content-type", "application/json");
    } else {
        Set<String> keySet_header = headers.keySet();
        for (String key : keySet_header) {
            request.setHeader(key, headers.get(key));
        }
    }
    HttpResponsePOJO result = invoke(httpclient, request);
    return result;
}

From source file:de.dentrassi.pm.jenkins.UploaderV3.java

@Override
public boolean complete() {
    if (this.failed) {
        return false;
    }//from   w  w  w. j a va  2 s  . c om

    try {
        closeTransfer();

        final URIBuilder uri = new URIBuilder(String.format("%s/api/v3/upload/archive/channel/%s",
                this.serverUrl, URIUtil.encodeWithinPath(this.channelId)));

        this.listener.getLogger().println("API endpoint: " + uri.build().toString());

        final HttpPut httppost = new HttpPut(uri.build());

        final String encodedAuth = Base64
                .encodeBase64String(("deploy:" + this.deployKey).getBytes("ISO-8859-1"));
        httppost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);

        final InputStream stream = new FileInputStream(this.tempFile);
        try {
            httppost.setEntity(new InputStreamEntity(stream, this.tempFile.length()));

            final HttpResponse response = this.client.execute(httppost);
            final HttpEntity resEntity = response.getEntity();

            this.listener.getLogger().println("Call returned: " + response.getStatusLine());

            if (resEntity != null) {
                switch (response.getStatusLine().getStatusCode()) {
                case 200:
                    processUploadResult(makeString(resEntity));
                    return true;
                case 404:
                    this.listener.error(
                            "Failed to find upload endpoint V3. This could mean that you configured a wrong server URL or that the server does not support the Upload V3. You will need a version 0.14+ of Eclipse Package Drone. It could also mean that you did use wrong credentials.");
                    return false;
                default:
                    if (!handleError(response)) {
                        addErrorMessage("Failed to upload: " + response.getStatusLine());
                    }
                    return false;
                }
            }

            addErrorMessage("Did not receive a result");

            return false;
        } finally {
            stream.close();
        }
    } catch (final Exception e) {
        e.printStackTrace(this.listener.error("Failed to perform archive upload"));
        return false;
    }
}

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

/**
 * ???deviceId????./*from w  w w  . jav  a2  s .c  o  m*/
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /vibration/vibrate?deviceId=123456789&mediId=xxxx
 * </pre>
 * <pre>
 * ??
 * result?1???????
 * </pre>
 */
public void testPutVibrateInvalidDeviceId() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(VibrationProfileConstants.PROFILE_NAME);
    builder.setAttribute(VibrationProfileConstants.ATTRIBUTE_VIBRATE);
    builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, "123456789");
    builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken());
    try {
        HttpUriRequest request = new HttpPut(builder.toString());
        JSONObject root = sendRequest(request);
        assertResultError(ErrorCode.NOT_FOUND_DEVICE.getCode(), root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    }
}

From source file:nl.esciencecenter.osmium.mac.MacITCase.java

/**
 * Submit status to a callback server using MAC Access authentication.
 * /*from   w  w  w. j a va2s. c o m*/
 * @throws URISyntaxException
 * @throws ClientProtocolException
 * @throws IOException
 */
@Test
public void test() throws URISyntaxException, ClientProtocolException, IOException {
    URI url = getServerURI();

    // TODO throw better exception than NullPointerException when property can not be found.

    String state = "STOPPED";
    HttpPut request = new HttpPut(url);
    request.setEntity(new StringEntity(state));

    String mac_id = "eyJzYWx0IjogIjU3MjY0NCIsICJleHBpcmVzIjogMTM4Njc3MjEwOC4yOTIyNTUsICJ1c2VyaWQiOiAiam9ibWFuYWdlciJ9KBJRMeTW2G9I6jlYwRj6j8koAek=";
    String mac_key = "_B1YfcqEYpZxyTx_-411-QdBOSI=";
    URI scope = new URI(url.getScheme(), null, url.getHost(), url.getPort(), null, null, null);
    ImmutableList<MacCredential> macs = ImmutableList.of(new MacCredential(mac_id, mac_key, scope));
    HttpClient httpClient = new DefaultHttpClient();
    httpClient = JobLauncherService.macifyHttpClient((AbstractHttpClient) httpClient, macs);

    HttpResponse response = httpClient.execute(request);

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(EntityUtils.toString(response.getEntity())).startsWith("MAC id=\"" + mac_id);
    // asserting rest of request.header[AUTHORIZATION] can not be done due to embedded timestamp and changing hostname/port.
}