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.ovirt.engine.sdk.web.HttpProxyBroker.java

/**
 * updates resource// w  ww. j a v  a 2  s  .  c  o m
 * 
 * @param url
 *            resource url
 * @param entity
 *            resource
 * @param from
 *            from type
 * @param to
 *            to type
 * @param headers
 *            HTTP headers
 * 
 * @return updated resource
 * 
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ServerException
 */
public <F, T> T update(String url, F entity, Class<F> from, Class<T> to, List<Header> headers)
        throws IOException, ClientProtocolException, ServerException {

    HttpPut httpput = new HttpPut(this.urlHelper.combine(url));

    String xmlReq = SerializationHelper.marshall(from, entity);
    HttpEntity httpentity = new StringEntity(xmlReq, StringUtils.UTF8);
    httpput.setEntity(httpentity);

    String xmlRes = this.proxy.execute(httpput, headers, null);
    return unmarshall(from, to, xmlRes);
}

From source file:com.hoccer.api.FileCache.java

public String store(StreamableContent data, int secondsUntilExipred)
        throws ClientProtocolException, IOException, Exception {

    String url = ClientConfig.getFileCacheBaseUri() + "/" + UUID.randomUUID() + "/?expires_in="
            + secondsUntilExipred;//from  ww w  .j a va 2  s .c o m
    LOG.finest("put uri = " + url);
    HttpPut request = new HttpPut(sign(url));

    InputStreamEntity entity = new InputStreamEntity(data.openNewInputStream(), data.getNewStreamLength());
    request.addHeader("Content-Disposition", " attachment; filename=\"" + data.getFilename() + "\"");
    entity.setContentType(data.getContentType());
    request.setEntity(entity);
    request.addHeader("Content-Type", data.getContentType());

    HttpResponse response = getHttpClient().execute(request);

    String responseString = convertResponseToString(response, false);
    LOG.finest("response = " + responseString);

    return responseString;
}

From source file:org.apache.manifoldcf.scriptengine.PUTCommand.java

/** Parse and execute.  Parsing begins right after the command name, and should stop before the trailing semicolon.
*@param sp is the script parser to use to help in the parsing.
*@param currentStream is the current token stream.
*@return true to send a break signal, false otherwise.
*///from ww w . j a  v a2 s .c  o  m
public boolean parseAndExecute(ScriptParser sp, TokenStream currentStream) throws ScriptException {
    VariableReference result = sp.evaluateExpression(currentStream);
    if (result == null)
        sp.syntaxError(currentStream, "Missing result expression");
    Token t = currentStream.peek();
    if (t == null || t.getPunctuation() == null || !t.getPunctuation().equals("="))
        sp.syntaxError(currentStream, "Missing '=' sign");
    currentStream.skip();
    VariableReference send = sp.evaluateExpression(currentStream);
    if (send == null)
        sp.syntaxError(currentStream, "Missing send expression");
    t = currentStream.peek();
    if (t == null || t.getToken() == null || !t.getToken().equals("to"))
        sp.syntaxError(currentStream, "Missing 'to'");
    currentStream.skip();
    VariableReference url = sp.evaluateExpression(currentStream);
    if (url == null)
        sp.syntaxError(currentStream, "Missing URL expression");

    // Perform the actual PUT.
    String urlString = sp.resolveMustExist(currentStream, url).getStringValue();
    Configuration configuration = sp.resolveMustExist(currentStream, send).getConfigurationValue();

    try {
        String json = configuration.toJSON();
        HttpClient client = sp.getHttpClient();
        HttpPut method = new HttpPut(urlString);
        try {
            method.setEntity(new StringEntity(json, ContentType.create("text/plain", StandardCharsets.UTF_8)));
            HttpResponse httpResponse = client.execute(method);
            int resultCode = httpResponse.getStatusLine().getStatusCode();
            String resultJSON = sp.convertToString(httpResponse);
            result.setReference(new VariableResult(resultCode, resultJSON));

            return false;
        } finally {
            //method.releaseConnection();
        }
    } catch (ManifoldCFException e) {
        throw new ScriptException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ScriptException(e.getMessage(), e);
    }
}

From source file:org.hl7.fhir.client.ClientUtils.java

public static <T extends Resource> ResourceRequest<T> issuePutRequest(URI resourceUri, byte[] payload,
        String resourceFormat, HttpHost proxy) {
    HttpPut httpPut = new HttpPut(resourceUri);
    return issueResourceRequest(resourceFormat, httpPut, payload, null, proxy);
}

From source file:org.mobicents.slee.enabler.rest.client.RESTClientEnablerChildSbb.java

@Override
public void execute(RESTClientEnablerRequest request) throws Exception {

    // validate request
    if (request == null) {
        throw new NullPointerException("request is null");
    }/*from ww  w  .  ja v  a2s. c o  m*/
    if (request.getType() == null) {
        throw new NullPointerException("request type is null");
    }
    if (request.getUri() == null) {
        throw new NullPointerException("request uri is null");
    }

    // create http request
    HttpUriRequest httpRequest = null;
    switch (request.getType()) {
    case DELETE:
        httpRequest = new HttpDelete(request.getUri());
        break;
    case GET:
        httpRequest = new HttpGet(request.getUri());
        break;
    case POST:
        httpRequest = new HttpPost(request.getUri());
        break;
    case PUT:
        httpRequest = new HttpPut(request.getUri());
        break;
    default:
        throw new IllegalArgumentException("unknown request type");
    }

    // add headers, if any
    if (request.getHeaders() != null) {
        for (Header h : request.getHeaders()) {
            httpRequest.addHeader(h);
        }
    }

    // sign request using oauth, if needed
    if (request.getOAuthConsumer() != null) {
        request.getOAuthConsumer().sign(httpRequest);
    }

    // add content, if any
    if (request.getContent() != null) {
        if (!(httpRequest instanceof HttpEntityEnclosingRequest)) {
            throw new IllegalArgumentException("request includes content but type does not allows content");
        }
        if (request.getContentType() == null) {
            throw new IllegalArgumentException("request includes content but no content type");
        }
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(request.getContent());
        if (request.getContentEncoding() != null)
            entity.setContentEncoding(request.getContentEncoding());
        entity.setContentType(request.getContentType());
        ((HttpEntityEnclosingRequest) httpRequest).setEntity(entity);
    }

    // get http client activity and attach to related aci
    HttpClientActivity activity = httpProvider.createHttpClientActivity(true, null);
    ActivityContextInterface aci = httpClientActivityContextInterfaceFactory
            .getActivityContextInterface(activity);
    aci.attach(this.sbbContext.getSbbLocalObject());

    // execute request on the activity
    activity.execute(httpRequest, request);
}

From source file:com.mashape.unirest.android.http.HttpClientHelper.java

private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }/*  w w  w  .  j ava 2s  . co  m*/
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        //reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        //reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:org.wso2.carbon.esb.nhttp.transport.test.DefaultRequestContentTypeTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Test for DEFAULT_REQUEST_TYPE for nhttp transport")
public void testReturnContentType() throws Exception {
    try {//from  w  w w  . java2 s .co  m
        String url = getApiInvocationURL("defaultRequestContentTypeApi").concat("?symbol=wso2");
        HttpUriRequest request = new HttpPut(url);
        DefaultHttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(request);
        Assert.assertNotNull(response);
        Assert.assertTrue(getResponse(response).toString().contains("WSO2"));
    } catch (IOException e) {
        log.error("Error while sending the request to the endpoint. ", e);
    }

}

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

public void addComponentVersionLink(String componentName, String versionName, String linkTitle, String linkURL)
        throws JSONException, IOException {
    String uri = url + "/cli/version/addLink?component=" + encodePath(componentName) + "&version="
            + encodePath(versionName) + "&linkName=" + encodePath(linkTitle) + "&link=" + encodePath(linkURL);

    HttpPut method = new HttpPut(uri);
    invokeMethod(method);//from w  w w .j av  a2 s.  com
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Put response./* w  ww.java2  s .  co m*/
 *
 * @param url the url
 * @param json the json
 * @param httpClient the http client
 * @return the http response
 */
public static synchronized HttpResponse putResponse(final String url, final String json,
        final CloseableHttpClient httpClient) {

    try {
        checkHTTPClient(httpClient);
        final HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPut.setHeader(HttpHeaders.ACCEPT, "application/json");

        final StringEntity params = new StringEntity(json);
        httpPut.setEntity(params);

        final CloseableHttpResponse response = httpClient.execute(httpPut);
        setLogString("Status == " + response.getStatusLine(), true);
        return response;

    } catch (IOException | HTTPClientException e) {
        setLogString("Error executing HTTPS method. Reason ::: " + e, true);
        return null;
    }
}

From source file:com.ecofactor.qa.automation.drapi.HTTPSClient.java

/**
 * Put response./* w w w  .j  a va2  s  .c  o  m*/
 * @param url the url
 * @param json the json
 * @param httpClient the http client
 * @return the http response
 */
public static synchronized HttpResponse putResponse(final String url, final String json,
        final CloseableHttpClient httpClient) {

    try {
        checkHTTPClient(httpClient);
        final HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPut.setHeader(HttpHeaders.ACCEPT, "application/json");

        final StringEntity params = new StringEntity(json);
        httpPut.setEntity(params);

        final CloseableHttpResponse response = httpClient.execute(httpPut);
        setLogString("URL Values of the API \n" + url + "\n" + json, true);
        setLogString("Status == " + response.getStatusLine(), true);
        // setLogString("response " + response, true);
        return response;

    } catch (IOException | HTTPClientException e) {
        setLogString("Error executing HTTPS method. Reason ::: " + e, true);
        return null;
    }
}