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.impetus.kundera.ycsb.utils.CouchDBOperationUtils.java

public void createdatabase(String keyspace, String host, int port) throws URISyntaxException, IOException

{
    initiateClient(host, port);/*from   ww  w .ja v a2 s.  c om*/
    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
            CouchDBConstants.URL_SAPRATOR + keyspace.toLowerCase(), null, null);

    HttpPut put = new HttpPut(uri);
    HttpResponse putRes = null;
    try {
        // creating database.
        logger.info("Creating database " + keyspace);
        putRes = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
    } finally {
        CouchDBUtils.closeContent(putRes);
    }
}

From source file:com.yahoo.gondola.container.client.ApacheHttpComponentProxyClient.java

/**
 * Proxies the request to the destination host.
 *
 * @param request The original request//w w  w.jav  a2s  .  c  o  m
 * @param baseUri The target App URL
 * @return the response of the proxied request
 */
@Override
public Response proxyRequest(ContainerRequestContext request, String baseUri) throws IOException {
    String method = request.getMethod();
    String requestURI = request.getUriInfo().getRequestUri().getPath();
    CloseableHttpResponse proxiedResponse;
    switch (method) {
    case "GET":
        proxiedResponse = executeRequest(new HttpGet(baseUri + requestURI), request);
        break;
    case "PUT":
        proxiedResponse = executeRequest(new HttpPut(baseUri + requestURI), request);
        break;
    case "POST":
        proxiedResponse = executeRequest(new HttpPost(baseUri + requestURI), request);
        break;
    case "DELETE":
        proxiedResponse = executeRequest(new HttpDelete(baseUri + requestURI), request);
        break;
    case "PATCH":
        proxiedResponse = executeRequest(new HttpPatch(baseUri + requestURI), request);
        break;
    default:
        throw new IllegalStateException("Method not supported: " + method);
    }

    return getResponse(proxiedResponse);
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }/*from w w w. j  av  a  2  s.  c  om*/
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:org.metaeffekt.dcc.agent.UnitBasedEndpointUriBuilder.java

public HttpUriRequest buildHttpUriRequest(Commands command, Id<DeploymentId> deploymentId, Id<UnitId> unitId,
        Id<PackageId> packageId, Map<String, byte[]> executionProperties) {
    Validate.isTrue(executionProperties != null && !executionProperties.isEmpty());

    StringBuilder sb = new StringBuilder("/");
    sb.append(PATH_ROOT).append("/");
    sb.append(deploymentId).append("/");
    sb.append("packages").append("/").append(packageId).append("/");
    sb.append("units").append("/").append(unitId).append("/");
    sb.append(command);//ww w.  j a  va  2 s  .  co m
    String path = sb.toString();

    URIBuilder uriBuilder = createUriBuilder();
    uriBuilder.setPath(path);
    URI uri;
    try {
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpPut put = new HttpPut(uri);

    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    for (Map.Entry<String, byte[]> entry : executionProperties.entrySet()) {
        multipartBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }

    put.setEntity(multipartBuilder.build());
    if (requestConfig != null) {
        put.setConfig(requestConfig);
    }
    return put;
}

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

/**
 * deviceId???ondeviceorientation???.//w w w  .j  a v  a  2 s .c  o  m
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /deviceorientation/ondeviceorientation
 * </pre>
 * <pre>
 * ??
 * result?1???????
 * </pre>
 */
public void testPutOnDeviceOrientation001() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(DeviceOrientationProfileConstants.PROFILE_NAME);
    builder.setAttribute(DeviceOrientationProfileConstants.ATTRIBUTE_ON_DEVICE_ORIENTATION);
    builder.addParameter(DConnectProfileConstants.PARAM_SESSION_KEY, getClientId());
    builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken());
    try {
        HttpUriRequest request = new HttpPut(builder.toString());
        JSONObject root = sendRequest(request);
        assertResultError(ErrorCode.EMPTY_DEVICE_ID.getCode(), root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    }
}

From source file:com.asposewords.restfulapi.HttpClientClass.java

public String httpPutMethod(String converstionFormat, String fileName) throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = null;//from w  ww.  j av a  2s  .com
    String line = "";
    put = new HttpPut("http://localhost:8080/AsposeWords/rest/words/convert");
    put.addHeader("content-type", "text/plain");
    put.addHeader("src", fileName);
    put.addHeader("format", converstionFormat);
    try {
        HttpResponse response = client.execute(put);
        line = "" + response.getStatusLine().getStatusCode();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpClientClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HttpClientClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    return line;
}

From source file:org.talend.dataprep.api.service.command.dataset.CloneDataSet.java

/**
 * Constructor./* ww  w .  j a v a2  s.  c o m*/
 *
 * @param dataSetId the requested dataset id.
 * @param folderPath the folder to clone the dataset
 * @param cloneName the cloned name
 */
public CloneDataSet(String dataSetId, String folderPath, String cloneName) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {
        try {
            URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/clone/" + dataSetId);
            if (StringUtils.isNotEmpty(folderPath)) {
                uriBuilder.addParameter("folderPath", folderPath);
            }
            if (StringUtils.isNotEmpty(cloneName)) {
                uriBuilder.addParameter("cloneName", cloneName);
            }
            return new HttpPut(uriBuilder.build());
        } catch (URISyntaxException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        }
    });

    onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_COPY_DATASET_CONTENT, e,
            ExceptionContext.build().put("id", dataSetId)));

    on(HttpStatus.OK, HttpStatus.BAD_REQUEST).then((httpRequestBase, httpResponse) -> {
        try {
            // we transfer status code and content type
            return new HttpResponse(httpResponse.getStatusLine().getStatusCode(), //
                    IOUtils.toString(httpResponse.getEntity().getContent()), //
                    httpResponse.getStatusLine().getStatusCode() == HttpStatus.BAD_REQUEST.value() ? //
            APPLICATION_JSON_VALUE : TEXT_PLAIN_VALUE);
        } catch (IOException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        } finally {
            httpRequestBase.releaseConnection();
        }
    });
}

From source file:io.symcpe.hendrix.alerts.SuppressionMonitorBolt.java

@Override
public void execute(Tuple tuple) {
    try {//  www. j  av a2  s .  c  o  m
        client = Utils.buildClient(this.uiEndpoint, 3000, 3000);
        HttpPut put = new HttpPut(
                this.uiEndpoint + "/" + tuple.getShortByField(Constants.FIELD_ALERT_TEMPLATE_ID) + "/"
                        + tuple.getBooleanByField(Constants.SUPRESSION_STATE));
        client.execute(put);
        client.close();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) {
        collector.reportError(e);
    }
    collector.ack(tuple);
}

From source file:org.fcrepo.auth.integration.AbstractResourceIT.java

protected static HttpPut putDSMethod(final String pid, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPut put = new HttpPut(serverAddress + pid + "/" + ds + "/jcr:content");

    put.setEntity(new StringEntity(content));
    return put;//ww  w.  j av  a  2 s.c om
}

From source file:com.serena.rlc.provider.schedule.client.ScheduleWaiter.java

@Override
public void run() {
    logger.debug("ScheduleWaiter is sleeping for " + waitTime + " milliseconds, until " + endDate);
    try {/*w  ww  .  jav  a  2  s  . c  o m*/
        Thread.sleep(waitTime);
    } catch (InterruptedException ex) {
        logger.error("ScheduleWaiter was interrupted: " + ex.getLocalizedMessage());
    } catch (CancellationException ex) {
        logger.error("ScheduleWaiter thread has been cancelled: ", ex.getLocalizedMessage());
    }
    synchronized (executionId) {
        logger.debug("ScheduleWaiter has finished sleeping at " + new Date());

        try {
            String uri = callbackUrl + executionId + "/COMPLETED";
            logger.info("Start executing RLC PUT request to url=\"{}\"", uri);
            DefaultHttpClient rlcParams = new DefaultHttpClient();
            HttpPut put = new HttpPut(uri);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(callbackUsername,
                    callbackPassword);
            put.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
            //put.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //put.addHeader("Accept", "application/json");
            logger.info(credentials.toString());
            HttpResponse response = rlcParams.execute(put);
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.error("HTTP Status Code: " + response.getStatusLine().getStatusCode());
            }
        } catch (IOException ex) {
            logger.error(ex.getLocalizedMessage());
        }

        executionId.notify();
    }

}