List of usage examples for org.apache.http.client.methods HttpPut METHOD_NAME
String METHOD_NAME
To view the source code for org.apache.http.client.methods HttpPut METHOD_NAME.
Click Source Link
From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java
/** Builds the default request handlers **/ private PathTrie<RequestHandler> defaultHandlers(final Map<String, Bucket> buckets, final Bucket ec2Bucket, final Bucket ecsBucket) { final PathTrie<RequestHandler> handlers = new PathTrie<>(RestUtils.REST_DECODER); // HEAD Object ///*from ww w . j a v a 2 s .c om*/ // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html objectsPaths(authPath(HttpHead.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) { if (object.getKey().equals(objectName)) { return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } } return newObjectNotFoundError(request.getId(), objectName); })); // PUT Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html objectsPaths(authPath(HttpPut.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String destBucketName = request.getParam("bucket"); final Bucket destBucket = buckets.get(destBucketName); if (destBucket == null) { return newBucketNotFoundError(request.getId(), destBucketName); } final String destObjectName = objectName(request.getParameters()); // This is a chunked upload request. We should have the header "Content-Encoding : aws-chunked,gzip" // to detect it but it seems that the AWS SDK does not follow the S3 guidelines here. // // See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html // String headerDecodedContentLength = request.getHeader("X-amz-decoded-content-length"); if (headerDecodedContentLength != null) { int contentLength = Integer.valueOf(headerDecodedContentLength); // Chunked requests have a payload like this: // // 105;chunk-signature=01d0de6be013115a7f4794db8c4b9414e6ec71262cc33ae562a71f2eaed1efe8 // ... bytes of data .... // 0;chunk-signature=f890420b1974c5469aaf2112e9e6f2e0334929fd45909e03c0eff7a84124f6a4 // try (BufferedInputStream inputStream = new BufferedInputStream( new ByteArrayInputStream(request.getBody()))) { int b; // Moves to the end of the first signature line while ((b = inputStream.read()) != -1) { if (b == '\n') { break; } } final byte[] bytes = new byte[contentLength]; inputStream.read(bytes, 0, contentLength); destBucket.objects.put(destObjectName, bytes); return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } } return newInternalError(request.getId(), "Something is wrong with this PUT request"); })); // DELETE Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html objectsPaths(authPath(HttpDelete.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); bucket.objects.remove(objectName); return new Response(RestStatus.NO_CONTENT.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); })); // GET Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html objectsPaths(authPath(HttpGet.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); if (bucket.objects.containsKey(objectName)) { return new Response(RestStatus.OK.getStatus(), contentType("application/octet-stream"), bucket.objects.get(objectName)); } return newObjectNotFoundError(request.getId(), objectName); })); // HEAD Bucket // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html handlers.insert(authPath(HttpHead.METHOD_NAME, "/{bucket}"), (request) -> { String bucket = request.getParam("bucket"); if (Strings.hasText(bucket) && buckets.containsKey(bucket)) { return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } else { return newBucketNotFoundError(request.getId(), bucket); } }); // GET Bucket (List Objects) Version 1 // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html handlers.insert(authPath(HttpGet.METHOD_NAME, "/{bucket}/"), (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } String prefix = request.getParam("prefix"); if (prefix == null) { prefix = request.getHeader("Prefix"); } return newListBucketResultResponse(request.getId(), bucket, prefix); }); // Delete Multiple Objects // // https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html handlers.insert(nonAuthPath(HttpPost.METHOD_NAME, "/"), (request) -> { final List<String> deletes = new ArrayList<>(); final List<String> errors = new ArrayList<>(); if (request.getParam("delete") != null) { // The request body is something like: // <Delete><Object><Key>...</Key></Object><Object><Key>...</Key></Object></Delete> String requestBody = Streams .copyToString(new InputStreamReader(new ByteArrayInputStream(request.getBody()), UTF_8)); if (requestBody.startsWith("<Delete>")) { final String startMarker = "<Key>"; final String endMarker = "</Key>"; int offset = 0; while (offset != -1) { offset = requestBody.indexOf(startMarker, offset); if (offset > 0) { int closingOffset = requestBody.indexOf(endMarker, offset); if (closingOffset != -1) { offset = offset + startMarker.length(); final String objectName = requestBody.substring(offset, closingOffset); boolean found = false; for (Bucket bucket : buckets.values()) { if (bucket.objects.containsKey(objectName)) { final Response authResponse = authenticateBucket(request, bucket); if (authResponse != null) { return authResponse; } bucket.objects.remove(objectName); found = true; } } if (found) { deletes.add(objectName); } else { errors.add(objectName); } } } } return newDeleteResultResponse(request.getId(), deletes, errors); } } return newInternalError(request.getId(), "Something is wrong with this POST multiple deletes request"); }); // non-authorized requests TriFunction<String, String, String, Response> credentialResponseFunction = (profileName, key, token) -> { final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1)); final String response = "{" + "\"AccessKeyId\": \"" + key + "\"," + "\"Expiration\": \"" + DateUtils.formatISO8601Date(expiration) + "\"," + "\"RoleArn\": \"" + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"SecretAccessKey\": \"" + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"Token\": \"" + token + "\"" + "}"; final Map<String, String> headers = new HashMap<>(contentType("application/json")); return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8)); }; // GET // // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/"), (request) -> { final String response = EC2_PROFILE; final Map<String, String> headers = new HashMap<>(contentType("text/plain")); return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8)); }); // GET // // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html handlers.insert( nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/{profileName}"), (request) -> { final String profileName = request.getParam("profileName"); if (EC2_PROFILE.equals(profileName) == false) { return new Response(RestStatus.NOT_FOUND.getStatus(), new HashMap<>(), "unknown profile".getBytes(UTF_8)); } return credentialResponseFunction.apply(profileName, ec2Bucket.key, ec2Bucket.token); }); // GET // // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/ecs_credentials_endpoint"), (request) -> credentialResponseFunction.apply("CPV_ECS", ecsBucket.key, ecsBucket.token)); return handlers; }
From source file:org.jboss.as.test.integration.security.perimeter.WebConsoleSecurityTestCase.java
@Test public void testPut() throws Exception { getConnection().setRequestMethod(HttpPut.METHOD_NAME); getConnection().connect();//from ww w .j a va2 s. c om assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getConnection().getResponseCode()); }
From source file:org.elasticsearch.client.RequestConverters.java
static Request putMapping(PutMappingRequest putMappingRequest) throws IOException { // The concreteIndex is an internal concept, not applicable to requests made over the REST API. if (putMappingRequest.getConcreteIndex() != null) { throw new IllegalArgumentException( "concreteIndex cannot be set on PutMapping requests made over the REST API"); }// w w w . j ava 2s.c o m Request request = new Request(HttpPut.METHOD_NAME, endpoint(putMappingRequest.indices(), "_mapping", putMappingRequest.type())); Params parameters = new Params(request); parameters.withTimeout(putMappingRequest.timeout()); parameters.withMasterTimeout(putMappingRequest.masterNodeTimeout()); request.setEntity(createEntity(putMappingRequest, REQUEST_BODY_CONTENT_TYPE)); return request; }
From source file:com.clickntap.vimeo.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpRequestBase request = null;// w w w . j a va 2 s. co m String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { out.put(header.getName(), header.getValue()); } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; }
From source file:org.elasticsearch.client.Request.java
static Request index(IndexRequest indexRequest) { String method = Strings.hasLength(indexRequest.id()) ? HttpPut.METHOD_NAME : HttpPost.METHOD_NAME; boolean isCreate = (indexRequest.opType() == DocWriteRequest.OpType.CREATE); String endpoint = endpoint(indexRequest.index(), indexRequest.type(), indexRequest.id(), isCreate ? "_create" : null); Params parameters = Params.builder(); parameters.withRouting(indexRequest.routing()); parameters.withParent(indexRequest.parent()); parameters.withTimeout(indexRequest.timeout()); parameters.withVersion(indexRequest.version()); parameters.withVersionType(indexRequest.versionType()); parameters.withPipeline(indexRequest.getPipeline()); parameters.withRefreshPolicy(indexRequest.getRefreshPolicy()); parameters.withWaitForActiveShards(indexRequest.waitForActiveShards()); BytesRef source = indexRequest.source().toBytesRef(); ContentType contentType = ContentType.create(indexRequest.getContentType().mediaType()); HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, contentType); return new Request(method, endpoint, parameters.getParams(), entity); }
From source file:com.uploader.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { // try(CloseableHttpClient client = HttpClientBuilder.create().build()) { CloseableHttpClient client = HttpClientBuilder.create().build(); // CloseableHttpClient client = HttpClients.createDefault(); System.out.println("Building HTTP Client"); // try {// w ww . j a va2 s . com // client = // } catch(Exception e) { // System.out.println("Err in CloseableHttpClient"); // } // System.out.println(client); HttpRequestBase request = null; String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } System.out.println(url); if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else { if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { try { out.put(header.getName(), header.getValue()); } catch (Exception e) { System.out.println("Err in out.put"); } } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; // } catch(IOException e) { // System.out.println("Error Building HTTP Client"); // } }
From source file:org.eclipse.aether.transport.http.HttpTransporter.java
private void prepare(HttpUriRequest request, SharingHttpContext context) { boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod()); if (state.getWebDav() == null && (put || isPayloadPresent(request))) { try {/*from www .j av a 2 s. c om*/ HttpOptions req = commonHeaders(new HttpOptions(request.getURI())); HttpResponse response = client.execute(server, req, context); state.setWebDav(isWebDav(response)); EntityUtils.consumeQuietly(response.getEntity()); } catch (IOException e) { LOGGER.debug("Failed to prepare HTTP context", e); } } if (put && Boolean.TRUE.equals(state.getWebDav())) { mkdirs(request.getURI(), context); } }
From source file:com.microsoft.live.unittest.UploadTest.java
@Override protected String getMethod() { return HttpPut.METHOD_NAME; }
From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java
/** * Returns the request that points to the backend service defined by the provided * <code>urlToService</code> URL. The headers of the origin request are copied to * the backend request, except of "host" and "content-length". * //from w w w . j av a2 s . c o m * @param request * original request to the Web application * @param urlToService * URL to the targeted backend service * @return initialized backend service request * @throws IOException */ private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException { String method = request.getMethod(); LOGGER.debug("HTTP method: " + method); HttpRequestBase backendRequest = null; if (HttpPost.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPost post = new HttpPost(urlToService); post.setEntity(entity); backendRequest = post; } else if (HttpGet.METHOD_NAME.equals(method)) { HttpGet get = new HttpGet(urlToService); backendRequest = get; } else if (HttpPut.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPut put = new HttpPut(urlToService); put.setEntity(entity); backendRequest = put; } else if (HttpDelete.METHOD_NAME.equals(method)) { HttpDelete delete = new HttpDelete(urlToService); backendRequest = delete; } // copy headers from Web application request to backend request, while // filtering the blocked headers LOGGER.debug("backend request headers:"); Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS)); Enumeration<String> setCookieHeaders = request.getHeaders("Cookie"); while (setCookieHeaders.hasMoreElements()) { String cookieHeader = setCookieHeaders.nextElement(); if (blockedHeaders.contains(cookieHeader.toLowerCase())) { String replacedCookie = removeJSessionID(cookieHeader); backendRequest.addHeader("Cookie", replacedCookie); } LOGGER.debug("Cookie header => " + cookieHeader); } for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement().toString(); if (!blockedHeaders.contains(headerName.toLowerCase())) { backendRequest.addHeader(headerName, request.getHeader(headerName)); LOGGER.debug(" => " + headerName + ": " + request.getHeader(headerName)); } else { LOGGER.debug(" => " + headerName + ": blocked request header"); } } return backendRequest; }