Пример #1
0
  @Test
  public void testGetImagesByName() throws NoSuchMethodException, IOException {
    Invokable<?, ?> method = method(GridImageApi.class, "getImagesByName", String[].class);
    GeneratedHttpRequest httpRequest =
        processor.createRequest(method, ImmutableList.<Object>of("name1", "name2"));

    assertRequestLineEquals(
        httpRequest,
        "GET https://api.gogrid.com/api/grid/image/get?v=1.5&" + "name=name1&name=name2 HTTP/1.1");
    assertNonPayloadHeadersEqual(httpRequest, "");
    assertPayloadEquals(httpRequest, null, null, false);

    assertResponseParserClassEquals(method, httpRequest, ParseImageListFromJsonResponse.class);
    assertSaxResponseParserClassEquals(method, null);
    assertFallbackClassEquals(method, null);

    checkFilters(httpRequest);
    httpRequest =
        (GeneratedHttpRequest)
            Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);

    assertRequestLineEquals(
        httpRequest,
        "GET https://api.gogrid.com/api/grid/image/get?v=1.5&"
            + "name=name1&name=name2&"
            + "sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity "
            + "HTTP/1.1");
    assertNonPayloadHeadersEqual(httpRequest, "");
    assertPayloadEquals(httpRequest, null, null, false);
  }
Пример #2
0
  public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion()
      throws SecurityException, NoSuchMethodException, IOException {
    Invokable<?, ?> method =
        method(
            InstanceApi.class,
            "setInstanceInitiatedShutdownBehaviorForInstanceInRegion",
            String.class,
            String.class,
            InstanceInitiatedShutdownBehavior.class);
    GeneratedHttpRequest request =
        processor.createRequest(
            method,
            Lists.<Object>newArrayList(null, "1", InstanceInitiatedShutdownBehavior.TERMINATE));

    request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);

    assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
    assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
    assertPayloadEquals(
        request,
        setInstanceInitiatedShutdownBehavior.getPayload().getRawContent().toString(),
        "application/x-www-form-urlencoded",
        false);

    assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
    assertSaxResponseParserClassEquals(method, null);
    assertFallbackClassEquals(method, null);

    checkFilters(request);
  }
  public void testCreateSecurityGroup()
      throws SecurityException, NoSuchMethodException, IOException {
    Invokable<?, ?> method =
        method(
            AWSSecurityGroupApi.class,
            "createSecurityGroupInRegion",
            String.class,
            String.class,
            String.class);
    GeneratedHttpRequest request =
        processor.createRequest(method, Lists.<Object>newArrayList(null, "name", "description"));

    request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);

    assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
    assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
    assertPayloadEquals(
        request,
        "Action=CreateSecurityGroup&GroupName=name&GroupDescription=description&Version=2014-02-01",
        "application/x-www-form-urlencoded",
        false);

    assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
    assertSaxResponseParserClassEquals(method, null);
    assertFallbackClassEquals(method, null);

    checkFilters(request);
  }
Пример #4
0
  public void testSetBlockDeviceMappingForInstanceInRegion()
      throws SecurityException, NoSuchMethodException, IOException {
    Invokable<?, ?> method =
        method(
            InstanceApi.class,
            "setBlockDeviceMappingForInstanceInRegion",
            String.class,
            String.class,
            Map.class);

    Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();
    mapping.put("/dev/sda1", new BlockDevice("vol-test1", true));
    GeneratedHttpRequest request =
        processor.createRequest(method, Lists.<Object>newArrayList(null, "1", mapping));

    request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);

    assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
    assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
    assertPayloadEquals(
        request,
        filter.filter(setBlockDeviceMapping).getPayload().getRawContent().toString(),
        "application/x-www-form-urlencoded",
        false);

    checkFilters(request);
  }
 public ContainerProperties apply(HttpResponse from) {
   MutableContainerPropertiesWithMetadata to = new MutableContainerPropertiesWithMetadataImpl();
   to.setName(request.getInvocation().getArgs().get(0).toString());
   addUserMetadataTo(from, to);
   parseLastModifiedOrThrowException(from, to);
   addETagTo(from, to);
   to.setUrl(request.getEndpoint());
   return to;
 }
Пример #6
0
  public void testVersions() throws SecurityException, NoSuchMethodException, IOException {
    Invokable<?, ?> method = method(VCloudVersionsApi.class, "getSupportedVersions");
    GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());

    assertEquals(request.getRequestLine(), "GET http://localhost:8080/versions HTTP/1.1");
    assertNonPayloadHeadersEqual(request, "");
    assertPayloadEquals(request, null, null, false);

    assertResponseParserClassEquals(method, request, ParseSax.class);
    assertSaxResponseParserClassEquals(method, SupportedVersionsHandler.class);
    assertFallbackClassEquals(method, null);

    checkFilters(request);
  }
 @SuppressWarnings("unchecked")
 @Override
 public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
   GeneratedHttpRequest<?> r = GeneratedHttpRequest.class.cast(request);
   String payload = r.getJavaMethod().getAnnotation(Payload.class).value();
   if (postParams.size() > 0) {
     UriBuilder builder = uriBuilders.get();
     builder.uri(URI.create("http://test/"));
     builder.path(payload);
     URI fake = builder.buildFromMap(postParams);
     payload = fake.getPath().substring(1);
   }
   return (R) request.toBuilder().payload(Payloads.newStringPayload(payload)).build();
 }
Пример #8
0
  public void testBindWithQueryParameters() throws SecurityException, NoSuchMethodException {
    TestDto dto = new TestDto();
    Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class);
    GeneratedHttpRequest request =
        GeneratedHttpRequest.builder()
            .declaring(TestEndpointLink.class)
            .javaMethod(withEndpointLink)
            .args(ImmutableList.<Object>of(dto))
            .method(HttpMethod.GET)
            .endpoint(URI.create("http://localhost?param=value"))
            .build();

    BindToPath binder = new BindToPath();
    GeneratedHttpRequest newRequest = binder.bindToRequest(request, dto);
    assertEquals(newRequest.getRequestLine(), "GET http://linkuri?param=value HTTP/1.1");
  }
Пример #9
0
 public static String getNameFor(GeneratedHttpRequest request) {
   checkNotNull(request, "request");
   List<Object> args = request.getInvocation().getArgs();
   // assume first params are container and key
   if (args.size() >= 2 && args.get(0) instanceof String && args.get(1) instanceof String) {
     return args.get(1).toString();
   } else if (args.size() >= 1 && args.get(0) instanceof String) {
     Matcher matcher = keyFromContainer.matcher(args.get(0).toString());
     if (matcher.find()) return matcher.group(1);
   }
   String objectKey = request.getEndpoint().getPath();
   if (objectKey.startsWith("/")) {
     // Trim initial slash from object key name.
     objectKey = objectKey.substring(1);
   }
   return objectKey;
 }
 @Override
 public Iterator<ListPage<T>> apply(ListPage<T> input) {
   if (input.nextPageToken() == null) {
     return ListPages.singletonOrEmptyIterator(input);
   }
   return new AdvancingIterator<T>(
       input, fetchNextPage(ListPages.<O>listOptions(request.getInvocation().getArgs())));
 }
  public void testInitiateMultipartUpload()
      throws SecurityException, NegativeArraySizeException, NoSuchMethodException {
    Invokable<?, ?> method =
        method(
            AWSS3AsyncClient.class,
            "initiateMultipartUpload",
            String.class,
            ObjectMetadata.class,
            PutObjectOptions[].class);
    GeneratedHttpRequest request =
        processor.createRequest(
            method,
            ImmutableList.<Object>of(
                "bucket",
                ObjectMetadataBuilder.create()
                    .key("foo")
                    .contentMD5(new byte[] {1, 2, 3, 4})
                    .build()));

    assertRequestLineEquals(request, "POST https://bucket." + url + "/foo?uploads HTTP/1.1");
    assertNonPayloadHeadersEqual(
        request,
        "Content-MD5: AQIDBA==\nContent-Type: binary/octet-stream\nHost: bucket." + url + "\n");
    assertPayloadEquals(request, null, null, false);

    // as this is a payload-related command, but with no payload, be careful
    // that we check
    // filtering and do not ignore if this fails later.
    request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);

    assertRequestLineEquals(request, "POST https://bucket." + url + "/foo?uploads HTTP/1.1");
    assertNonPayloadHeadersEqual(
        request,
        "Authorization: AWS identity:Sp1FX4svL9P2u2bFJwroaYpSANo=\nContent-MD5: AQIDBA==\n"
            + "Content-Type: binary/octet-stream\nDate: 2009-11-08T15:54:08.897Z\nHost: bucket."
            + url
            + "\n");
    assertPayloadEquals(request, null, null, false);

    assertResponseParserClassEquals(method, request, UploadIdFromHttpResponseViaRegex.class);
    assertSaxResponseParserClassEquals(method, null);
    assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);

    checkFilters(request);
  }
 public static String findAvailabilityZoneInArgsOrNull(
     GeneratedHttpRequest gRequest, Set<String> zones) {
   for (Object arg : gRequest.getInvocation().getArgs()) {
     if (arg instanceof String) {
       String zone = (String) arg;
       if (zones.contains(zone)) return zone;
     }
   }
   return null;
 }
  public void testDefault() throws IOException {
    String expected =
        Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml"));

    GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
    expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
    expect(request.getArgs()).andReturn(ImmutableList.<Object>of()).atLeastOnce();
    request.setPayload(expected);
    replay(request);

    BindCloneVCloudExpressVAppParamsToXmlPayload binder =
        injector.getInstance(BindCloneVCloudExpressVAppParamsToXmlPayload.class);

    Map<String, String> map = Maps.newHashMap();
    map.put("newName", "my-vapp");
    map.put("vApp", "https://vcloud.safesecureweb.com/api/v0.8/vapp/4181");
    binder.bindToRequest(request, map);
    verify(request);
  }
Пример #14
0
 public static String findRegionInArgsOrNull(GeneratedHttpRequest gRequest) {
   for (Object arg : gRequest.getInvocation().getArgs()) {
     if (arg instanceof String) {
       String regionName = (String) arg;
       // TODO regions may not be amazon regions!
       // take from a configured value
       if (isRegion(regionName)) return regionName;
     }
   }
   return null;
 }
Пример #15
0
 GeneratedHttpRequest requestForEndpointAndArgs(String endpoint, List<Object> args) {
   try {
     Invocation invocation = Invocation.create(method(String.class, "toString"), args);
     return GeneratedHttpRequest.builder()
         .method("POST")
         .endpoint(URI.create(endpoint))
         .invocation(invocation)
         .build();
   } catch (SecurityException e) {
     throw Throwables.propagate(e);
   }
 }
Пример #16
0
 @SuppressWarnings("unchecked")
 protected Iterable<VMSpec> findSpecInArgsOrNull(GeneratedHttpRequest<?> gRequest) {
   for (Object arg : gRequest.getArgs()) {
     if (arg instanceof Iterable<?>) {
       Iterable<VMSpec> specs = (Iterable<VMSpec>) arg;
       checkArgument(
           Iterables.size(specs) > 0, "At least one VMSpec must be included in the argument list");
       return specs;
     }
   }
   throw new IllegalArgumentException("Iterbable<VMSpec> must be included in the argument list");
 }
  public void testAllOptions() throws IOException {

    String expected =
        Strings2.toStringAndClose(
            getClass().getResourceAsStream("/InstantiateVAppTemplateParams-options-test.xml"));
    Multimap<String, String> headers =
        Multimaps.synchronizedMultimap(HashMultimap.<String, String>create());
    GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
    expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
    expect(request.getArgs())
        .andReturn(
            ImmutableList.<Object>of(
                InstantiateVAppTemplateOptions.Builder.processorCount(2)
                    .memory(512)
                    .inGroup("group")
                    .withPassword("password")
                    .inRow("row")
                    .addNetworkConfig(new NetworkConfig(URI.create("http://network")))))
        .atLeastOnce();
    expect(request.getFirstHeaderOrNull("Content-Type"))
        .andReturn("application/unknown")
        .atLeastOnce();
    expect(request.getHeaders()).andReturn(headers).atLeastOnce();
    request.setPayload(expected);
    replay(request);

    BindInstantiateVAppTemplateParamsToXmlPayload binder =
        injector.getInstance(BindInstantiateVAppTemplateParamsToXmlPayload.class);

    Map<String, String> map = Maps.newHashMap();
    map.put("name", "name");
    map.put("template", "https://vcloud/vAppTemplate/3");
    binder.bindToRequest(request, map);
  }
Пример #18
0
  @Test
  public void testGetImageListWithOptions() throws NoSuchMethodException, IOException {
    Invokable<?, ?> method =
        method(GridImageApi.class, "getImageList", GetImageListOptions[].class);
    GeneratedHttpRequest httpRequest =
        processor.createRequest(
            method,
            ImmutableList.<Object>of(
                new GetImageListOptions()
                    .onlyPublic()
                    .setState(ServerImageState.AVAILABLE)
                    .setType(ServerImageType.WEB_APPLICATION_SERVER)));

    assertRequestLineEquals(
        httpRequest,
        "GET https://api.gogrid.com/api/grid/image/list?v=1.5&"
            + "isPublic=true&image.state=Available&"
            + "image.type=Web%20Server HTTP/1.1");
    assertNonPayloadHeadersEqual(httpRequest, "");
    assertPayloadEquals(httpRequest, null, null, false);

    assertResponseParserClassEquals(method, httpRequest, ParseImageListFromJsonResponse.class);
    assertSaxResponseParserClassEquals(method, null);
    assertFallbackClassEquals(method, null);

    checkFilters(httpRequest);
    httpRequest =
        (GeneratedHttpRequest)
            Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);

    assertRequestLineEquals(
        httpRequest,
        "GET https://api.gogrid.com/api/grid/image/list?"
            + "v=1.5&isPublic=true&image.state=Available&"
            + "image.type=Web%20Server&"
            + "sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity "
            + "HTTP/1.1");
    assertNonPayloadHeadersEqual(httpRequest, "");
    assertPayloadEquals(httpRequest, null, null, false);
  }
Пример #19
0
  @Override
  public PagedIterable<T> apply(ListPage<T> input) {
    if (input.nextMarker() == null) return PagedIterables.of(input);

    Optional<Object> project =
        tryFind(request.getCaller().get().getArgs(), instanceOf(String.class));

    Optional<Object> listOptions =
        tryFind(request.getInvocation().getArgs(), instanceOf(ListOptions.class));

    assert project.isPresent()
        : String.format(
            "programming error, method %s should have a string param for the " + "project",
            request.getCaller().get().getInvokable());

    return PagedIterables.advance(
        input,
        fetchNextPage(
            project.get().toString(),
            (String) input.nextMarker().orNull(),
            (ListOptions) listOptions.orNull()));
  }
  public void testWithDescriptionDeployOn() throws IOException {
    String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml"));

    CloneVAppOptions options =
        new CloneVAppOptions()
            .deploy()
            .powerOn()
            .withDescription("The description of the new vApp");
    GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
    expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
    expect(request.getArgs()).andReturn(ImmutableList.<Object>of(options)).atLeastOnce();
    request.setPayload(expected);
    replay(request);

    BindCloneVCloudExpressVAppParamsToXmlPayload binder =
        injector.getInstance(BindCloneVCloudExpressVAppParamsToXmlPayload.class);

    Map<String, String> map = Maps.newHashMap();
    map.put("newName", "new-linux-server");
    map.put("vApp", "https://vcloud.safesecureweb.com/api/v0.8/vapp/201");
    binder.bindToRequest(request, map);
    verify(request);
  }
Пример #21
0
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testInvalidInputType() throws SecurityException, NoSuchMethodException {
    Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class);
    GeneratedHttpRequest request =
        GeneratedHttpRequest.builder()
            .declaring(TestEndpointLink.class)
            .javaMethod(withEndpointLink)
            .args(ImmutableList.<Object>of(new TestDto()))
            .method(HttpMethod.GET)
            .endpoint(URI.create("http://localhost"))
            .build();

    BindToPath binder = new BindToPath();
    binder.bindToRequest(request, new Object());
  }
  @Test
  public void testResponsePathSchemeLocationOk() throws Exception {
    ParseURIFromListOrLocationHeaderIf20x function =
        new ParseURIFromListOrLocationHeaderIf20x(uriBuilderProvider);
    HttpResponse response = createMock(HttpResponse.class);
    GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class);
    Payload payload = createMock(Payload.class);

    function.setContext(request);
    expect(request.getEndpoint()).andReturn(URI.create("https://new/fd")).atLeastOnce();
    expect(response.getStatusCode()).andReturn(200).atLeastOnce();
    expect(response.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE)).andReturn("text/plain");
    expect(response.getFirstHeaderOrNull(HttpHeaders.LOCATION)).andReturn("path");
    expect(response.getPayload()).andReturn(payload).atLeastOnce();
    payload.release();

    replay(request);
    replay(payload);
    replay(response);
    assertEquals(function.apply(response), URI.create("https://new/path"));
    verify(request);
    verify(response);
    verify(payload);
  }
Пример #23
0
  @Test(expectedExceptions = BindException.class)
  public void testAnnotationNotPresent() throws SecurityException, NoSuchMethodException {
    TestDto dto = new TestDto();
    Method withoutEndpointLink =
        TestEndpointLink.class.getMethod("withoutEndpointLink", TestDto.class);
    GeneratedHttpRequest request =
        GeneratedHttpRequest.builder()
            .declaring(TestEndpointLink.class)
            .javaMethod(withoutEndpointLink)
            .args(ImmutableList.<Object>of(dto))
            .method(HttpMethod.GET)
            .endpoint(URI.create("http://localhost"))
            .build();

    BindToPath binder = new BindToPath();
    binder.bindToRequest(request, dto);
  }
 public Builder fromGeneratedHttpRequest(GeneratedHttpRequest in) {
   return super.fromHttpRequest(in).invocation(in.invocation).caller(in.getCaller().orNull());
 }
 private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {
   GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
   expect(request.getArgs()).andReturn(new Object[] {null}).atLeastOnce();
   replay(request);
   handler.setContext(request);
 }
 public void setContext(GeneratedHttpRequest<?> request) {
   this.endpoint = request == null ? null : request.getEndpoint();
 }
 @Override
 protected void checkFilters(GeneratedHttpRequest<TerremarkVCloudAsyncClient> httpMethod) {
   assertEquals(httpMethod.getFilters().size(), 1);
   assertEquals(httpMethod.getFilters().get(0).getClass(), SetVCloudTokenCookie.class);
 }
Пример #28
0
 private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {
   GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
   expect(request.getArgs()).andReturn(ImmutableList.<Object>of());
   replay(request);
   handler.setContext(request);
 }