org.jclouds.rest.AuthorizationException Java Examples

The following examples show how to use org.jclouds.rest.AuthorizationException. 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: AWSEC2ComputeServiceContextModule.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(
         final RegionAndIdToImage delegate) {
   return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() {
      private final AtomicReference<AuthorizationException> authException = Atomics.newReference();

      @Override
      public Image load(final RegionAndName key) throws Exception {
         // raw lookup of an image
         Supplier<Image> rawSupplier = new Supplier<Image>() {
            @Override public Image get() {
               try {
                  return delegate.load(key);
               } catch (ExecutionException e) {
                  throw Throwables.propagate(e);
               }
            }
         };
         return new SetAndThrowAuthorizationExceptionSupplier<Image>(rawSupplier, authException).get();
      }

   });
}
 
Example #2
Source File: AWSEC2ComputeServiceContextModuleTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception {
   AWSEC2ComputeServiceContextModule module = new AWSEC2ComputeServiceContextModule() {
      public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) {
         return super.provideRegionAndNameToImageSupplierCacheLoader(delegate);
      }
   };
   
   RegionAndName regionAndName = new RegionAndName("myregion", "myname");
   AuthorizationException authException = new AuthorizationException();
   
   RegionAndIdToImage mockRegionAndIdToImage = createMock(RegionAndIdToImage.class);
   expect(mockRegionAndIdToImage.load(regionAndName)).andThrow(authException).once();
   replay(mockRegionAndIdToImage);
   
   CacheLoader<RegionAndName, Image> cacheLoader = module.provideRegionAndNameToImageSupplierCacheLoader(mockRegionAndIdToImage).get();

   for (int i = 0; i < 2; i++) {
      try {
         Image image = cacheLoader.load(regionAndName);
         fail("Expected Authorization exception, but got " + image);
      } catch (AuthorizationException e) {
         // success
      }
   }
}
 
Example #3
Source File: NovaLauncher.java    From karamel with Apache License 2.0 5 votes vote down vote up
public static NovaContext validateCredentials(NovaCredentials novaCredentials, ContextBuilder builder)
        throws InvalidNovaCredentialsException {
  try {
    NovaContext context = new NovaContext(novaCredentials, builder);
    SecurityGroupApi securityGroupApi = context.getSecurityGroupApi();
    securityGroupApi.list();
    return context;
  } catch (AuthorizationException e) {
    throw new InvalidNovaCredentialsException("account-name:" + novaCredentials.getAccountName(), e);
  }
}
 
Example #4
Source File: GceLauncher.java    From karamel with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param credentials
 * @return
 * @throws InvalidCredentialsException
 */
public static GceContext validateCredentials(Credentials credentials) throws InvalidCredentialsException {
  try {
    GceContext context = new GceContext(credentials);
    GoogleComputeEngineApi gceApi = context.getGceApi();
    String projectName = gceApi.project().get().name();
    context.setProjectName(projectName);
    logger.info(String.format("Sucessfully Authenticated to project %s", projectName));
    return context;
  } catch (AuthorizationException e) {
    throw new InvalidCredentialsException("accountid:" + credentials.identity, e);
  }
}
 
Example #5
Source File: Ec2Launcher.java    From karamel with Apache License 2.0 5 votes vote down vote up
public static Ec2Context validateCredentials(Ec2Credentials credentials) throws InvalidEc2CredentialsException {
  try {
    if (credentials.getAccessKey().isEmpty() || credentials.getSecretKey().isEmpty()) {
      throw new InvalidEc2CredentialsException("Ec2 credentials empty - not entered yet.");
    }
    Ec2Context cxt = new Ec2Context(credentials);
    SecurityGroupApi securityGroupApi = cxt.getSecurityGroupApi();
    securityGroupApi.describeSecurityGroupsInRegion(Settings.AWS_REGION_CODE_DEFAULT);
    return cxt;
  } catch (AuthorizationException e) {
    throw new InvalidEc2CredentialsException(e.getMessage() + " - accountid:" + credentials.getAccessKey(), e);
  }
}
 
Example #6
Source File: AWSEC2ComputeServiceContextModule.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
protected Supplier<Set<? extends Image>> supplyNonParsingImageCache(
         AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,
         final Supplier<Set<? extends Image>> imageSupplier, Injector injector) {
   final Supplier<LoadingCache<RegionAndName, ? extends Image>> cache = injector.getInstance(Key
            .get(new TypeLiteral<Supplier<LoadingCache<RegionAndName, ? extends Image>>>() {
            }));
   return new Supplier<Set<? extends Image>>() {
      @Override
      public Set<? extends Image> get() {
         return ImmutableSet.copyOf(cache.get().asMap().values());
      }
   };
}
 
Example #7
Source File: NovaLauncherTest.java    From karamel with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidNovaCredentialsException.class)
public void validateNovaCredentialsTestException() throws InvalidNovaCredentialsException {
  when(securityGroupApi.list()).thenThrow(AuthorizationException.class);
  NovaContext context = NovaLauncher.validateCredentials(novaCredentials, builder);
}
 
Example #8
Source File: JcloudsStubTemplateBuilder.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
     * Used source from jclouds project.
     * {@link org.jclouds.ec2.compute.EC2TemplateBuilderTest#newTemplateBuilder}
     */
    @SuppressWarnings("unchecked")
    protected TemplateBuilder newTemplateBuilder(Supplier<Set<? extends Image>> images, Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache) {
        Provider<TemplateOptions> optionsProvider = mock(Provider.class);
        Provider<TemplateBuilder> templateBuilderProvider = mock(Provider.class);
        TemplateOptions defaultOptions = newTemplateOptions();
        final GetImageStrategy getImageStrategy = mock(GetImageStrategy.class);

        when(optionsProvider.get()).thenReturn(defaultOptions);

        Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
                .of(jcloudsDomainLocation));
        Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
                .of(getHardware()));


//        AtomicReference<AuthorizationException> authException = new AtomicReference<AuthorizationException>(new AuthorizationException());
        AtomicReference<AuthorizationException> authException = new AtomicReference<AuthorizationException>();

        com.google.inject.Provider<GetImageStrategy> imageLoader = new com.google.inject.Provider<GetImageStrategy>() {
            @Override
            public GetImageStrategy get() {
                return getImageStrategy;
            }
        };

        switch (providerName) {
        case "aws-ec2" :
        case "ec2" :
            return new EC2TemplateBuilderImpl(
                    locations,
                    new ImageCacheSupplier(images, 60, authException, imageLoader),
                    sizes,
                    Suppliers.ofInstance(jcloudsDomainLocation),
                    optionsProvider,
                    templateBuilderProvider,
                    imageCache) {
                @Override
                protected MoreObjects.ToStringHelper string() {
                    return super.string().add("type", "Stubbed-TemplateBuilder");
                }
            };
        default:
            return new TemplateBuilderImpl(
                    locations,
                    new ImageCacheSupplier(images, 60, authException, imageLoader),
                    sizes,
                    Suppliers.ofInstance(jcloudsDomainLocation),
                    optionsProvider,
                    templateBuilderProvider) {
                @Override
                protected MoreObjects.ToStringHelper string() {
                    return super.string().add("type", "Stubbed-TemplateBuilder");
                }
            };
        }
    }
 
Example #9
Source File: S3ProxyHandler.java    From s3proxy with Apache License 2.0 4 votes vote down vote up
private static void handleContainerCreate(HttpServletRequest request,
        HttpServletResponse response, InputStream is, BlobStore blobStore,
        String containerName) throws IOException, S3Exception {
    if (containerName.isEmpty()) {
        throw new S3Exception(S3ErrorCode.METHOD_NOT_ALLOWED);
    }

    String contentLengthString = request.getHeader(
            HttpHeaders.CONTENT_LENGTH);
    if (contentLengthString != null) {
        long contentLength;
        try {
            contentLength = Long.parseLong(contentLengthString);
        } catch (NumberFormatException nfe) {
            throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe);
        }
        if (contentLength < 0) {
            throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
        }
    }

    String locationString;
    try (PushbackInputStream pis = new PushbackInputStream(is)) {
        int ch = pis.read();
        if (ch == -1) {
            // handle empty bodies
            locationString = null;
        } else {
            pis.unread(ch);
            CreateBucketRequest cbr = new XmlMapper().readValue(
                    pis, CreateBucketRequest.class);
            locationString = cbr.locationConstraint;
        }
    }

    Location location = null;
    if (locationString != null) {
        for (Location loc : blobStore.listAssignableLocations()) {
            if (loc.getId().equalsIgnoreCase(locationString)) {
                location = loc;
                break;
            }
        }
        if (location == null) {
            throw new S3Exception(S3ErrorCode.INVALID_LOCATION_CONSTRAINT);
        }
    }
    logger.debug("Creating bucket with location: {}", location);

    CreateContainerOptions options = new CreateContainerOptions();
    String acl = request.getHeader(AwsHttpHeaders.ACL);
    if ("public-read".equalsIgnoreCase(acl)) {
        options.publicRead();
    }

    boolean created;
    try {
        created = blobStore.createContainerInLocation(location,
                containerName, options);
    } catch (AuthorizationException ae) {
        if (ae.getCause() instanceof AccessDeniedException) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED,
                    "Could not create bucket", ae);
        }
        throw new S3Exception(S3ErrorCode.BUCKET_ALREADY_EXISTS, ae);
    }
    if (!created) {
        throw new S3Exception(S3ErrorCode.BUCKET_ALREADY_OWNED_BY_YOU,
                S3ErrorCode.BUCKET_ALREADY_OWNED_BY_YOU.getMessage(),
                null, ImmutableMap.of("BucketName", containerName));
    }

    response.addHeader(HttpHeaders.LOCATION, "/" + containerName);
}