Пример #1
0
  public Ec2Context(Ec2Credentials credentials) {
    this.credentials = credentials;
    Properties properties = new Properties();
    long scriptTimeout = TimeUnit.MILLISECONDS.convert(50, TimeUnit.MINUTES);
    properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, scriptTimeout + "");
    properties.setProperty(TIMEOUT_PORT_OPEN, scriptTimeout + "");
    properties.setProperty(PROPERTY_CONNECTION_TIMEOUT, scriptTimeout + "");
    properties.setProperty(
        PROPERTY_EC2_AMI_QUERY, "owner-id=137112412989;state=available;image-type=machine");
    properties.setProperty(PROPERTY_EC2_CC_AMI_QUERY, "");
    properties.setProperty(
        Constants.PROPERTY_MAX_RETRIES, Settings.JCLOUDS_PROPERTY_MAX_RETRIES + "");
    properties.setProperty(
        Constants.PROPERTY_RETRY_DELAY_START, Settings.JCLOUDS_PROPERTY_RETRY_DELAY_START + "");

    Iterable<Module> modules =
        ImmutableSet.<Module>of(
            new SshjSshClientModule(),
            new SLF4JLoggingModule(),
            new EnterpriseConfigurationModule());

    ContextBuilder build =
        ContextBuilder.newBuilder("aws-ec2")
            .credentials(credentials.getAccessKey(), credentials.getSecretKey())
            .modules(modules)
            .overrides(properties);
    ComputeServiceContext context = build.buildView(ComputeServiceContext.class);
    this.computeService = (AWSEC2ComputeService) context.getComputeService();
    this.ec2api = computeService.getContext().unwrapApi(EC2Api.class);
    this.securityGroupApi = ec2api.getSecurityGroupApi().get();
    this.keypairApi = (AWSKeyPairApi) ec2api.getKeyPairApi().get();

    vmBatchSize = Settings.AWS_VM_BATCH_SIZE();
  }
Пример #2
0
 public CloudComputeService(
     String apiKey,
     String accessKey,
     String instanceType,
     String groupName,
     String imageId,
     String keyPair,
     String securityGroup,
     float maxBid) {
   mInstanceType = instanceType;
   mGroupName = groupName;
   mImageId = imageId;
   mkeyPair = keyPair;
   mSecurityGroup = securityGroup;
   mMaxBid = maxBid;
   mGroupTag = "group=" + mGroupName;
   Properties overrides = new Properties();
   overrides.put(ComputeServiceProperties.POLL_INITIAL_PERIOD, String.valueOf(60L * 1000L));
   overrides.put(ComputeServiceProperties.POLL_MAX_PERIOD, String.valueOf(600L * 1000L));
   overrides.put(Constants.PROPERTY_MAX_RETRIES, String.valueOf(60));
   mComputeServiceContext =
       ContextBuilder.newBuilder("aws-ec2")
           .credentials(apiKey, accessKey)
           .modules(ImmutableSet.of(new Log4JLoggingModule()))
           .overrides(overrides)
           .buildView(ComputeServiceContext.class);
   mComputeService = mComputeServiceContext.getComputeService();
 }
 @BeforeClass
 public void setUp() {
   context =
       ContextBuilder.newBuilder("virtualbox")
           .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()))
           .build(ComputeServiceContext.class);
 }
Пример #4
0
 @Provides
 @Singleton
 RestContext<UltraDNSWSApi, UltraDNSWSAsyncApi> provideContext(Supplier<Credentials> credentials) {
   return ContextBuilder.newBuilder(new UltraDNSWSProviderMetadata())
       .credentialsSupplier(credentials)
       .modules(ImmutableSet.<com.google.inject.Module>of(new SLF4JLoggingModule()))
       .build();
 }
  @Before
  public void setUp() {
    Properties prop = new Properties();
    prop.put(Constants.PROPERTY_ENDPOINT, TestConstants.ENDPOINT);

    ContextBuilder builder =
        ContextBuilder.newBuilder(TestConstants.PROVIDER)
            .credentials(TestConstants.API_KEY, TestConstants.SECRET_KEY)
            //              .modules(modules)
            .overrides(prop);

    CloudStackContext context = builder.buildView(CloudStackContext.class);

    RestContext<CloudStackClient, CloudStackAsyncClient> providerContext =
        context.getProviderSpecificContext();
    client = providerContext.getApi();
  }
 private BlobStore getBlobStore() {
   BlobStoreContext context =
       ContextBuilder.newBuilder("transient")
           .name("test-transient")
           .credentials("user", "pass")
           .build(BlobStoreContext.class);
   return context.getBlobStore();
 }
Пример #7
0
 public ListContainers(String username, String apiKey) {
   BlobStoreContext context =
       ContextBuilder.newBuilder(PROVIDER)
           .credentials(username, apiKey)
           .buildView(BlobStoreContext.class);
   blobStore = context.getBlobStore();
   swift = context.unwrap();
 }
Пример #8
0
 @Provides
 @Singleton
 UltraDNSWSApi provideApi(Supplier<Credentials> credentials) {
   return ContextBuilder.newBuilder(new UltraDNSWSProviderMetadata())
       .credentialsSupplier(credentials)
       .modules(ImmutableSet.<com.google.inject.Module>of(new SLF4JLoggingModule()))
       .buildApi(UltraDNSWSApi.class);
 }
Пример #9
0
  private void copyToS3(String fileName) {

    String bucketName = (String) properties.get(BUCKET_PROPNAME);
    String accessId = (String) properties.get(ACCESS_ID_PROPNAME);
    String secretKey = (String) properties.get(SECRET_KEY_PROPNAME);

    Properties overrides = new Properties();
    overrides.setProperty("s3" + ".identity", accessId);
    overrides.setProperty("s3" + ".credential", secretKey);

    final Iterable<? extends Module> MODULES =
        ImmutableSet.of(
            new JavaUrlHttpCommandExecutorServiceModule(),
            new Log4JLoggingModule(),
            new NettyPayloadModule());

    BlobStoreContext context =
        ContextBuilder.newBuilder("s3")
            .credentials(accessId, secretKey)
            .modules(MODULES)
            .overrides(overrides)
            .buildView(BlobStoreContext.class);

    // Create Container (the bucket in s3)
    try {
      AsyncBlobStore blobStore = context.getAsyncBlobStore(); // it can be changed to sync
      // BlobStore (returns false if it already exists)
      ListenableFuture<Boolean> container = blobStore.createContainerInLocation(null, bucketName);
      if (container.get()) {
        LOG.info("Created bucket " + bucketName);
      }
    } catch (Exception ex) {
      logger.error("Could not start binary service: {}", ex.getMessage());
      throw new RuntimeException(ex);
    }

    try {
      File file = new File(fileName);
      AsyncBlobStore blobStore = context.getAsyncBlobStore();
      BlobBuilder blobBuilder =
          blobStore
              .blobBuilder(file.getName())
              .payload(file)
              .calculateMD5()
              .contentType("text/plain")
              .contentLength(file.length());

      Blob blob = blobBuilder.build();

      ListenableFuture<String> futureETag =
          blobStore.putBlob(bucketName, blob, PutOptions.Builder.multipart());

      LOG.info("Uploaded file etag=" + futureETag.get());
    } catch (Exception e) {
      LOG.error("Error uploading to blob store", e);
    }
  }
  /** Checks if context parameters are managed in the correct way */
  public void testParameters() {
    // no base directory declared in properties
    try {
      Properties props = new Properties();
      context = ContextBuilder.newBuilder(PROVIDER).overrides(props).build(BlobStoreContext.class);
      fail("No error if base directory is not specified");
    } catch (CreationException e) {
    }

    // no base directory declared in properties
    try {
      Properties props = new Properties();
      props.setProperty(FilesystemConstants.PROPERTY_BASEDIR, null);
      context = ContextBuilder.newBuilder(PROVIDER).overrides(props).build(BlobStoreContext.class);
      fail("No error if base directory is null in the option");
    } catch (NullPointerException e) {
    }
  }
 /** Strategy to perform any pre setup, before {@link org.apache.camel.CamelContext} is created */
 @Override
 protected void doPreSetup() throws Exception {
   BlobStore blobStore =
       ContextBuilder.newBuilder("transient")
           .credentials("identity", "credential")
           .buildView(BlobStoreContext.class)
           .getBlobStore();
   blobStore.createContainerInLocation(null, TEST_CONTAINER);
   blobStore.clearContainer(TEST_CONTAINER);
 }
 @BeforeMethod
 protected void setUp() throws Exception {
   // create context for filesystem container
   Properties prop = new Properties();
   prop.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR);
   context = ContextBuilder.newBuilder(PROVIDER).overrides(prop).build(BlobStoreContext.class);
   // create a container in the default location
   blobStore = context.getBlobStore();
   new File(TestUtils.TARGET_BASE_DIR).mkdir();
   TestUtils.createResources();
 }
 @BeforeMethod
 public void start() throws IOException {
   server = new MockWebServer();
   server.play();
   ApiContext<ProfitBricksApi> ctx =
       ContextBuilder.newBuilder("profitbricks-rest")
           .credentials("username", "password")
           .endpoint(url(""))
           .modules(modules)
           .overrides(overrides())
           .build();
   api = ctx.getApi();
 }
Пример #14
0
  public JCloudsNeutron(String tenantName, String userName, String password) {
    Iterable<Module> modules = ImmutableSet.<Module>of(new SLF4JLoggingModule());

    String identity = tenantName + ":" + userName; // tenantName:userName

    neutronApi =
        ContextBuilder.newBuilder(provider)
            .credentials(identity, password)
            .endpoint(endpoint)
            .modules(modules)
            .buildApi(NeutronApi.class);
    regions = neutronApi.getConfiguredRegions();
  }
Пример #15
0
 public ComputeServiceContext getContext(Provider provider) {
   ComputeServiceContext context = contextForProvider.get(provider);
   Credentials credentials = provider.getCredentials();
   if (context == null && provider.areCredentialsSetup()) {
     provider.registerCredentialsChangedListener(this);
     context =
         ContextBuilder.newBuilder(provider.getId())
             .credentials(credentials.getKey(), credentials.getSecret())
             .modules(ImmutableSet.<Module>of(new JschSshClientModule()))
             .buildView(ComputeServiceContext.class);
   }
   return context;
 }
  public void testOverrideInitStatusProperties() {
    Properties overrides = new Properties();
    overrides.setProperty(ComputeServiceProperties.INIT_STATUS_INITIAL_PERIOD, "501");
    overrides.setProperty(ComputeServiceProperties.INIT_STATUS_MAX_PERIOD, "5001");

    InitStatusProperties props =
        ContextBuilder.newBuilder("stub")
            .overrides(overrides)
            .buildInjector()
            .getInstance(InitStatusProperties.class);

    assertEquals(props.initStatusInitialPeriod, 501);
    assertEquals(props.initStatusMaxPeriod, 5001);
  }
  @BeforeMethod(alwaysRun = true)
  @Override
  public void setUp() throws Exception {
    super.setUp();

    jcloudsLocation =
        (JcloudsLocation) managementContext.getLocationRegistry().resolve(LOCATION_SPEC);

    context =
        ContextBuilder.newBuilder(PROVIDER)
            .modules(Arrays.asList(new SshjSshClientModule(), new SLF4JLoggingModule()))
            .credentials(jcloudsLocation.getIdentity(), jcloudsLocation.getCredential())
            .build(ComputeServiceContext.class);
  }
  private void init(String[] args) {
    // The provider configures jclouds To use the Rackspace Cloud (US)
    // To use the Rackspace Cloud (UK) set the provider to "rackspace-cloudloadbalancers-uk"
    String provider = "rackspace-cloudloadbalancers-us";

    String username = args[0];
    String apiKey = args[1];

    clb =
        ContextBuilder.newBuilder(provider)
            .credentials(username, apiKey)
            .buildApi(CloudLoadBalancersApi.class);
    lbApi = clb.getLoadBalancerApiForZone(Constants.ZONE);
  }
  public UploadLargeObject(String username, String apiKey) {
    Properties overrides = new Properties();
    // This property controls the number of parts being uploaded in parallel, the default is 4
    overrides.setProperty("jclouds.mpu.parallel.degree", "5");
    // This property controls the size (in bytes) of parts being uploaded in parallel, the default
    // is 33554432 bytes = 32 MB
    overrides.setProperty("jclouds.mpu.parts.size", "67108864"); // 64 MB

    RegionScopedBlobStoreContext context =
        ContextBuilder.newBuilder(PROVIDER)
            .credentials(username, apiKey)
            .overrides(overrides)
            .buildView(RegionScopedBlobStoreContext.class);
    blobStore = context.blobStoreInRegion(REGION);
  }
  private void buildNeutronApi() {

    String iaasProviderNullMsg = "IaasProvider is null. Unable to build neutron API";
    assertNotNull(iaasProvider, iaasProviderNullMsg);

    String region = ComputeServiceBuilderUtil.extractRegion(iaasProvider);
    String regionNullOrEmptyErrorMsg =
        String.format(
            "Region is not set. Unable to build neutron API for the iaas provider %s",
            iaasProvider.getProvider());
    assertNotNullAndNotEmpty(region, regionNullOrEmptyErrorMsg);

    String endpoint = iaasProvider.getProperty(CloudControllerConstants.JCLOUDS_ENDPOINT);
    String endpointNullOrEmptyErrorMsg =
        String.format(
            "Endpoint is not set. Unable to build neutorn API for the iaas provider %s",
            iaasProvider.getProvider());
    assertNotNullAndNotEmpty(endpoint, endpointNullOrEmptyErrorMsg);

    Iterable<Module> modules = ImmutableSet.<Module>of(new SLF4JLoggingModule());

    try {
      this.neutronApi =
          ContextBuilder.newBuilder(provider)
              .credentials(iaasProvider.getIdentity(), iaasProvider.getCredential())
              .endpoint(endpoint)
              .modules(modules)
              .buildApi(NeutronApi.class);
    } catch (Exception e) {
      String msg =
          String.format(
              "Unable to build neutron API for [provider=%s, identity=%s, credential=%s, endpoint=%s]",
              provider, iaasProvider.getIdentity(), iaasProvider.getCredential(), endpoint);
      log.error(msg, e);
      throw new CloudControllerException(msg, e);
    }

    this.portApi = neutronApi.getPortApi(region);
    String portApiNullOrEmptyErrorMessage =
        String.format("Unable to get port Api from neutron Api for region ", region);
    assertNotNull(portApi, portApiNullOrEmptyErrorMessage);

    this.floatingIPApi = neutronApi.getFloatingIPApi(region).get();
    String floatingIPApiNullOrEmptyErrorMessage =
        String.format("Unable to get floatingIP Api from neutron Api for region ", region);
    assertNotNull(floatingIPApi, floatingIPApiNullOrEmptyErrorMessage);
  }
  public CreateServerWithKeyPair(String username, String apiKey) {
    Iterable<Module> modules = ImmutableSet.<Module>of(new SshjSshClientModule());

    // These properties control how often jclouds polls for a status update
    Properties overrides = new Properties();
    overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
    overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);

    ComputeServiceContext context =
        ContextBuilder.newBuilder(PROVIDER)
            .credentials(username, apiKey)
            .overrides(overrides)
            .modules(modules)
            .buildView(ComputeServiceContext.class);

    computeService = context.getComputeService();
    novaApi = context.unwrapApi(NovaApi.class);
  }
Пример #22
0
  public static Map<Integer, Integer> dockerPortMappingsFor(
      JcloudsLocation docker, String containerId) {
    ComputeServiceContext context = null;
    try {
      Properties properties = new Properties();
      properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, Boolean.toString(true));
      properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, Boolean.toString(true));
      context =
          ContextBuilder.newBuilder("docker")
              .endpoint(docker.getEndpoint())
              .credentials(docker.getIdentity(), docker.getCredential())
              .overrides(properties)
              .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()))
              .build(ComputeServiceContext.class);
      DockerApi api = context.unwrapApi(DockerApi.class);
      Container container = api.getContainerApi().inspectContainer(containerId);
      Map<Integer, Integer> portMappings = Maps.newLinkedHashMap();
      Map<String, List<Map<String, String>>> ports = container.networkSettings().ports();
      if (ports == null) ports = ImmutableMap.<String, List<Map<String, String>>>of();

      LOG.debug("Docker will forward these ports {}", ports);
      for (Map.Entry<String, List<Map<String, String>>> entrySet : ports.entrySet()) {
        String containerPort = Iterables.get(Splitter.on("/").split(entrySet.getKey()), 0);
        String hostPort =
            Iterables.getOnlyElement(
                Iterables.transform(
                    entrySet.getValue(),
                    new Function<Map<String, String>, String>() {
                      @Override
                      public String apply(Map<String, String> hostIpAndPort) {
                        return hostIpAndPort.get("HostPort");
                      }
                    }));
        portMappings.put(Integer.parseInt(containerPort), Integer.parseInt(hostPort));
      }
      return portMappings;
    } finally {
      if (context != null) {
        context.close();
      }
    }
  }
Пример #23
0
  /**
   * Temporary constructor to address https://issues.apache.org/jira/browse/JCLOUDS-615.
   *
   * <p>See https://issues.apache.org/jira/browse/BROOKLYN-6 . When
   * https://issues.apache.org/jira/browse/JCLOUDS-615 is fixed in the jclouds we use, we can remove
   * the useSoftlayerFix argument.
   *
   * <p>(Marked Beta as that argument will likely be removed.)
   *
   * @since 0.7.0
   */
  @Beta
  public static BlobStoreContext newBlobstoreContext(
      String provider, @Nullable String endpoint, String identity, String credential) {
    Properties overrides = new Properties();
    // * Java 7,8 bug workaround - sockets closed by GC break the internal bookkeeping
    //   of HttpUrlConnection, leading to invalid handling of the "HTTP/1.1 100 Continue"
    //   response. Coupled with a bug when using SSL sockets reads will block
    //   indefinitely even though a read timeout is explicitly set.
    // * Java 6 ignores the header anyways as it is included in its restricted headers black list.
    // * Also there's a bug in SL object store which still expects Content-Length bytes
    //   even when it responds with a 408 timeout response, leading to incorrectly
    //   interpreting the next request (triggered by above problem).
    overrides.setProperty(Constants.PROPERTY_STRIP_EXPECT_HEADER, "true");

    ContextBuilder contextBuilder =
        ContextBuilder.newBuilder(provider).credentials(identity, credential);
    contextBuilder.modules(MutableList.copyOf(JcloudsUtil.getCommonModules()));
    if (!org.apache.brooklyn.util.text.Strings.isBlank(endpoint)) {
      contextBuilder.endpoint(endpoint);
    }
    contextBuilder.overrides(overrides);
    BlobStoreContext context = contextBuilder.buildView(BlobStoreContext.class);
    return context;
  }
 private ChefContext createConnection(String identity, String key) throws IOException {
   return ContextBuilder.newBuilder(new TransientChefApiMetadata())
       .credentials(identity, key)
       .build();
 }
  @Override
  public ComputeService findComputeService(ConfigBag conf, boolean allowReuse) {
    String provider = checkNotNull(conf.get(CLOUD_PROVIDER), "provider must not be null");
    String identity =
        checkNotNull(conf.get(CloudLocationConfig.ACCESS_IDENTITY), "identity must not be null");
    String credential =
        checkNotNull(
            conf.get(CloudLocationConfig.ACCESS_CREDENTIAL), "credential must not be null");

    Properties properties = new Properties();
    properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, Boolean.toString(true));
    properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, Boolean.toString(true));
    properties.setProperty(
        "jclouds.ssh.max-retries",
        conf.getStringKey("jclouds.ssh.max-retries") != null
            ? conf.getStringKey("jclouds.ssh.max-retries").toString()
            : "50");
    // Enable aws-ec2 lazy image fetching, if given a specific imageId; otherwise customize for
    // specific owners; or all as a last resort
    // See https://issues.apache.org/jira/browse/WHIRR-416
    if ("aws-ec2".equals(provider)) {
      // TODO convert AWS-only flags to config keys
      if (groovyTruth(conf.get(IMAGE_ID))) {
        properties.setProperty(PROPERTY_EC2_AMI_QUERY, "");
        properties.setProperty(PROPERTY_EC2_CC_AMI_QUERY, "");
      } else if (groovyTruth(conf.getStringKey("imageOwner"))) {
        properties.setProperty(
            PROPERTY_EC2_AMI_QUERY,
            "owner-id=" + conf.getStringKey("imageOwner") + ";state=available;image-type=machine");
      } else if (groovyTruth(conf.getStringKey("anyOwner"))) {
        // set `anyOwner: true` to override the default query (which is restricted to certain owners
        // as per below),
        // allowing the AMI query to bind to any machine
        // (note however, we sometimes pick defaults in JcloudsLocationFactory);
        // (and be careful, this can give a LOT of data back, taking several minutes,
        // and requiring extra memory allocated on the command-line)
        properties.setProperty(PROPERTY_EC2_AMI_QUERY, "state=available;image-type=machine");
        /*
         * by default the following filters are applied:
         * Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&
         * Filter.1.Value.2=063491364108&
         * Filter.1.Value.3=099720109477&
         * Filter.1.Value.4=411009282317&
         * Filter.2.Name=state&Filter.2.Value.1=available&
         * Filter.3.Name=image-type&Filter.3.Value.1=machine&
         */
      }

      // occasionally can get com.google.common.util.concurrent.UncheckedExecutionException:
      // java.lang.RuntimeException:
      //     security group eu-central-1/jclouds#brooklyn-bxza-alex-eu-central-shoul-u2jy-nginx-ielm
      // is not available after creating
      // the default timeout was 500ms so let's raise it in case that helps
      properties.setProperty(
          EC2Constants.PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT,
          "" + Duration.seconds(30).toMilliseconds());
    }

    // FIXME Deprecated mechanism, should have a ConfigKey for overrides
    Map<String, Object> extra =
        Maps.filterKeys(conf.getAllConfig(), Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
      LOG.warn("Jclouds using deprecated property overrides: " + Sanitizer.sanitize(extra));
    }
    properties.putAll(extra);

    String endpoint = conf.get(CloudLocationConfig.CLOUD_ENDPOINT);
    if (!groovyTruth(endpoint)) endpoint = getDeprecatedProperty(conf, Constants.PROPERTY_ENDPOINT);
    if (groovyTruth(endpoint)) properties.setProperty(Constants.PROPERTY_ENDPOINT, endpoint);

    Map<?, ?> cacheKey =
        MutableMap.builder()
            .putAll(properties)
            .put("provider", provider)
            .put("identity", identity)
            .put("credential", credential)
            .putIfNotNull("endpoint", endpoint)
            .build()
            .asUnmodifiable();

    if (allowReuse) {
      ComputeService result = cachedComputeServices.get(cacheKey);
      if (result != null) {
        LOG.trace(
            "jclouds ComputeService cache hit for compute service, for "
                + Sanitizer.sanitize(properties));
        return result;
      }
      LOG.debug(
          "jclouds ComputeService cache miss for compute service, creating, for "
              + Sanitizer.sanitize(properties));
    }

    Iterable<Module> modules = getCommonModules();

    // Synchronizing to avoid deadlock from sun.reflect.annotation.AnnotationType.
    // See https://github.com/brooklyncentral/brooklyn/issues/974
    ComputeServiceContext computeServiceContext;
    synchronized (createComputeServicesMutex) {
      computeServiceContext =
          ContextBuilder.newBuilder(provider)
              .modules(modules)
              .credentials(identity, credential)
              .overrides(properties)
              .build(ComputeServiceContext.class);
    }
    final ComputeService computeService = computeServiceContext.getComputeService();
    if (allowReuse) {
      synchronized (cachedComputeServices) {
        ComputeService result = cachedComputeServices.get(cacheKey);
        if (result != null) {
          LOG.debug(
              "jclouds ComputeService cache recovery for compute service, for "
                  + Sanitizer.sanitize(cacheKey));
          // keep the old one, discard the new one
          computeService.getContext().close();
          return result;
        }
        LOG.debug(
            "jclouds ComputeService created "
                + computeService
                + ", adding to cache, for "
                + Sanitizer.sanitize(properties));
        cachedComputeServices.put(cacheKey, computeService);
      }
    }
    return computeService;
  }
public class JcloudsBlobStoreProducerTest extends CamelTestSupport {

  private static final String TEST_CONTAINER = "testContainer";
  private static final String TEST_BLOB_IN_DIR = "/dir/testBlob";
  private static final String MESSAGE = "<test>This is a test</test>";

  BlobStoreContext blobStoreContext =
      ContextBuilder.newBuilder("transient")
          .credentials("identity", "credential")
          .build(BlobStoreContext.class);
  BlobStore blobStore = blobStoreContext.getBlobStore();

  @Test
  public void testBlobStorePut() throws InterruptedException {
    MockEndpoint mockEndpoint = resolveMandatoryEndpoint("mock:results", MockEndpoint.class);
    mockEndpoint.expectedMessageCount(1);
    template.sendBody("direct:put", "Some message");
    mockEndpoint.assertIsSatisfied();
  }

  @Test
  public void testBlobStorePutAndGet() throws InterruptedException {
    String message = "Some message";
    template.sendBody("direct:put-and-get", message);
    Object result =
        template.requestBodyAndHeader(
            "direct:put-and-get",
            null,
            JcloudsConstants.OPERATION,
            JcloudsConstants.GET,
            String.class);
    assertEquals(message, result);
  }

  @Test
  public void testBlobStorePutWithStreamAndGet() throws InterruptedException, TransformerException {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(MESSAGE.getBytes());
    Exchange exchange = new DefaultExchange(context);
    StreamCache streamCache =
        StreamCacheConverter.convertToStreamCache(
            new SAXSource(new InputSource(inputStream)), exchange);
    template.sendBody("direct:put-and-get", streamCache);
    Object result =
        template.requestBodyAndHeader(
            "direct:put-and-get",
            null,
            JcloudsConstants.OPERATION,
            JcloudsConstants.GET,
            String.class);
    assertEquals(MESSAGE, result);
  }

  @Override
  protected RouteBuilder createRouteBuilder() throws Exception {
    blobStore.createContainerInLocation(null, TEST_CONTAINER);
    ((JcloudsComponent) context.getComponent("jclouds"))
        .setBlobStores(Lists.newArrayList(blobStore));

    return new RouteBuilder() {
      public void configure() {
        from("direct:put")
            .setHeader(JcloudsConstants.BLOB_NAME, constant(TEST_BLOB_IN_DIR))
            .setHeader(JcloudsConstants.CONTAINER_NAME, constant(TEST_CONTAINER))
            .to("jclouds:blobstore:transient")
            .to("mock:results");

        from("direct:put-and-get")
            .setHeader(JcloudsConstants.BLOB_NAME, constant(TEST_BLOB_IN_DIR))
            .setHeader(JcloudsConstants.CONTAINER_NAME, constant(TEST_CONTAINER))
            .to("jclouds:blobstore:transient");
      }
    };
  }
}
Пример #27
0
// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire
@Test(groups = "unit", testName = "FormSignerTest")
public class FormSignerTest {
  public static final Injector INJECTOR =
      ContextBuilder.newBuilder(
              AnonymousProviderMetadata.forClientMappedToAsyncClientOnEndpoint(
                  IntegrationTestClient.class,
                  IntegrationTestAsyncClient.class,
                  "http://localhost"))
          .credentials("identity", "credential")
          .apiVersion("apiVersion")
          .modules(
              ImmutableList.<Module>of(
                  new MockModule(),
                  new NullLoggingModule(),
                  new AbstractModule() {
                    @Override
                    protected void configure() {
                      bind(RequestSigner.class).to(FormSigner.class);
                      bind(String.class)
                          .annotatedWith(Names.named(PROPERTY_HEADER_TAG))
                          .toInstance("amz");
                      bind(String.class)
                          .annotatedWith(TimeStamp.class)
                          .toInstance("2009-11-08T15:54:08.897Z");
                    }
                  }))
          .buildInjector();
  FormSigner filter = INJECTOR.getInstance(FormSigner.class);

  @Test
  void testBuildCanonicalizedStringSetsVersion() {

    assertEquals(
        filter
            .filter(
                HttpRequest.builder()
                    .method("GET")
                    .endpoint("http://localhost")
                    .addHeader(HttpHeaders.HOST, "localhost")
                    .payload("Action=DescribeImages&ImageId.1=ami-2bb65342")
                    .build())
            .getPayload()
            .getRawContent(),
        "Action=DescribeImages&ImageId.1=ami-2bb65342&Signature=ugnt4m2eHE7Ka%2FvXTr9EhKZq7bhxOfvW0y4pAEqF97w%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&Version=apiVersion&AWSAccessKeyId=identity");
  }

  @Test
  void testBuildCanonicalizedString() {
    assertEquals(
        filter.buildCanonicalizedString(
            new ImmutableMultimap.Builder<String, String>()
                .put("AWSAccessKeyId", "foo")
                .put("Action", "DescribeImages")
                .put("Expires", "2008-02-10T12:00:00Z")
                .put("ImageId.1", "ami-2bb65342")
                .put("SignatureMethod", "HmacSHA256")
                .put("SignatureVersion", "2")
                .put("Version", "2010-06-15")
                .build()),
        "AWSAccessKeyId=foo&Action=DescribeImages&Expires=2008-02-10T12%3A00%3A00Z&ImageId.1=ami-2bb65342&SignatureMethod=HmacSHA256&SignatureVersion=2&Version=2010-06-15");
  }
}
 public CreateContainer(String username, String apiKey) {
   cloudFiles =
       ContextBuilder.newBuilder(PROVIDER)
           .credentials(username, apiKey)
           .buildApi(CloudFilesApi.class);
 }
Пример #29
0
 public UpdateDomains(String username, String apiKey) {
   dnsApi =
       ContextBuilder.newBuilder(PROVIDER)
           .credentials(username, apiKey)
           .buildApi(CloudDNSApi.class);
 }
 @BeforeClass
 public static void setUpClass() {
   ctx = ContextBuilder.newBuilder("transient").buildView(BlobStoreContext.class);
   System.setProperty("com.netflix.config.blobstore.containerName", DEFAULT_CONTAINER);
   ctx.getBlobStore().createContainerInLocation(null, DEFAULT_CONTAINER);
 }