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:com.sonatype.nexus.perftest.maven.ArtifactDeployer.java

private void deploy0(HttpEntity entity, String groupId, String artifactId, String version, String extension)
        throws IOException {
    StringBuilder path = new StringBuilder();

    path.append(groupId.replace('.', '/')).append('/');
    path.append(artifactId).append('/');
    path.append(version).append('/');
    path.append(artifactId).append('-').append(version).append(extension);

    HttpPut httpPut = new HttpPut(repoUrl + path);
    httpPut.setEntity(entity);// ww w .j  a v a 2 s.co  m

    HttpResponse response;
    try {
        response = httpclient.execute(httpPut);

        try {
            EntityUtils.consume(response.getEntity());
        } finally {
            httpPut.releaseConnection();
        }
    } catch (IOException e) {
        throw new IOException("IOException executing " + httpPut.toString(), e);
    }

    if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
        throw new IOException(httpPut.toString() + " : " + response.getStatusLine().toString());
    }
}

From source file:eionet.webq.xforms.XFormsHTTPSubmissionHandler.java

@SuppressWarnings("unchecked")
@Override/*from   ww w . j a va  2s.  c o m*/
protected void put(String uri, String body, String type, String encoding) throws XFormsException {
    HttpEntityEnclosingRequestBase httpMethod = new HttpPut(uri);
    httpRequestAuthHandler.addAuthToHttpRequest(httpMethod, getContext());

    try {
        configureRequest(httpMethod, body, type, encoding);

        execute(httpMethod);
    } catch (XFormsException e) {
        throw e;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:com.magnet.tools.tests.RestStepDefs.java

@When("^I send the following Rest queries:$")
public static void sendRestQueries(List<RestQueryEntry> entries) throws Throwable {
    for (RestQueryEntry e : entries) {
        String url = expandVariables(e.url);
        StatusLine statusLine;//from  ww  w  .j a v a  2  s. c  o m
        HttpUriRequest httpRequest;
        HttpEntity entityResponse;
        CloseableHttpClient httpClient = getTestHttpClient(new URI(url));

        Object body = isStringNotEmpty(e.body) ? e.body : getRef(e.bodyRef);

        String verb = e.verb;
        if ("GET".equalsIgnoreCase(verb)) {

            httpRequest = new HttpGet(url);
        } else if ("POST".equalsIgnoreCase(verb)) {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new StringEntity(expandVariables((String) body)));
        } else if ("PUT".equalsIgnoreCase(verb)) {
            httpRequest = new HttpPut(url);
            ((HttpPut) httpRequest).setEntity(new StringEntity(expandVariables((String) body)));
        } else if ("DELETE".equalsIgnoreCase(verb)) {
            httpRequest = new HttpDelete(url);
        } else {
            throw new IllegalArgumentException("Unknown verb: " + e.verb);
        }
        String response;
        setHttpHeaders(httpRequest, e);
        ScenarioUtils.log("Sending HTTP Request: " + e.url);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            statusLine = httpResponse.getStatusLine();
            entityResponse = httpResponse.getEntity();
            InputStream is = entityResponse.getContent();
            response = IOUtils.toString(is);
            EntityUtils.consume(entityResponse);
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (Exception ex) {
                    /* do nothing */ }
            }
        }

        ScenarioUtils.log("====> Received response body:\n " + response);
        Assert.assertNotNull(response);
        setHttpResponseBody(response);
        if (isStringNotEmpty(e.expectedResponseBody)) { // inline the assertion check on http response body
            ensureHttpResponseBody(e.expectedResponseBody);
        }

        if (isStringNotEmpty(e.expectedResponseBodyRef)) { // inline the assertion check on http response body
            ensureHttpResponseBody((String) getRef(e.expectedResponseBodyRef));
        }

        if (isStringNotEmpty(e.expectedResponseContains)) { // inline the assertion check on http response body
            ensureHttpResponseBodyContains(e.expectedResponseContains);
        }

        if (null == statusLine) {
            throw new IllegalArgumentException("Status line in http response is null, request was " + e.url);
        }

        int statusCode = statusLine.getStatusCode();
        ScenarioUtils.log("====> Received response code: " + statusCode);
        setHttpResponseStatus(statusCode);
        if (isStringNotEmpty(e.expectedResponseStatus)) { // inline the assertion check on http status
            ensureHttpResponseStatus(Integer.parseInt(e.expectedResponseStatus));
        }

    }

}

From source file:org.sonatype.nexus.test.utils.hc4client.Hc4MethodCall.java

/**
 * Constructor.// w  ww  .  j a v  a 2 s. c om
 *
 * @param helper     The parent HTTP client helper.
 * @param method     The method name.
 * @param requestUri The request URI.
 * @param hasEntity  Indicates if the call will have an entity to send to the server.
 */
public Hc4MethodCall(Hc4ClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new HttpGet(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new HttpPost(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new HttpPut(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HttpHead(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new HttpDelete(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            // CONNECT unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new HttpOptions(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new HttpTrace(requestUri);
        } else {
            // custom HTTP verbs unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        }

        this.httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,
                this.clientHelper.isFollowRedirects());
        // retry handler setting unsupported (legaacy ITs use default HC4 retry handler)
        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:org.openhim.mediator.engine.connectors.HTTPConnector.java

private HttpUriRequest buildApacheHttpRequest(MediatorHTTPRequest req)
        throws URISyntaxException, UnsupportedEncodingException {
    HttpUriRequest uriReq;/*from  w w  w  .  jav a2s  .  c  om*/

    switch (req.getMethod()) {
    case "GET":
        uriReq = new HttpGet(buildURI(req));
        break;
    case "POST":
        uriReq = new HttpPost(buildURI(req));
        StringEntity entity = new StringEntity(req.getBody());
        ((HttpPost) uriReq).setEntity(entity);
        break;
    case "PUT":
        uriReq = new HttpPut(buildURI(req));
        StringEntity putEntity = new StringEntity(req.getBody());
        ((HttpPut) uriReq).setEntity(putEntity);
        break;
    case "DELETE":
        uriReq = new HttpDelete(buildURI(req));
        break;
    default:
        throw new UnsupportedOperationException(req.getMethod() + " requests not supported");
    }

    copyHeaders(req, uriReq);
    return uriReq;
}

From source file:com.phonegap.plugins.CloudStorage.java

/**
  * Executes the request and returns PluginResult.
  *//from w  ww .j  a  v  a  2  s . c  o m
  * @param action        The action to execute.
  * @param data          JSONArry of arguments for the plugin.
  *                   'url': server url for upload
  *                   'file URI': URI of file to upload
 *                   'X-Auth-Token': authentication header to use for this request
  * @param callbackId    The callback id used when calling back into JavaScript.
  * @return              A PluginResult object with a status and message.
  * 
  */
public PluginResult execute(String action, JSONArray data, String callbackId) {
    PluginResult result = null;
    if (ACTION_UPLOAD.equals(action) || ACTION_STORE.equals(action)) {
        try {
            String serverUrl = data.get(0).toString();
            String imageURI = data.getString(1).toString();
            String token = null;
            if (ACTION_UPLOAD.equals(action)) {
                token = data.getString(2).toString();
            }

            File file = new File(new URI(imageURI));
            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPut httpput = new HttpPut(serverUrl);

                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
                if (ACTION_UPLOAD.equals(action)) {
                    reqEntity.setContentType("binary/octet-stream");
                    reqEntity.setChunked(true); // Send in multiple parts if needed
                } else {
                    reqEntity.setContentType("image/jpg");
                }

                httpput.setEntity(reqEntity);
                if (token != null) {
                    httpput.addHeader("X-Auth-Token", token);
                }

                HttpResponse response = httpclient.execute(httpput);
                Log.d(LOG_TAG, "http response: " + response.getStatusLine().getStatusCode()
                        + response.getStatusLine().getReasonPhrase());
                //Do something with response...
                result = new PluginResult(Status.OK, response.getStatusLine().getStatusCode());
            } catch (Exception e) {
                Log.d(LOG_TAG, e.getLocalizedMessage());
                result = new PluginResult(Status.ERROR);
            }
        } catch (JSONException e) {
            Log.d(LOG_TAG, e.getLocalizedMessage());
            result = new PluginResult(Status.JSON_EXCEPTION);
        } catch (Exception e1) {
            Log.d(LOG_TAG, e1.getLocalizedMessage());
            result = new PluginResult(Status.ERROR);
        }
    }
    return result;
}

From source file:net.modelbased.proasense.storage.registry.RestRequest.java

public static String putData(URI uri, String data) {
    URI target = null;/*  w  w w  .  j a  v a2 s. c om*/
    try {
        target = new URI(uri.toString() + DISPATCHER_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    HttpClient client = new DefaultHttpClient();
    HttpPut request = new HttpPut(target);
    request.setHeader("Content-type", "application/json");
    String response = null;
    try {
        StringEntity seContent = new StringEntity(data);
        seContent.setContentType("text/json");
        request.setEntity(seContent);
        response = resolveResponse(client.execute(request));
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (response.trim().length() > 2) {
        throw new IllegalAccessError("Sensor not registred: " + response);
    }
    return response;
}

From source file:org.elasticsearch.shell.command.HttpPutCommand.java

@SuppressWarnings("unused")
public HttpCommandResponse execute(String url, HttpParameters parameters, String charsetName)
        throws IOException {
    HttpPut httpPut = new HttpPut(url);
    httpPut.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName(charsetName)));
    return new HttpCommandResponse(shellHttpClient.getHttpClient().execute(httpPut));
}

From source file:org.jclouds.http.apachehc.ApacheHCUtils.java

public HttpUriRequest convertToApacheRequest(HttpRequest request) {
    HttpUriRequest apacheRequest;/*from   w w  w  .  j a v  a2s  .c  o m*/
    if (request.getMethod().equals(HttpMethod.HEAD)) {
        apacheRequest = new HttpHead(request.getEndpoint());
    } else if (request.getMethod().equals(HttpMethod.GET)) {
        apacheRequest = new HttpGet(request.getEndpoint());
    } else if (request.getMethod().equals(HttpMethod.DELETE)) {
        apacheRequest = new HttpDelete(request.getEndpoint());
    } else if (request.getMethod().equals(HttpMethod.PUT)) {
        apacheRequest = new HttpPut(request.getEndpoint());
        apacheRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    } else if (request.getMethod().equals(HttpMethod.POST)) {
        apacheRequest = new HttpPost(request.getEndpoint());
    } else {
        final String method = request.getMethod();
        if (request.getPayload() != null)
            apacheRequest = new HttpEntityEnclosingRequestBase() {

                @Override
                public String getMethod() {
                    return method;
                }

            };
        else
            apacheRequest = new HttpRequestBase() {

                @Override
                public String getMethod() {
                    return method;
                }

            };
        HttpRequestBase.class.cast(apacheRequest).setURI(request.getEndpoint());
    }
    Payload payload = request.getPayload();

    // Since we may remove headers, ensure they are added to the apache
    // request after this block
    if (apacheRequest instanceof HttpEntityEnclosingRequest) {
        if (payload != null) {
            addEntityForContent(HttpEntityEnclosingRequest.class.cast(apacheRequest), payload);
        }
    } else {
        apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
    }

    for (Map.Entry<String, String> entry : request.getHeaders().entries()) {
        String header = entry.getKey();
        // apache automatically tries to add content length header
        if (!header.equals(HttpHeaders.CONTENT_LENGTH))
            apacheRequest.addHeader(header, entry.getValue());
    }
    apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT);
    return apacheRequest;
}