org.jclouds.http.HttpRequest Java Examples

The following examples show how to use org.jclouds.http.HttpRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GenerateTempURL.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private void generateDeleteTempURL() throws IOException {
   System.out.format("Generate DELETE Temp URL%n");

   HttpRequest request = blobStoreContext.getSigner(REGION).signRemoveBlob(CONTAINER, FILENAME);

   System.out.format("  %s %s%n", request.getMethod(), request.getEndpoint());

   // DELETE the file using jclouds
   HttpResponse response = blobStoreContext.utils().http().invoke(request);
   int statusCode = response.getStatusCode();

   if (statusCode >= 200 && statusCode < 299) {
      System.out.format("  DELETE Success (%s)%n", statusCode);
   }
   else {
      throw new HttpResponseException(null, response);
   }
}
 
Example #2
Source File: JenkinsAuthenticationFilter.java    From jenkins-rest with Apache License 2.0 6 votes vote down vote up
@Override
public HttpRequest filter(final HttpRequest request) throws HttpException {
    if (creds.authType() == AuthenticationType.Anonymous) {
        return request;
    } else {
        final String authHeader = creds.authType() + " " + creds.authValue();
        final HttpRequest.Builder<? extends HttpRequest.Builder<?>> builder = request.toBuilder();
        builder.addHeader(HttpHeaders.AUTHORIZATION, authHeader);

        // whether to add crumb header or not
        final Pair<Crumb, Boolean> localCrumb = getCrumb();
        if (localCrumb.getKey().value() != null) {
            builder.addHeader(CRUMB_HEADER, localCrumb.getKey().value());
            Optional.ofNullable(localCrumb.getKey().sessionIdCookie())
                    .ifPresent(sessionId -> builder.addHeader(HttpHeaders.COOKIE, sessionId));
        } else {
            if (localCrumb.getValue() == false) {
                throw new RuntimeException("Unexpected exception being thrown: error=" + localCrumb.getKey().errors().get(0));
            }
        }

        return builder.build();
    }
}
 
Example #3
Source File: GenerateTempURL.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private void generateGetTempURL() throws IOException {
   System.out.format("Generate GET Temp URL%n");

   HttpRequest request = blobStoreContext.getSigner(REGION).signGetBlob(CONTAINER, FILENAME, TEN_MINUTES);

   System.out.format("  %s %s%n", request.getMethod(), request.getEndpoint());

   // GET the file using jclouds
   File file = File.createTempFile(FILENAME, ".tmp");
   Payload payload = blobStoreContext.utils().http().invoke(request).getPayload();

   try {
      Files.asByteSink(file).writeFrom(payload.openStream());

      System.out.format("  GET Success (%s)%n", file.getAbsolutePath());
   } finally {
      payload.release();
      file.delete();
   }
}
 
Example #4
Source File: JCloudsAppStorageService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public URI getSignedGetContentUri( String key )
{
    BlobRequestSigner signer = blobStoreContext.getSigner();

    if ( !requestSigningSupported( signer ) )
    {
        return null;
    }

    HttpRequest httpRequest;

    try
    {
        httpRequest = signer.signGetBlob( config.container, key, FIVE_MINUTES_IN_SECONDS );
    }
    catch ( UnsupportedOperationException uoe )
    {
        return null;
    }

    return httpRequest.getEndpoint();
}
 
Example #5
Source File: JCloudsFileResourceContentStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public URI getSignedGetContentUri( String key )
{
    BlobRequestSigner signer = blobStoreContext.getSigner();

    if ( !requestSigningSupported( signer ) )
    {
        return null;
    }

    HttpRequest httpRequest;

    try
    {
        httpRequest = signer.signGetBlob( config.container, key, FIVE_MINUTES_IN_SECONDS );
    }
    catch ( UnsupportedOperationException uoe )
    {
        return null;
    }

    return httpRequest.getEndpoint();
}
 
Example #6
Source File: GenerateTempURL.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
private void generatePutTempURL() throws IOException {
   System.out.format("Generate PUT Temp URL%n");

   // Create the Payload
   String data = "This object will be public for 10 minutes.";
   ByteSource source = ByteSource.wrap(data.getBytes());
   Payload payload = Payloads.newByteSourcePayload(source);

   // Create the Blob
   Blob blob = blobStore.blobBuilder(FILENAME).payload(payload).contentType("text/plain").build();
   HttpRequest request = blobStoreContext.getSigner(REGION).signPutBlob(CONTAINER, blob, TEN_MINUTES);

   System.out.format("  %s %s%n", request.getMethod(), request.getEndpoint());

   // PUT the file using jclouds
   HttpResponse response = blobStoreContext.utils().http().invoke(request);
   int statusCode = response.getStatusCode();

   if (statusCode >= 200 && statusCode < 299) {
      System.out.format("  PUT Success (%s)%n", statusCode);
   }
   else {
      throw new HttpResponseException(null, response);
   }
}
 
Example #7
Source File: AWSEC2SecurityGroupHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public HandlerForGeneratedRequestWithResult<SecurityGroup> setContext(HttpRequest request) {
   region = AWSUtils.findRegionInArgsOrNull(GeneratedHttpRequest.class.cast(request));
   if (region == null)
      region = defaultRegion.get();
   builder = builder();
   return super.setContext(request);
}
 
Example #8
Source File: BlobStoreFileSystemHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public URI getAssetDirectLink(String id, String root, String filePath) throws IOException {
    ContainerAndName can = getContainerAndName(id, root, filePath);
    HttpRequest hr = context.getSigner().signGetBlob(can.container, can.name, SIGNED_URL_VALIDITY_SECONDS);
    if (hr == null) {
        throw new IOException("No object found to creat signed url " + id);
    }

    return hr.getEndpoint();
}
 
Example #9
Source File: BaseAWSEC2ApiTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override protected void assertNonPayloadHeadersEqual(HttpRequest request, String toMatch) {
   Multimap<String, String> headersToCheck = LinkedHashMultimap.create();
   for (String key : request.getHeaders().keySet()) {
      if (key.equals("X-Amz-Date")) {
         assertEquals(request.getFirstHeaderOrNull(key), "20120416T155408Z");
      } else if (key.equals("Authorization")) {
         assertThat(request.getFirstHeaderOrNull(AUTHORIZATION)).startsWith(
               "AWS4-HMAC-SHA256 Credential=identity/20120416/"
                     + "us-east-1/ec2/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=");
      } else {
         headersToCheck.putAll(key, request.getHeaders().get(key));
      }
   }
   assertEquals(sortAndConcatHeadersIntoString(headersToCheck), toMatch);
}
 
Example #10
Source File: BindMapToForm.java    From jenkins-rest with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(final R request, final Object properties) {

    if (properties == null) {
        return (R) request.toBuilder().build();
    }

   checkArgument(properties instanceof Map, "binder is only valid for Map");
   Map<String, List<String>> props = (Map<String, List<String>>) properties;

   Builder<?> builder = request.toBuilder();
   for (Map.Entry<String, List<String>> prop : props.entrySet()) {
      if (prop.getKey() != null) {
         String potentialKey = prop.getKey().trim();
         if (potentialKey.length() > 0) {
             if (prop.getValue() == null) {
                 prop.setValue(Lists.newArrayList(""));
             }

             builder.addFormParam(potentialKey, prop.getValue().toArray(new String[prop.getValue().size()]));
         }
      }
   }

   return (R) builder.build();
}
 
Example #11
Source File: BindLaunchSpecificationToFormParams.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
   checkArgument(input instanceof LaunchSpecification, "this binder is only valid for LaunchSpecifications!");
   LaunchSpecification launchSpec = LaunchSpecification.class.cast(input);
   return (R) request.toBuilder().replaceFormParams(Multimaps.forMap(apply(launchSpec))).build();
}
 
Example #12
Source File: JenkinsNoCrumbAuthenticationFilter.java    From jenkins-rest with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequest filter(final HttpRequest request) throws HttpException {
    if (creds.authType() == AuthenticationType.Anonymous) {
        return request;
    } else {
        final String authHeader = creds.authType() + " " + creds.authValue();
        return request.toBuilder().addHeader(HttpHeaders.AUTHORIZATION, authHeader).build();
    }
}
 
Example #13
Source File: BindHookSettingsToPayload.java    From bitbucket-rest with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(final R request, final Object hookSettings) {
    checkArgument(hookSettings instanceof HookSettings, "binder is only valid for HookSettings");
    final HookSettings passedHookSettings = HookSettings.class.cast(hookSettings);
    final String payload = passedHookSettings.settings().toString();
    return (R) request.toBuilder().payload(payload).build();
}
 
Example #14
Source File: BlobStoreFileSystemHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public URI getAssetDirectLink(String id, String root, String filePath) throws IOException {
    ContainerAndName can = getContainerAndName(id, root, filePath);
    HttpRequest hr = context.getSigner().signGetBlob(can.container, can.name, SIGNED_URL_VALIDITY_SECONDS);
    if (hr == null) {
        throw new IOException("No object found to creat signed url " + id);
    }

    return hr.getEndpoint();
}
 
Example #15
Source File: BitbucketAuthenticationFilter.java    From bitbucket-rest with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequest filter(final HttpRequest request) throws HttpException {
    if (creds.authType() == AuthenticationType.Anonymous) {
        return request;
    } else {
        final String authHeader = creds.authType() + " " + creds.authValue();
        return request.toBuilder().addHeader(HttpHeaders.AUTHORIZATION, authHeader).build();
    }
}
 
Example #16
Source File: ScrubNullFromPathFilter.java    From bitbucket-rest with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequest filter(final HttpRequest request) throws HttpException {
    String requestPath = request.getEndpoint().getRawPath()
            .replaceAll(SCRUB_NULL_PARAM, EMPTY_STRING)
            .replaceAll(DOUBLE_FORWARD_SLASH, FORWARD_SLASH);
    if (requestPath.charAt(requestPath.length() - 1) == FORWARD_SLASH_CHAR) {
        requestPath = requestPath.substring(0, requestPath.length() - 1);
    }
    return request.toBuilder().replacePath(requestPath).build();
}
 
Example #17
Source File: BindTagsToIndexedFormParamsTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public void test() {
   HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
   request = binder.bindToRequest(request, ImmutableMap.<String, String>builder().put("one", "alpha").put("two", "beta").build());
   assertEquals(request.getPayload().getRawContent(), "Tag.1.Key=one&Tag.1.Value=alpha&Tag.2.Key=two&Tag.2.Value=beta");
}
 
Example #18
Source File: ScrubNullFolderParam.java    From jenkins-rest with Apache License 2.0 4 votes vote down vote up
@Override
public HttpRequest filter(final HttpRequest request) throws HttpException {
    final String requestPath = request.getEndpoint().getRawPath().replaceAll(SCRUB_NULL_PARAM, EMPTY_STRING);
    return request.toBuilder().fromHttpRequest(request).replacePath(requestPath).build();
}
 
Example #19
Source File: BaseAWSEC2ApiTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
protected void checkFilters(HttpRequest request) {
   assertEquals(request.getFilters().size(), 1);
   assertTrue(request.getFilters().get(0) instanceof FormSignerV4);
}
 
Example #20
Source File: BindTagsToIndexedFormParamsTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = NullPointerException.class)
public void testNullIsBad() {
   HttpRequest request = HttpRequest.builder().method("GET").endpoint("http://momma").build();
   binder.bindToRequest(request, null);
}
 
Example #21
Source File: BindTagsToIndexedFormParamsTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeArray() {
   HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
   binder.bindToRequest(request, new File("foo"));
}
 
Example #22
Source File: BindTagsToIndexedFormParamsTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public void testEmpty() {
   HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
   request = binder.bindToRequest(request, ImmutableMap.<String, String>builder().put("empty", "").build());
   assertEquals(request.getPayload().getRawContent(), "Tag.1.Key=empty&Tag.1.Value=");
}
 
Example #23
Source File: BindTagFiltersToIndexedFormParams.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
    checkArgument(checkNotNull(input, "input") instanceof Map<?, ?>, "this binder is only valid for Map<?, Iterable<?>>");
    return AWSUtils.indexMapOfIterableToFormValuesWithPrefix(request, "Filter", "Name", "Value", input);
}
 
Example #24
Source File: AWSEC2DescribeSecurityGroupsResponseHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public HandlerForGeneratedRequestWithResult<Set<SecurityGroup>> setContext(HttpRequest request) {
   securityGroupHandler.setContext(request);
   return super.setContext(request);
}
 
Example #25
Source File: SpotInstancesHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public HandlerWithResult<Set<SpotInstanceRequest>> setContext(HttpRequest request) {
   spotRequestHandler.setContext(request);
   return super.setContext(request);
}
 
Example #26
Source File: DescribePlacementGroupsResponseHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public HandlerWithResult<Set<PlacementGroup>> setContext(HttpRequest request) {
   bundleTaskHandler.setContext(request);
   return super.setContext(request);
}
 
Example #27
Source File: DescribeSpotPriceHistoryResponseHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public HandlerWithResult<Set<Spot>> setContext(HttpRequest request) {
   spotHandler.setContext(request);
   return super.setContext(request);
}
 
Example #28
Source File: DescribeReservedInstancesOfferingResponseHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public HandlerWithResult<Set<ReservedInstancesOffering>> setContext(HttpRequest request) {
   reservedInstancesOffering.setContext(request);
   return super.setContext(request);
}
 
Example #29
Source File: BindSpotInstanceRequestIdsToIndexedFormParams.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
   return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, "SpotInstanceRequestId", input);
}
 
Example #30
Source File: BindTagsToIndexedFormParams.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
    checkArgument(checkNotNull(input, "input") instanceof Map, "This binder is only valid for Map<String,String>");
    return AWSUtils.indexMapToFormValuesWithPrefix(request, "Tag", "Key", "Value", input);
}