Example #1
0
  @Test
  public void test408ShouldRetry() {
    HttpCommand command = createMock(HttpCommand.class);
    HttpResponse response = createMock(HttpResponse.class);
    @SuppressWarnings("unchecked")
    LoadingCache<Credentials, Access> cache = createMock(LoadingCache.class);
    BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);

    expect(response.getPayload())
        .andReturn(
            Payloads.newStringPayload(
                "The server has waited too long for the request to be sent by the client."))
        .times(3);
    expect(backoffHandler.shouldRetryRequest(command, response)).andReturn(true).once();
    expect(response.getStatusCode()).andReturn(408).once();

    replay(command);
    replay(response);
    replay(cache);
    replay(backoffHandler);

    RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);

    assertTrue(retry.shouldRetryRequest(command, response));

    verify(command);
    verify(response);
    verify(cache);
    verify(backoffHandler);
  }
Example #2
0
  @Test
  public void test401ShouldRetry() {
    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = createMock(HttpRequest.class);
    HttpResponse response = createMock(HttpResponse.class);
    @SuppressWarnings("unchecked")
    LoadingCache<Credentials, Access> cache = createMock(LoadingCache.class);
    BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);

    expect(command.getCurrentRequest()).andReturn(request);

    cache.invalidateAll();
    expectLastCall();

    expect(response.getPayload()).andReturn(Payloads.newStringPayload("")).anyTimes();
    expect(response.getStatusCode()).andReturn(401).atLeastOnce();

    replay(command);
    replay(response);
    replay(cache);
    replay(backoffHandler);

    RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);

    assertTrue(retry.shouldRetryRequest(command, response));

    verify(command);
    verify(response);
    verify(cache);
  }
  protected void assertCodeMakes(
      String method,
      URI uri,
      int statusCode,
      String message,
      String contentType,
      String content,
      Class<? extends Exception> expected) {

    HttpErrorHandler function =
        Guice.createInjector(new SaxParserModule()).getInstance(getHandlerClass());

    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = new HttpRequest(method, uri);
    HttpResponse response =
        new HttpResponse(statusCode, message, Payloads.newStringPayload(content));
    if (contentType != null) response.getPayload().getContentMetadata().setContentType(contentType);

    expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();
    command.setException(classEq(expected));

    replay(command);

    function.handleError(command, response);

    verify(command);
  }
Example #4
0
  @Test
  public void test401ShouldRetry4Times() {
    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = createMock(HttpRequest.class);
    HttpResponse response = createMock(HttpResponse.class);

    @SuppressWarnings("unchecked")
    LoadingCache<Credentials, Access> cache = createMock(LoadingCache.class);
    BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);

    expect(command.getCurrentRequest()).andReturn(request).anyTimes();
    expect(request.getHeaders()).andStubReturn(null);

    cache.invalidateAll();
    expectLastCall().anyTimes();

    expect(response.getPayload()).andReturn(Payloads.newStringPayload("")).anyTimes();
    expect(response.getStatusCode()).andReturn(401).anyTimes();

    replay(command, request, response, cache);

    RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);

    for (int i = 0; i < RetryOnRenew.NUM_RETRIES - 1; ++i) {
      assertTrue(retry.shouldRetryRequest(command, response), "Expected retry to succeed");
    }

    assertFalse(
        retry.shouldRetryRequest(command, response),
        "Expected retry to fail on attempt " + RetryOnRenew.NUM_RETRIES);

    verify(command, response, cache);
  }
 public void testWeCanReadAndWriteToDrive() throws IOException {
   drive2 =
       client.createDrive(
           new CreateDriveRequest.Builder().name(prefix + "2").size(1 * 1024 * 1024l).build());
   client.writeDrive(drive2.getUuid(), Payloads.newStringPayload("foo"));
   assertEquals(Strings2.toString(client.readDrive(drive2.getUuid(), 0, 3)), "foo");
 }
  public void testAbortMultipartUpload()
      throws SecurityException, NegativeArraySizeException, NoSuchMethodException {
    Invokable<?, ?> method =
        method(
            AWSS3AsyncClient.class,
            "abortMultipartUpload",
            String.class,
            String.class,
            String.class);
    GeneratedHttpRequest request =
        processor.createRequest(
            method,
            ImmutableList.<Object>of(
                "bucket", "foo", "asdsadasdas", 1, Payloads.newStringPayload("")));

    assertRequestLineEquals(
        request, "DELETE https://bucket." + url + "/foo?uploadId=asdsadasdas HTTP/1.1");
    assertNonPayloadHeadersEqual(request, "Host: bucket." + url + "\n");
    assertPayloadEquals(request, "", "application/unknown", false);

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

    checkFilters(request);
  }
  public void testUploadPart()
      throws SecurityException, NegativeArraySizeException, NoSuchMethodException {
    Invokable<?, ?> method =
        method(
            AWSS3AsyncClient.class,
            "uploadPart",
            String.class,
            String.class,
            int.class,
            String.class,
            Payload.class);
    GeneratedHttpRequest request =
        processor.createRequest(
            method,
            ImmutableList.<Object>of(
                "bucket", "foo", 1, "asdsadasdas", Payloads.newStringPayload("")));

    assertRequestLineEquals(
        request, "PUT https://bucket." + url + "/foo?partNumber=1&uploadId=asdsadasdas HTTP/1.1");
    assertNonPayloadHeadersEqual(request, "Host: bucket." + url + "\n");
    assertPayloadEquals(request, "", "application/unknown", false);

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

    checkFilters(request);
  }
Example #8
0
 // TODO: change EC2 apis to add this themselves with @FormParams
 private Payload addVersionIfNecessary(Payload payload, String form) {
   if (form.indexOf(VERSION) == -1) {
     form += "&Version=" + apiVersion;
     payload = Payloads.newStringPayload(form);
     payload.getContentMetadata().setContentType(APPLICATION_FORM_URLENCODED);
     payload.getContentMetadata().setContentLength((long) form.length());
   }
   return payload;
 }
 @Test(expectedExceptions = IllegalArgumentException.class)
 public void testNullContentLengthIllegal() {
   AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null);
   Payload payload = Payloads.newStringPayload("");
   payload.getContentMetadata().setContentLength(null);
   object.setPayload(payload);
   HttpRequest request = new HttpRequest("GET", URI.create("http://localhost"));
   binder.bindToRequest(request, object);
 }
 public String sign(String toSign) {
   try {
     byte[] encrypted =
         toByteArray(new RSAEncryptingPayload(Payloads.newStringPayload(toSign), supplyKey.get()));
     return base64().encode(encrypted);
   } catch (IOException e) {
     throw new HttpException("error signing request", e);
   }
 }
 public void testPutAndGet() throws IOException {
   temp = File.createTempFile("foo", "bar");
   temp.deleteOnExit();
   SshClient client = setupClient();
   client.put(temp.getAbsolutePath(), Payloads.newStringPayload("rabbit"));
   Payload input = setupClient().get(temp.getAbsolutePath());
   String contents = Strings2.toStringAndClose(input.getInput());
   assertEquals(contents, "rabbit");
 }
 public void testGood() {
   AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null);
   Payload payload = Payloads.newStringPayload("");
   object.setPayload(payload);
   object.getUserMetadata().getListableMetadata().put("apple", "bear");
   object.getUserMetadata().getListableMetadata().put("sushi", "king");
   HttpRequest request = new HttpRequest("GET", URI.create("http://localhost"));
   request = binder.bindToRequest(request, object);
   assertEquals(request.getFirstHeaderOrNull("x-emc-listable-meta"), "apple=bear,sushi=king");
 }
 public void testRegex() {
   assertEquals(
       handler.apply(
           new HttpResponse(
               200,
               "ok",
               Payloads.newStringPayload(
                   "{\n\"opscode-validator\": \"https://api.opscode.com/...\", \"pimp-validator\": \"https://api.opscode.com/...\"}"))),
       ImmutableSet.of("opscode-validator", "pimp-validator"));
 }
  public void testNoSchedule() throws UnknownHostException {

    UnwrapOnlyJsonValue<BackupSchedule> parser =
        i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<BackupSchedule>>() {}));
    BackupSchedule response =
        parser.apply(
            new HttpResponse(
                200,
                "ok",
                Payloads.newStringPayload("{\"backupSchedule\":{\"enabled\" : false}}")));
    assertEquals(new BackupSchedule(), response);
  }
  private void doCreateMarkerFile(Slice newDetails, String pass) throws IOException {
    String ip = getIp(newDetails);
    IPSocket socket = new IPSocket(ip, 22);
    socketTester.apply(socket);

    SshClient client = sshFactory.create(socket, "root", pass);
    try {
      client.connect();
      client.put("/etc/jclouds.txt", Payloads.newStringPayload("slicehost"));
    } finally {
      if (client != null) client.disconnect();
    }
  }
 @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();
 }
 @Inject
 public SignedHeaderAuth(
     SignatureWire signatureWire,
     @org.jclouds.location.Provider Supplier<Credentials> creds,
     Supplier<PrivateKey> supplyKey,
     @TimeStamp Provider<String> timeStampProvider,
     HttpUtils utils) {
   this.signatureWire = signatureWire;
   this.creds = creds;
   this.supplyKey = supplyKey;
   this.timeStampProvider = timeStampProvider;
   this.emptyStringHash = hashBody(Payloads.newStringPayload(""));
   this.utils = utils;
 }
  @Test(enabled = false, dependsOnMethods = "testCreateAndAttachVolume")
  void testBundleInstance() {
    SshClient ssh =
        sshFactory.create(
            new IPSocket(instance.getIpAddress(), 22),
            new Credentials("ubuntu", keyPair.getKeyMaterial()));
    try {
      ssh.connect();
    } catch (SshException e) { // try twice in case there is a network timeout
      try {
        Thread.sleep(10 * 1000);
      } catch (InterruptedException e1) {
      }
      ssh.connect();
    }
    try {
      System.out.printf(
          "%d: %s writing ebs script%n", System.currentTimeMillis(), instance.getId());
      String script = "/tmp/mkebsboot-init.sh";
      ssh.put(script, Payloads.newStringPayload(mkEbsBoot));

      System.out.printf(
          "%d: %s launching ebs script%n", System.currentTimeMillis(), instance.getId());
      ssh.exec("chmod 755 " + script);
      ssh.exec(script + " init");
      ExecResponse output = ssh.exec("sudo " + script + " start");
      System.out.println(output);
      output = ssh.exec(script + " status");

      assert !output.getOutput().trim().equals("") : output;

      RetryablePredicate<String> scriptTester =
          new RetryablePredicate<String>(
              new ScriptTester(ssh, SCRIPT_END), 600, 10, TimeUnit.SECONDS);
      scriptTester.apply(script);
    } finally {
      if (ssh != null) ssh.disconnect();
    }
  }
Example #19
0
 public MockFilePayload(String content) {
   super(createMockFile(content));
   this.realPayload = Payloads.newStringPayload(content);
 }
Example #20
0
 @Override
 public void put(String path, String contents) {
   put(path, Payloads.newStringPayload(checkNotNull(contents, "contents")));
 }