diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClientTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClientTest.java index a3de15092c..885e867ca4 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClientTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClientTest.java @@ -70,17 +70,15 @@ public class AtmosStorageAsyncClientTest extends RestClientTest createContextSpec() { - return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", - new Properties()); + return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", new Properties()); } } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java index 0c6bf2c8b8..5869f41109 100755 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java @@ -130,39 +130,31 @@ public class EC2ComputeServiceContextModule extends AbstractModule { @Singleton @Named("PRESENT") protected Predicate instancePresent(InstancePresent present) { - return new RetryablePredicate(present, 3000, 200, - TimeUnit.MILLISECONDS); + return new RetryablePredicate(present, 3000, 200, TimeUnit.MILLISECONDS); } @Override protected void configure() { install(new ComputeServiceTimeoutsModule()); - bind(Location.class).toProvider(DefaultLocationProvider.class).in( - Scopes.SINGLETON); + bind(Location.class).toProvider(DefaultLocationProvider.class).in(Scopes.SINGLETON); bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class); bind(TemplateOptions.class).to(EC2TemplateOptions.class); bind(ComputeService.class).to(EC2ComputeService.class); bind(new TypeLiteral() { - }) - .to( - new TypeLiteral>() { - }).in(Scopes.SINGLETON); + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); bind(new TypeLiteral>() { }).to(new TypeLiteral>() { }).in(Scopes.SINGLETON); - bind(LoadBalanceNodesStrategy.class) - .to(EC2LoadBalanceNodesStrategy.class); - bind(DestroyLoadBalancerStrategy.class).to( - EC2DestroyLoadBalancerStrategy.class); - bind(RunNodesAndAddToSetStrategy.class).to( - EC2RunNodesAndAddToSetStrategy.class); + bind(LoadBalanceNodesStrategy.class).to(EC2LoadBalanceNodesStrategy.class); + bind(DestroyLoadBalancerStrategy.class).to(EC2DestroyLoadBalancerStrategy.class); + bind(RunNodesAndAddToSetStrategy.class).to(EC2RunNodesAndAddToSetStrategy.class); bind(ListNodesStrategy.class).to(EC2ListNodesStrategy.class); bind(GetNodeMetadataStrategy.class).to(EC2GetNodeMetadataStrategy.class); bind(RebootNodeStrategy.class).to(EC2RebootNodeStrategy.class); bind(DestroyNodeStrategy.class).to(EC2DestroyNodeStrategy.class); bind(new TypeLiteral>>() { - }).annotatedWith(Names.named("volumeMapping")).to( - RunningInstanceToStorageMappingUnix.class).in(Scopes.SINGLETON); + }).annotatedWith(Names.named("volumeMapping")).to(RunningInstanceToStorageMappingUnix.class).in(Scopes.SINGLETON); } @Provides @@ -181,12 +173,10 @@ public class EC2ComputeServiceContextModule extends AbstractModule { @Provides @Named("DEFAULT") - protected TemplateBuilder provideTemplate(@Region String region, - TemplateBuilder template) { - return "Eucalyptus".equals(region) ? template.osFamily(CENTOS).smallest() - : template.architecture(Architecture.X86_32).osFamily(UBUNTU) - .imageNameMatches(".*10\\.?04.*").osDescriptionMatches( - "^ubuntu-images.*"); + protected TemplateBuilder provideTemplate(@Region String region, TemplateBuilder template) { + return "Eucalyptus".equals(region) ? template.osFamily(CENTOS).smallest() : template.architecture( + Architecture.X86_32).osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*").osDescriptionMatches( + "^ubuntu-images.*"); } // TODO make this more efficient for listNodes(); currently @@ -204,8 +194,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule { private final ExecutorService executor; @Inject - protected EC2ListNodesStrategy(EC2Client client, - @Region Map regionMap, + protected EC2ListNodesStrategy(EC2Client client, @Region Map regionMap, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { this.client = client; @@ -220,45 +209,37 @@ public class EC2ComputeServiceContextModule extends AbstractModule { } @Override - public Iterable listDetailsOnNodesMatching( - Predicate filter) { + public Iterable listDetailsOnNodesMatching(Predicate filter) { final Set nodes = Sets.newHashSet(); Map> parallelResponses = Maps.newHashMap(); for (final String region : regionMap.keySet()) { - parallelResponses.put(region, ConcurrentUtils.makeListenable( - executor.submit(new Callable() { - @Override - public Void call() throws Exception { - Iterables.addAll(nodes, Iterables.transform(Iterables - .concat(client.getInstanceServices() - .describeInstancesInRegion(region)), - runningInstanceToNodeMetadata)); - return null; - } - }), executor)); + parallelResponses.put(region, ConcurrentUtils.makeListenable(executor.submit(new Callable() { + @Override + public Void call() throws Exception { + Iterables.addAll(nodes, Iterables.transform(Iterables.concat(client.getInstanceServices() + .describeInstancesInRegion(region)), runningInstanceToNodeMetadata)); + return null; + } + }), executor)); } - Map exceptions = awaitCompletion(parallelResponses, - executor, null, logger, "nodes"); + Map exceptions = awaitCompletion(parallelResponses, executor, null, logger, "nodes"); if (exceptions.size() > 0) - throw new RuntimeException(String.format( - "error parsing nodes in regions: %s", exceptions)); + throw new RuntimeException(String.format("error parsing nodes in regions: %s", exceptions)); return Iterables.filter(nodes, filter); } } @Singleton - public static class EC2GetNodeMetadataStrategy implements - GetNodeMetadataStrategy { + public static class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy { private final EC2Client client; private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata; @Inject - protected EC2GetNodeMetadataStrategy(EC2Client client, - RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) { + protected EC2GetNodeMetadataStrategy(EC2Client client, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) { this.client = client; this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata; } @@ -269,9 +250,8 @@ public class EC2ComputeServiceContextModule extends AbstractModule { String region = parts[0]; String instanceId = parts[1]; try { - RunningInstance runningInstance = Iterables - .getOnlyElement(getAllRunningInstancesInRegion(client - .getInstanceServices(), region, instanceId)); + RunningInstance runningInstance = Iterables.getOnlyElement(getAllRunningInstancesInRegion(client + .getInstanceServices(), region, instanceId)); return runningInstanceToNodeMetadata.apply(runningInstance); } catch (NoSuchElementException e) { return null; @@ -286,8 +266,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule { private final GetNodeMetadataStrategy getNode; @Inject - protected EC2RebootNodeStrategy(EC2Client client, - GetNodeMetadataStrategy getNode) { + protected EC2RebootNodeStrategy(EC2Client client, GetNodeMetadataStrategy getNode) { this.client = client.getInstanceServices(); this.getNode = getNode; } @@ -305,8 +284,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule { @Provides @Singleton - protected final Map credentialsMap( - CreateUniqueKeyPair in) { + protected final Map credentialsMap(CreateUniqueKeyPair in) { // doesn't seem to clear when someone issues remove(key) // return new MapMaker().makeComputingMap(in); return Maps.newLinkedHashMap(); @@ -314,8 +292,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule { @Provides @Singleton - protected final Map securityGroupMap( - CreateSecurityGroupIfNeeded in) { + protected final Map securityGroupMap(CreateSecurityGroupIfNeeded in) { // doesn't seem to clear when someone issues remove(key) // return new MapMaker().makeComputingMap(in); return Maps.newLinkedHashMap(); @@ -334,45 +311,36 @@ public class EC2ComputeServiceContextModule extends AbstractModule { @Provides @Singleton - Set provideSizes(Set locations, - @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) { + Set provideSizes(Set locations, @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) { Set sizes = Sets.newHashSet(); for (String ccAmi : ccAmis) { final String region = ccAmi.split("/")[0]; - Location location = Iterables.find(locations, - new Predicate() { + Location location = Iterables.find(locations, new Predicate() { - @Override - public boolean apply(Location input) { - return input.getScope() == LocationScope.REGION - && input.getId().equals(region); - } + @Override + public boolean apply(Location input) { + return input.getScope() == LocationScope.REGION && input.getId().equals(region); + } - }); - sizes.add(new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, - 23 * 1024, 1690, ccAmis)); + }); + sizes.add(new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, 23 * 1024, 1690, ccAmis)); } - sizes.addAll(ImmutableSet. of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, - EC2Size.M1_LARGE, EC2Size.M1_SMALL, EC2Size.M1_XLARGE, - EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE)); + sizes.addAll(ImmutableSet. of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, EC2Size.M1_LARGE, EC2Size.M1_SMALL, + EC2Size.M1_XLARGE, EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE)); return sizes; } @Provides @Singleton - Set provideLocations( - Map availabilityZoneToRegionMap, + Set provideLocations(Map availabilityZoneToRegionMap, @Provider String providerName) { - Location ec2 = new LocationImpl(LocationScope.PROVIDER, providerName, - providerName, null); + Location ec2 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); Set locations = Sets.newLinkedHashSet(); for (String zone : availabilityZoneToRegionMap.keySet()) { - Location region = new LocationImpl(LocationScope.REGION, - availabilityZoneToRegionMap.get(zone), + Location region = new LocationImpl(LocationScope.REGION, availabilityZoneToRegionMap.get(zone), availabilityZoneToRegionMap.get(zone), ec2); locations.add(region); - locations - .add(new LocationImpl(LocationScope.ZONE, zone, zone, region)); + locations.add(new LocationImpl(LocationScope.ZONE, zone, zone, region)); } return locations; } @@ -402,29 +370,24 @@ public class EC2ComputeServiceContextModule extends AbstractModule { } @Provides - protected Set provideImages( - Map map) { + protected Set provideImages(Map map) { return ImmutableSet.copyOf(map.values()); } @Provides @Singleton - protected ConcurrentMap provideImageMap( - RegionAndIdToImage regionAndIdToImage) { + protected ConcurrentMap provideImageMap(RegionAndIdToImage regionAndIdToImage) { return new MapMaker().makeComputingMap(regionAndIdToImage); } @Provides @Singleton - protected Map provideImages( - final EC2Client sync, @Region Map regionMap, - final LogHolder holder, Function indexer, - @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, - @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners, - final ImageParser parser, - final ConcurrentMap images, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) - throws InterruptedException, ExecutionException, TimeoutException { + protected Map provideImages(final EC2Client sync, + @Region Map regionMap, final LogHolder holder, Function indexer, + @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners, + final ImageParser parser, final ConcurrentMap images, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) throws InterruptedException, + ExecutionException, TimeoutException { if (amiOwners.length == 0) { holder.logger.debug(">> no owners specified, skipping image parsing"); } else { @@ -437,40 +400,33 @@ public class EC2ComputeServiceContextModule extends AbstractModule { else options = ownedBy(amiOwners); for (final String region : regionMap.keySet()) { - parallelResponses.put(region, ConcurrentUtils.makeListenable( - executor.submit(new Callable() { - @Override - public Void call() throws Exception { - for (final org.jclouds.aws.ec2.domain.Image from : sync - .getAMIServices().describeImagesInRegion(region, - options)) { - Image image = parser.apply(from); - if (image != null) - images.put(new RegionAndName(region, image - .getProviderId()), image); - else if (from.getImageType() == ImageType.MACHINE) - holder.logger.trace("<< image(%s) didn't parse", - from.getId()); - } - return null; - } - }), executor)); + parallelResponses.put(region, ConcurrentUtils.makeListenable(executor.submit(new Callable() { + @Override + public Void call() throws Exception { + Set matchingImages = sync.getAMIServices().describeImagesInRegion( + region, options); + for (final org.jclouds.aws.ec2.domain.Image from : matchingImages) { + Image image = parser.apply(from); + if (image != null) + images.put(new RegionAndName(region, image.getProviderId()), image); + else if (from.getImageType() == ImageType.MACHINE) + holder.logger.trace("<< image(%s) didn't parse", from.getId()); + } + return null; + } + }), executor)); } - Map exceptions = awaitCompletion(parallelResponses, - executor, null, holder.logger, "images"); + Map exceptions = awaitCompletion(parallelResponses, executor, null, holder.logger, "images"); for (String ccAmi : ccAmis) { String region = ccAmi.split("/")[0]; - org.jclouds.aws.ec2.domain.Image from = Iterables - .getOnlyElement(sync.getAMIServices().describeImagesInRegion( - region, imageIds(ccAmi.split("/")[1]))); + org.jclouds.aws.ec2.domain.Image from = Iterables.getOnlyElement(sync.getAMIServices() + .describeImagesInRegion(region, imageIds(ccAmi.split("/")[1]))); Image image = parser.apply(from); if (image != null) - images.put(new RegionAndName(region, image.getProviderId()), - image); + images.put(new RegionAndName(region, image.getProviderId()), image); } if (exceptions.size() > 0) - throw new RuntimeException(String.format( - "error parsing images in regions: %s", exceptions)); + throw new RuntimeException(String.format("error parsing images in regions: %s", exceptions)); holder.logger.debug("<< images(%d)", images.size()); } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImpl.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImpl.java index f3faa21d81..3129e47b92 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImpl.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImpl.java @@ -1,6 +1,25 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ package org.jclouds.aws.ec2.compute.internal; -import java.util.List; +import static com.google.common.base.Preconditions.checkArgument; + import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; @@ -18,7 +37,7 @@ import org.jclouds.compute.internal.TemplateBuilderImpl; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Location; -import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; /** * @@ -29,15 +48,11 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl { private final ConcurrentMap imageMap; @Inject - protected EC2TemplateBuilderImpl( - Provider> locations, - Provider> images, - Provider> sizes, Location defaultLocation, - Provider optionsProvider, + protected EC2TemplateBuilderImpl(Provider> locations, Provider> images, + Provider> sizes, Location defaultLocation, Provider optionsProvider, @Named("DEFAULT") Provider defaultTemplateProvider, ConcurrentMap imageMap) { - super(locations, images, sizes, defaultLocation, optionsProvider, - defaultTemplateProvider); + super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider); this.imageMap = imageMap; } @@ -47,37 +62,62 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl { if (from instanceof EC2TemplateOptions) { EC2TemplateOptions eFrom = EC2TemplateOptions.class.cast(from); EC2TemplateOptions eTo = EC2TemplateOptions.class.cast(to); - if (eFrom.getGroupIds().size() >0) + if (eFrom.getGroupIds().size() > 0) eTo.securityGroups(eFrom.getGroupIds()); if (eFrom.getKeyPair() != null) eTo.keyPair(eFrom.getKeyPair()); if (!eFrom.shouldAutomaticallyCreateKeyPair()) eTo.noKeyPair(); - if(eFrom.getSubnetId() != null) + if (eFrom.getSubnetId() != null) eTo.subnetId(eFrom.getSubnetId()); } } + final Provider lazyImageProvider = new Provider() { + + @Override + public Image get() { + if (imageId != null) { + String[] regionName = imageId.split("/"); + checkArgument(regionName.length == 2, + "amazon image ids must include the region. ex. us-east-1/ami-7ea24a17"); + RegionAndName key = new RegionAndName(regionName[0], regionName[1]); + try { + return imageMap.get(key); + } catch (NullPointerException nex) { + throw new NoSuchElementException(String.format("image %s/%s not found", key.getRegion(), key.getName())); + } + } + return null; + } + + }; + /** * @throws NoSuchElementException * if the image is not found */ @Override - protected List resolveImages() { + protected Image resolveImage(Size size) { try { - return super.resolveImages(); + return super.resolveImage(size); } catch (NoSuchElementException e) { - if (locationId != null && imageId != null) { - RegionAndName key = new RegionAndName(this.locationId, this.imageId); - try { - return ImmutableList.of(imageMap.get(key)); - } catch (NullPointerException nex) { - throw new NoSuchElementException(String.format( - "image %s/%s not found", key.getRegion(), key.getName())); - } - } + Image returnVal = lazyImageProvider.get(); + if (returnVal != null) + return returnVal; throw e; } } + @Override + protected Set getImages() { + Set images = this.images.get(); + if (images.size() == 0) { + Image toReturn = lazyImageProvider.get(); + if (toReturn != null) + return ImmutableSet.of(lazyImageProvider.get()); + } + return images; + } + } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandler.java b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandler.java index f634704617..f5a876e72c 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandler.java @@ -21,7 +21,9 @@ package org.jclouds.aws.ec2.xml; import java.util.Set; import javax.annotation.Resource; +import javax.inject.Inject; +import org.jclouds.aws.Region; import org.jclouds.aws.ec2.domain.AvailabilityZoneInfo; import org.jclouds.http.functions.ParseSax; import org.jclouds.logging.Logger; @@ -33,9 +35,9 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -public class DescribeAvailabilityZonesResponseHandler extends - ParseSax.HandlerWithResult> { +public class DescribeAvailabilityZonesResponseHandler extends ParseSax.HandlerWithResult> { private StringBuilder currentText = new StringBuilder(); + private final String defaultRegion; private Set availablilityZones = Sets.newLinkedHashSet(); private String zone; @@ -46,6 +48,15 @@ public class DescribeAvailabilityZonesResponseHandler extends private boolean inMessageSet; private Set messages = Sets.newHashSet(); + /** + * Eucalyptus 1.6 doesn't return region in the XML output + */ + @Inject + DescribeAvailabilityZonesResponseHandler(@Region String defaultRegion) { + this.defaultRegion = defaultRegion; + region = defaultRegion; + } + public Set getResult() { return availablilityZones; } @@ -75,7 +86,7 @@ public class DescribeAvailabilityZonesResponseHandler extends } else if (qName.equals("item") && !inMessageSet) { availablilityZones.add(new AvailabilityZoneInfo(zone, zoneState, region, messages)); this.zone = null; - this.region = null; + this.region = defaultRegion; this.zoneState = null; this.messages = Sets.newHashSet(); } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java index fc5d44e13d..d399ae3554 100755 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java @@ -49,8 +49,7 @@ import com.google.common.collect.Sets; * @see */ -public class DescribeImagesResponseHandler extends - ParseSax.HandlerForGeneratedRequestWithResult> { +public class DescribeImagesResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { @Inject public DescribeImagesResponseHandler(@Region String defaultRegion) { @@ -79,7 +78,10 @@ public class DescribeImagesResponseHandler extends private String ramdiskId; private boolean inProductCodes; private boolean inBlockDeviceMapping; - private RootDeviceType rootDeviceType; + /** + * Eucalyptus 1.6 doesn't set rootDeviceType + */ + private RootDeviceType rootDeviceType = RootDeviceType.INSTANCE_STORE; private Map ebsBlockDevices = Maps.newHashMap(); private String deviceName; private String snapshotId; @@ -149,8 +151,7 @@ public class DescribeImagesResponseHandler extends virtualizationType = currentText.toString().trim(); } else if (qName.equals("item")) { if (inBlockDeviceMapping) { - ebsBlockDevices.put(deviceName, new Image.EbsBlockDevice(snapshotId, volumeSize, - deleteOnTermination)); + ebsBlockDevices.put(deviceName, new Image.EbsBlockDevice(snapshotId, volumeSize, deleteOnTermination)); this.deviceName = null; this.snapshotId = null; this.volumeSize = 0; @@ -160,10 +161,9 @@ public class DescribeImagesResponseHandler extends String region = EC2Utils.findRegionInArgsOrNull((GeneratedHttpRequest) request); if (region == null) region = defaultRegion; - contents.add(new Image(region, architecture, this.name, description, imageId, - imageLocation, imageOwnerId, imageState, imageType, isPublic, productCodes, - kernelId, platform, ramdiskId, rootDeviceType, rootDeviceName, - ebsBlockDevices, virtualizationType)); + contents.add(new Image(region, architecture, this.name, description, imageId, imageLocation, + imageOwnerId, imageState, imageType, isPublic, productCodes, kernelId, platform, ramdiskId, + rootDeviceType, rootDeviceName, ebsBlockDevices, virtualizationType)); } catch (NullPointerException e) { logger.warn(e, "malformed image: %s", imageId); } @@ -180,7 +180,7 @@ public class DescribeImagesResponseHandler extends this.platform = null; this.productCodes = Sets.newHashSet(); this.ramdiskId = null; - this.rootDeviceType = null; + this.rootDeviceType = RootDeviceType.INSTANCE_STORE; this.rootDeviceName = null; this.ebsBlockDevices = Maps.newHashMap(); this.virtualizationType = "paravirtual"; diff --git a/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java b/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java index cd06ae0b1a..ce61833573 100755 --- a/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java +++ b/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java @@ -66,33 +66,33 @@ public class ParseAWSErrorFromXmlContent implements HttpErrorHandler { try { AWSError error = utils.parseAWSErrorFromContent(request, response); exception = error != null ? new AWSResponseException(command, response, error) : exception; + String notFoundMessage = error != null ? error.getMessage() : String.format("%s -> %s", request + .getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { - case 400: - if (error.getCode().endsWith(".NotFound")) - exception = new ResourceNotFoundException(error.getMessage(), exception); - else if (error.getCode().equals("IncorrectState")) - exception = new IllegalStateException(error.getMessage(), exception); - else if (error.getCode().equals("AuthFailure")) - exception = new AuthorizationException(command.getRequest(), - error != null ? error.getMessage() : response.getStatusLine()); - break; - case 401: - case 403: - exception = new AuthorizationException(command.getRequest(), error != null ? error - .getMessage() : response.getStatusLine()); - break; - case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String message = error != null ? error.getMessage() : String.format("%s -> %s", - request.getRequestLine(), response.getStatusLine()); - String container = request.getEndpoint().getHost(); - String key = request.getEndpoint().getPath(); - if (key == null || key.equals("/")) - exception = new ContainerNotFoundException(container, message); - else - exception = new KeyNotFoundException(container, key, message); - } - break; + case 400: + if (error.getCode().endsWith(".NotFound")) + exception = new ResourceNotFoundException(notFoundMessage, exception); + else if (error.getCode().equals("IncorrectState")) + exception = new IllegalStateException(error.getMessage(), exception); + else if (error.getCode().equals("AuthFailure")) + exception = new AuthorizationException(command.getRequest(), error != null ? error.getMessage() + : response.getStatusLine()); + break; + case 401: + case 403: + exception = new AuthorizationException(command.getRequest(), error != null ? error.getMessage() : response + .getStatusLine()); + break; + case 404: + if (!command.getRequest().getMethod().equals("DELETE")) { + String container = request.getEndpoint().getHost(); + String key = request.getEndpoint().getPath(); + if (key == null || key.equals("/")) + exception = new ContainerNotFoundException(container, notFoundMessage); + else + exception = new KeyNotFoundException(container, key, notFoundMessage); + } + break; } } finally { releasePayload(response); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java index 76b1ea3d33..471fcb6e68 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java @@ -33,8 +33,10 @@ import org.jclouds.aws.ec2.services.InstanceClient; import org.jclouds.aws.ec2.services.KeyPairClient; import org.jclouds.aws.ec2.services.SecurityGroupClient; import org.jclouds.compute.BaseComputeServiceLiveTest; +import org.jclouds.compute.domain.Architecture; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.TemplateOptions; @@ -66,7 +68,32 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { } @Test(enabled = true, dependsOnMethods = "testCorrectAuthException") + public void testImagesResolveCorrectly() { + Template defaultTemplate = client.templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getId(), defaultTemplate.getImage().getLocation().getId() + "/" + + defaultTemplate.getImage().getProviderId()); + Template byId = client.templateBuilder().imageId(defaultTemplate.getImage().getId()).build(); + assertEquals(byId.getImage(), defaultTemplate.getImage()); + } + + @Test(enabled = true, dependsOnMethods = "testImagesResolveCorrectly") + public void testDefaultTemplateBuilder() { + assertDefaultWorks(); + } + + protected void assertDefaultWorks() { + Template defaultTemplate = client.templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getArchitecture(), Architecture.X86_32); + assertEquals(defaultTemplate.getImage().getOsFamily(), OsFamily.UBUNTU); + assertEquals(defaultTemplate.getSize().getCores(), 1.0d); + } + + @Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder") public void testTemplateChoiceForInstanceByCCSizeId() throws Exception { + assertCCsizeWorks(); + } + + protected void assertCCsizeWorks() { Set sizes = context.getComputeService().listSizes(); assert Iterables.any(sizes, new Predicate() { @@ -85,24 +112,21 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { } }) : images; - Template template = context.getComputeService().templateBuilder() - .fastest().build(); + Template template = context.getComputeService().templateBuilder().fastest().build(); assert template != null : "The returned template was null, but it should have a value."; assertEquals(template.getSize().getProviderId(), InstanceType.CC1_4XLARGE); assertEquals(template.getImage().getId(), "us-east-1/ami-7ea24a17"); } - @Test(enabled = true, dependsOnMethods = "testTemplateChoiceForInstanceByCCSizeId") + @Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder") public void testExtendedOptionsAndLogin() throws Exception { - SecurityGroupClient securityGroupClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()) + SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getSecurityGroupServices(); - KeyPairClient keyPairClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()).getKeyPairServices(); + KeyPairClient keyPairClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) + .getKeyPairServices(); - InstanceClient instanceClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()) + InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); String tag = this.tag + "optionsandlogin"; @@ -119,14 +143,12 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { // create a security group that allows ssh in so that our scripts later // will work securityGroupClient.createSecurityGroupInRegion(null, tag, tag); - securityGroupClient.authorizeSecurityGroupIngressInRegion(null, tag, - IpProtocol.TCP, 22, 22, "0.0.0.0/0"); + securityGroupClient.authorizeSecurityGroupIngressInRegion(null, tag, IpProtocol.TCP, 22, 22, "0.0.0.0/0"); // create a keypair to pass in as well KeyPair result = keyPairClient.createKeyPairInRegion(null, tag); - Set nodes = client.runNodesWithTag(tag, 1, - options); + Set nodes = client.runNodesWithTag(tag, 1, options); NodeMetadata first = Iterables.get(nodes, 0); assert first.getCredentials() != null : first; assert first.getCredentials().identity != null : first; @@ -138,27 +160,23 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { assertEquals(instance.getKeyName(), tag); // make sure we made our dummy group and also let in the user's group - assertEquals(instance.getGroupIds(), ImmutableSet. of(tag, - "jclouds#" + tag)); + assertEquals(instance.getGroupIds(), ImmutableSet. of(tag, "jclouds#" + tag)); // make sure our dummy group has no rules - SecurityGroup group = Iterables.getOnlyElement(securityGroupClient - .describeSecurityGroupsInRegion(null, "jclouds#" + tag)); + SecurityGroup group = Iterables.getOnlyElement(securityGroupClient.describeSecurityGroupsInRegion(null, + "jclouds#" + tag)); assert group.getIpPermissions().size() == 0 : group; // try to run a script with the original keyPair - runScriptWithCreds(tag, first.getImage().getOsFamily(), - new Credentials(first.getCredentials().identity, result - .getKeyMaterial())); + runScriptWithCreds(tag, first.getImage().getOsFamily(), new Credentials(first.getCredentials().identity, + result.getKeyMaterial())); } finally { client.destroyNodesMatching(NodePredicates.withTag(tag)); if (startedId != null) { // ensure we didn't delete these resources! - assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag) - .size(), 1); - assertEquals(securityGroupClient.describeSecurityGroupsInRegion( - null, tag).size(), 1); + assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag).size(), 1); + assertEquals(securityGroupClient.describeSecurityGroupsInRegion(null, tag).size(), 1); } cleanupExtendedStuff(securityGroupClient, keyPairClient, tag); } @@ -166,15 +184,13 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { @Test(enabled = true, dependsOnMethods = "testTemplateChoiceForInstanceByCCSizeId") public void testExtendedOptionsNoKeyPair() throws Exception { - SecurityGroupClient securityGroupClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()) + SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getSecurityGroupServices(); - KeyPairClient keyPairClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()).getKeyPairServices(); + KeyPairClient keyPairClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) + .getKeyPairServices(); - InstanceClient instanceClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()) + InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); String tag = this.tag + "optionsnokey"; @@ -191,8 +207,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { // create the security group securityGroupClient.createSecurityGroupInRegion(null, tag, tag); - Set nodes = client.runNodesWithTag(tag, 1, - options); + Set nodes = client.runNodesWithTag(tag, 1, options); Credentials creds = nodes.iterator().next().getCredentials(); assert creds == null; @@ -203,20 +218,18 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { assertEquals(instance.getKeyName(), null); // make sure we made our dummy group and also let in the user's group - assertEquals(instance.getGroupIds(), ImmutableSet. of(tag, - "jclouds#" + tag)); + assertEquals(instance.getGroupIds(), ImmutableSet. of(tag, "jclouds#" + tag)); // make sure our dummy group has no rules - SecurityGroup group = Iterables.getOnlyElement(securityGroupClient - .describeSecurityGroupsInRegion(null, "jclouds#" + tag)); + SecurityGroup group = Iterables.getOnlyElement(securityGroupClient.describeSecurityGroupsInRegion(null, + "jclouds#" + tag)); assert group.getIpPermissions().size() == 0 : group; } finally { client.destroyNodesMatching(NodePredicates.withTag(tag)); if (startedId != null) { // ensure we didn't delete these resources! - assertEquals(securityGroupClient.describeSecurityGroupsInRegion( - null, tag).size(), 1); + assertEquals(securityGroupClient.describeSecurityGroupsInRegion(null, tag).size(), 1); } cleanupExtendedStuff(securityGroupClient, keyPairClient, tag); } @@ -230,15 +243,13 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { // Skip test and return return; } - SecurityGroupClient securityGroupClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()) + SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getSecurityGroupServices(); - KeyPairClient keyPairClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()).getKeyPairServices(); + KeyPairClient keyPairClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) + .getKeyPairServices(); - InstanceClient instanceClient = EC2Client.class.cast( - context.getProviderSpecificContext().getApi()) + InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); String tag = this.tag + "optionswithsubnetid"; @@ -260,8 +271,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { // create a keypair to pass in as well keyPairClient.createKeyPairInRegion(null, tag); - Set nodes = client.runNodesWithTag(tag, 1, - options); + Set nodes = client.runNodesWithTag(tag, 1, options); NodeMetadata first = Iterables.get(nodes, 0); assert first.getCredentials() != null : first; @@ -279,22 +289,19 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { client.destroyNode(nodeId); if (startedId != null) { // ensure we didn't delete these resources! - assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag) - .size(), 1); + assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag).size(), 1); } cleanupExtendedStuff(securityGroupClient, keyPairClient, tag); } } private RunningInstance getInstance(InstanceClient instanceClient, String id) { - RunningInstance instance = Iterables - .getOnlyElement(Iterables.getOnlyElement(instanceClient - .describeInstancesInRegion(null, id))); + RunningInstance instance = Iterables.getOnlyElement(Iterables.getOnlyElement(instanceClient + .describeInstancesInRegion(null, id))); return instance; } - private void cleanupExtendedStuff(SecurityGroupClient securityGroupClient, - KeyPairClient keyPairClient, String tag) { + private void cleanupExtendedStuff(SecurityGroupClient securityGroupClient, KeyPairClient keyPairClient, String tag) { try { securityGroupClient.deleteSecurityGroupInRegion(null, tag); } catch (Exception e) { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTest.java index 13db7748d1..27c895ce04 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTest.java @@ -18,6 +18,11 @@ */ package org.jclouds.aws.ec2.compute; +import static org.testng.Assert.assertEquals; + +import org.jclouds.compute.domain.Architecture; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Template; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -35,4 +40,17 @@ public class EucalyptusComputeServiceLiveTest extends EC2ComputeServiceLiveTest tag = "euc"; } + @Override + protected void assertDefaultWorks() { + Template defaultTemplate = client.templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getArchitecture(), Architecture.X86_64); + assertEquals(defaultTemplate.getImage().getOsFamily(), OsFamily.CENTOS); + // 64 bit implied 4 ecus + assertEquals(defaultTemplate.getSize().getCores(), 4.0d); + } + + @Override + protected void assertCCsizeWorks() { + // no CC size in eucalyptus + } } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java index 2180fa4339..29a4b04e5b 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java @@ -49,54 +49,41 @@ import com.google.common.collect.Iterables; public class ImageParserTest extends BaseEC2HandlerTest { public void testParseAlesticCanonicalImage() { - InputStream is = getClass().getResourceAsStream( - "/ec2/alestic_canonical.xml"); + InputStream is = getClass().getResourceAsStream("/ec2/alestic_canonical.xml"); Set result = parseImages(is); assertEquals(result.size(), 7); - ImageParser parser = new ImageParser( - new EC2PopulateDefaultLoginCredentialsForImageStrategy(), - ImmutableSet. of(defaultLocation), defaultLocation); - org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables - .get(result, 0)); + ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet + . of(defaultLocation), defaultLocation); + org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables.get(result, 0)); - assertEquals(ubuntuHardy.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_32); - assertEquals(ubuntuHardy.getDescription(), - "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml"); + assertEquals(ubuntuHardy.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); + assertEquals(ubuntuHardy.getDescription(), "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml"); assertEquals(ubuntuHardy.getProviderId(), "ami-7e28ca17"); assertEquals(ubuntuHardy.getLocation(), defaultLocation); assertEquals(ubuntuHardy.getName(), "8.04"); assertEquals(ubuntuHardy.getOsDescription(), "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml"); assertEquals(ubuntuHardy.getOsFamily(), OsFamily.UBUNTU); - assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap - . of("owner", "099720109477")); + assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap. of("owner", "099720109477")); assertEquals(ubuntuHardy.getVersion(), "20091130"); - org.jclouds.compute.domain.Image alesticKarmic = parser.apply(Iterables - .get(result, 1)); + org.jclouds.compute.domain.Image alesticKarmic = parser.apply(Iterables.get(result, 1)); - assertEquals(alesticKarmic.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_32); - assertEquals(alesticKarmic.getDescription(), - "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml"); + assertEquals(alesticKarmic.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); + assertEquals(alesticKarmic.getDescription(), "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml"); assertEquals(alesticKarmic.getProviderId(), "ami-19a34270"); assertEquals(alesticKarmic.getLocation(), defaultLocation); assertEquals(alesticKarmic.getName(), "9.10"); - assertEquals(alesticKarmic.getOsDescription(), - "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml"); + assertEquals(alesticKarmic.getOsDescription(), "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml"); assertEquals(alesticKarmic.getOsFamily(), OsFamily.UBUNTU); - assertEquals(alesticKarmic.getUserMetadata(), ImmutableMap - . of("owner", "063491364108")); + assertEquals(alesticKarmic.getUserMetadata(), ImmutableMap. of("owner", "063491364108")); assertEquals(alesticKarmic.getVersion(), "20090623"); - org.jclouds.compute.domain.Image ubuntuKarmic = parser.apply(Iterables - .get(result, 2)); + org.jclouds.compute.domain.Image ubuntuKarmic = parser.apply(Iterables.get(result, 2)); - assertEquals(ubuntuKarmic.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_32); + assertEquals(ubuntuKarmic.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); assertEquals(ubuntuKarmic.getDescription(), "ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml"); assertEquals(ubuntuKarmic.getProviderId(), "ami-bb709dd2"); @@ -105,178 +92,128 @@ public class ImageParserTest extends BaseEC2HandlerTest { assertEquals(ubuntuKarmic.getOsDescription(), "ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml"); assertEquals(ubuntuKarmic.getOsFamily(), OsFamily.UBUNTU); - assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap - . of("owner", "099720109477")); + assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap. of("owner", "099720109477")); assertEquals(ubuntuKarmic.getVersion(), "20100121"); // should skip testing image assert parser.apply(Iterables.get(result, 3)) == null; - org.jclouds.compute.domain.Image alesticHardy = parser.apply(Iterables - .get(result, 4)); + org.jclouds.compute.domain.Image alesticHardy = parser.apply(Iterables.get(result, 4)); - assertEquals(alesticHardy.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_32); - assertEquals(alesticHardy.getDescription(), - "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml"); + assertEquals(alesticHardy.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); + assertEquals(alesticHardy.getDescription(), "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml"); assertEquals(alesticHardy.getProviderId(), "ami-c0fa1ea9"); assertEquals(alesticHardy.getLocation(), defaultLocation); assertEquals(alesticHardy.getName(), "8.04"); - assertEquals(alesticHardy.getOsDescription(), - "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml"); + assertEquals(alesticHardy.getOsDescription(), "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml"); assertEquals(alesticHardy.getOsFamily(), OsFamily.UBUNTU); - assertEquals(alesticHardy.getUserMetadata(), ImmutableMap - . of("owner", "063491364108")); + assertEquals(alesticHardy.getUserMetadata(), ImmutableMap. of("owner", "063491364108")); assertEquals(alesticHardy.getVersion(), "20080905"); - org.jclouds.compute.domain.Image ubuntuLucid = parser.apply(Iterables - .get(result, 5)); + org.jclouds.compute.domain.Image ubuntuLucid = parser.apply(Iterables.get(result, 5)); - assertEquals(ubuntuLucid.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_32); - assertEquals( - ubuntuLucid.getDescription(), + assertEquals(ubuntuLucid.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); + assertEquals(ubuntuLucid.getDescription(), "ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml"); assertEquals(ubuntuLucid.getProviderId(), "ami-c597c680"); assertEquals(ubuntuLucid.getLocation(), defaultLocation); assertEquals(ubuntuLucid.getName(), "10.04"); - assertEquals( - ubuntuLucid.getOsDescription(), + assertEquals(ubuntuLucid.getOsDescription(), "ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml"); assertEquals(ubuntuLucid.getOsFamily(), OsFamily.UBUNTU); - assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap - . of("owner", "099720109477")); + assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap. of("owner", "099720109477")); assertEquals(ubuntuLucid.getVersion(), "20100427.1"); // should skip kernel assert parser.apply(Iterables.get(result, 6)) == null; } - private Location defaultLocation = new LocationImpl(LocationScope.REGION, - "us-east-1", "us-east-1", null); + private Location defaultLocation = new LocationImpl(LocationScope.REGION, "us-east-1", "us-east-1", null); public void testParseVostokImage() { InputStream is = getClass().getResourceAsStream("/ec2/vostok.xml"); Set result = parseImages(is); - ImageParser parser = new ImageParser( - new EC2PopulateDefaultLoginCredentialsForImageStrategy(), - ImmutableSet. of(defaultLocation), defaultLocation); + ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet + . of(defaultLocation), defaultLocation); - org.jclouds.compute.domain.Image image = parser.apply(Iterables.get( - result, 0)); + org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0)); - assertEquals(image.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_32); - assertEquals(image.getDescription(), - "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml"); + assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); + assertEquals(image.getDescription(), "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml"); assertEquals(image.getProviderId(), "ami-870de2ee"); assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getName(), ""); - assertEquals(image.getOsDescription(), - "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml"); + assertEquals(image.getOsDescription(), "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml"); assertEquals(image.getOsFamily(), null); - assertEquals(image.getUserMetadata(), ImmutableMap. of( - "owner", "133804938231")); + assertEquals(image.getUserMetadata(), ImmutableMap. of("owner", "133804938231")); assertEquals(image.getVersion(), ""); } public void testParseRightScaleImage() { - InputStream is = getClass().getResourceAsStream( - "/ec2/rightscale_images.xml"); + InputStream is = getClass().getResourceAsStream("/ec2/rightscale_images.xml"); Set result = parseImages(is); - ImageParser parser = new ImageParser( - new EC2PopulateDefaultLoginCredentialsForImageStrategy(), - ImmutableSet. of(defaultLocation), defaultLocation); + ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet + . of(defaultLocation), defaultLocation); - org.jclouds.compute.domain.Image image = parser.apply(Iterables.get( - result, 0)); + org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0)); - assertEquals(image.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_64); - assertEquals(image.getDescription(), - "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml"); + assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_64); + assertEquals(image.getDescription(), "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml"); assertEquals(image.getProviderId(), "ami-ccb35ea5"); assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getName(), "5.4"); - assertEquals(image.getOsDescription(), - "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml"); + assertEquals(image.getOsDescription(), "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml"); assertEquals(image.getOsFamily(), OsFamily.CENTOS); - assertEquals(image.getUserMetadata(), ImmutableMap. of( - "owner", "411009282317")); + assertEquals(image.getUserMetadata(), ImmutableMap. of("owner", "411009282317")); assertEquals(image.getVersion(), "4.4.10"); image = parser.apply(Iterables.get(result, 1)); - assertEquals(image.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_64); - assertEquals(image.getDescription(), - "RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha"); + assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_64); + assertEquals(image.getDescription(), "RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha"); assertEquals(image.getProviderId(), "ami-c19db6b5"); assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getName(), "9.10"); - assertEquals(image.getOsDescription(), - "411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha"); + assertEquals(image.getOsDescription(), "411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha"); assertEquals(image.getOsFamily(), OsFamily.UBUNTU); - assertEquals(image.getUserMetadata(), ImmutableMap. of( - "owner", "411009282317")); + assertEquals(image.getUserMetadata(), ImmutableMap. of("owner", "411009282317")); assertEquals(image.getVersion(), "4.5.3_EBS_Alpha"); } public void testParseEucalyptusImage() { - InputStream is = getClass().getResourceAsStream( - "/ec2/eucalyptus_images.xml"); + InputStream is = getClass().getResourceAsStream("/ec2/eucalyptus_images.xml"); Set result = parseImages(is); - assertEquals(result.size(), 11); - ImageParser parser = new ImageParser( - new EC2PopulateDefaultLoginCredentialsForImageStrategy(), - ImmutableSet. of(defaultLocation), defaultLocation); + assertEquals(result.size(), 4); + ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet + . of(defaultLocation), defaultLocation); - org.jclouds.compute.domain.Image image = parser.apply(Iterables.get( - result, 0)); + org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0)); - assertEquals(image.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_64); - assertEquals(image.getDescription(), - "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml"); + assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_64); + assertEquals(image.getDescription(), "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml"); assertEquals(image.getProviderId(), "emi-9ACB1363"); assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getName(), "5.3"); - assertEquals(image.getOsDescription(), - "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml"); + assertEquals(image.getOsDescription(), "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml"); assertEquals(image.getOsFamily(), OsFamily.CENTOS); - assertEquals(image.getUserMetadata(), ImmutableMap. of( - "owner", "admin")); + assertEquals(image.getUserMetadata(), ImmutableMap. of("owner", "admin")); assertEquals(image.getVersion(), ""); - image = parser.apply(Iterables.get(result, 6)); - assertEquals(image.getDescription(), - "Lean/ubuntu.9-04.x86-64.img.manifest.xml"); - assertEquals(image.getArchitecture(), - org.jclouds.compute.domain.Architecture.X86_64); - assertEquals(image.getDescription(), - "Lean/ubuntu.9-04.x86-64.img.manifest.xml"); - assertEquals(image.getProviderId(), "emi-CBEA100C"); - assertEquals(image.getLocation(), defaultLocation); - assertEquals(image.getName(), "9.04"); - assertEquals(image.getOsDescription(), - "Lean/ubuntu.9-04.x86-64.img.manifest.xml"); - assertEquals(image.getOsFamily(), OsFamily.UBUNTU); - assertEquals(image.getUserMetadata(), ImmutableMap. of( - "owner", "mashaobing1")); - assertEquals(image.getVersion(), ""); + // should skip test images + image = parser.apply(Iterables.get(result, 3)); + assertEquals(image, null); } private Set parseImages(InputStream is) { - DescribeImagesResponseHandler handler = injector - .getInstance(DescribeImagesResponseHandler.class); + DescribeImagesResponseHandler handler = injector.getInstance(DescribeImagesResponseHandler.class); addDefaultRegionToHandler(handler); Set result = factory.create(handler).parse(is); return result; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java index d6ff7a98d0..3c3d341805 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java @@ -64,14 +64,13 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { RegionAndName knownRegionAndName = new RegionAndName("region", "ami"); Image knownImage = createNiceMock(Image.class); - ConcurrentMap imageMap = new MapMaker() - .makeComputingMap(new Function() { - @Override - public Image apply(RegionAndName from) { - return from.equals(knownRegionAndName) ? knownImage : null; - } + ConcurrentMap imageMap = new MapMaker().makeComputingMap(new Function() { + @Override + public Image apply(RegionAndName from) { + return from.equals(knownRegionAndName) ? knownImage : null; + } - }); + }); @BeforeTest void setup() { @@ -84,56 +83,89 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { } @Override - protected EC2TemplateBuilderImpl createTemplateBuilder( - Provider> locations, - Provider> images, - Provider> sizes, Location defaultLocation, - Provider optionsProvider, - Provider templateBuilderProvider) { - return new EC2TemplateBuilderImpl(locations, images, sizes, - defaultLocation, optionsProvider, templateBuilderProvider, imageMap); + protected EC2TemplateBuilderImpl createTemplateBuilder(Provider> locations, + Provider> images, Provider> sizes, Location defaultLocation, + Provider optionsProvider, Provider templateBuilderProvider) { + return new EC2TemplateBuilderImpl(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider, imageMap); } @SuppressWarnings("unchecked") @Test public void testParseOnDemand() { - Location location = new LocationImpl(LocationScope.REGION, "region", - "region", null); + Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); - Provider> locations = Providers - .> of(ImmutableSet. of(location)); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet - . of(new SizeImpl("1", "1", "region/1", location, null, - ImmutableMap. of(), 1, 1, 1, - ImagePredicates.any()))); + Provider> locations = Providers.> of(ImmutableSet + . of(location)); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of(new SizeImpl("1", + "1", "region/1", location, null, ImmutableMap. of(), 1, 1, 1, ImagePredicates.any()))); - Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateOptions defaultOptions = createMock(TemplateOptions.class); knownImage = createMock(Image.class); - expect(defaultLocation.getId()).andReturn("region"); expect(optionsProvider.get()).andReturn(defaultOptions); - expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32); + + expect(knownImage.getId()).andReturn("region/ami"); + expect(knownImage.getLocation()).andReturn(location).atLeastOnce(); + expect(knownImage.getOsFamily()).andReturn(null); + expect(knownImage.getName()).andReturn(null); + expect(knownImage.getDescription()).andReturn(null); + expect(knownImage.getOsDescription()).andReturn(null); + expect(knownImage.getVersion()).andReturn(null); + expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce(); replay(knownImage); replay(defaultOptions); - replay(defaultLocation); replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, location, optionsProvider, + templateBuilderProvider); - assertEquals(template.imageId("ami").build().getImage(), knownImage); + assertEquals(template.imageId("region/ami").build().getImage(), knownImage); verify(knownImage); verify(defaultOptions); - verify(defaultLocation); + verify(optionsProvider); + verify(templateBuilderProvider); + } + + @SuppressWarnings("unchecked") + @Test + public void testParseOnDemandWithoutRegionEncodedIntoId() { + Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); + + Provider> locations = Providers.> of(ImmutableSet + . of(location)); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of(new SizeImpl("1", + "1", "region/1", location, null, ImmutableMap. of(), 1, 1, 1, ImagePredicates.any()))); + + Provider optionsProvider = createMock(Provider.class); + Provider templateBuilderProvider = createMock(Provider.class); + TemplateOptions defaultOptions = createMock(TemplateOptions.class); + knownImage = createMock(Image.class); + + expect(optionsProvider.get()).andReturn(defaultOptions); + + replay(knownImage); + replay(defaultOptions); + replay(optionsProvider); + replay(templateBuilderProvider); + + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, location, optionsProvider, + templateBuilderProvider); + try { + template.imageId("ami").build(); + assert false; + } catch (IllegalArgumentException e) { + + } + verify(knownImage); + verify(defaultOptions); verify(optionsProvider); verify(templateBuilderProvider); } @@ -141,18 +173,13 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { @SuppressWarnings("unchecked") @Test(expectedExceptions = NoSuchElementException.class) public void testParseOnDemandNotFound() { - Location location = new LocationImpl(LocationScope.REGION, "region", - "region", null); + Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); - Provider> locations = Providers - .> of(ImmutableSet. of(location)); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet - . of(new SizeImpl("1", "1", "region/1", location, null, - ImmutableMap. of(), 1, 1, 1, - ImagePredicates.any()))); + Provider> locations = Providers.> of(ImmutableSet + . of(location)); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of(new SizeImpl("1", + "1", "region/1", location, null, ImmutableMap. of(), 1, 1, 1, ImagePredicates.any()))); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); @@ -162,8 +189,7 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { expect(defaultLocation.getId()).andReturn("region"); expect(optionsProvider.get()).andReturn(defaultOptions); - expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32) - .atLeastOnce(); + expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce(); replay(knownImage); replay(defaultOptions); @@ -171,10 +197,10 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); - assertEquals(template.imageId("bad").build().getImage(), knownImage); + assertEquals(template.imageId("region/bad").build().getImage(), knownImage); verify(knownImage); verify(defaultOptions); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIAsyncClientTest.java index bd7fd27df4..b91e977e5a 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIAsyncClientTest.java @@ -51,16 +51,14 @@ import com.google.inject.TypeLiteral; public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { public void testCreateImage() throws SecurityException, NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, - String.class, String.class, Array.newInstance(CreateImageOptions.class, 0) - .getClass()); + Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, String.class, String.class, + Array.newInstance(CreateImageOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "name", "instanceId"); 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, - "Version=2010-06-15&Action=CreateImage&InstanceId=instanceId&Name=name", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=CreateImage&InstanceId=instanceId&Name=name", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertExceptionParserClassEquals(method, null); @@ -68,20 +66,18 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testCreateImageOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, - String.class, String.class, Array.newInstance(CreateImageOptions.class, 0) - .getClass()); - HttpRequest request = processor.createRequest(method, null, "name", "instanceId", - new CreateImageOptions().withDescription("description").noReboot()); + public void testCreateImageOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, String.class, String.class, + Array.newInstance(CreateImageOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, "name", "instanceId", new CreateImageOptions() + .withDescription("description").noReboot()); 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, - "Version=2010-06-15&Action=CreateImage&InstanceId=instanceId&Name=name&Description=description&NoReboot=true", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=CreateImage&InstanceId=instanceId&Name=name&Description=description&NoReboot=true", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); @@ -91,19 +87,19 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { } public void testDescribeImages() throws SecurityException, NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array - .newInstance(DescribeImagesOptions.class, 0).getClass()); + Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array.newInstance( + DescribeImagesOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, (String) null); 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, "Version=2010-06-15&Action=DescribeImages", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeImages", "application/x-www-form-urlencoded", + false); filter.filter(request); assertPayloadEquals( - request, - "Action=DescribeImages&Signature=qE4vexSFJqS0UWK%2BccV3s%2BP9woL3M5HI5bTBoM7s%2FLY%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&Version=2010-06-15&AWSAccessKeyId=identity", - "application/x-www-form-urlencoded", false); + request, + "Action=DescribeImages&Signature=qE4vexSFJqS0UWK%2BccV3s%2BP9woL3M5HI5bTBoM7s%2FLY%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&Version=2010-06-15&AWSAccessKeyId=identity", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeImagesResponseHandler.class); @@ -112,19 +108,18 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testDescribeImagesOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array - .newInstance(DescribeImagesOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, null, executableBy("me").ownedBy( - "fred", "nancy").imageIds("1", "2")); + public void testDescribeImagesOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array.newInstance( + DescribeImagesOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, executableBy("me").ownedBy("fred", "nancy").imageIds( + "1", "2")); 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, - "Version=2010-06-15&Action=DescribeImages&ExecutableBy=me&Owner.1=fred&Owner.2=nancy&ImageId.1=1&ImageId.2=2", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=DescribeImages&ExecutableBy=me&Owner.1=fred&Owner.2=nancy&ImageId.1=1&ImageId.2=2", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeImagesResponseHandler.class); @@ -134,14 +129,13 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { } public void testDeregisterImage() throws SecurityException, NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("deregisterImageInRegion", String.class, - String.class); + Method method = AMIAsyncClient.class.getMethod("deregisterImageInRegion", String.class, String.class); HttpRequest request = processor.createRequest(method, null, "imageId"); 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, "Version=2010-06-15&Action=DeregisterImage&ImageId=imageId", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -150,18 +144,15 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testRegisterImageFromManifest() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", - String.class, String.class, String.class, Array.newInstance( - RegisterImageOptions.class, 0).getClass()); + public void testRegisterImageFromManifest() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", String.class, String.class, + String.class, Array.newInstance(RegisterImageOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest"); 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, - "Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertExceptionParserClassEquals(method, null); @@ -169,20 +160,17 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testRegisterImageFromManifestOptions() throws SecurityException, - NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", - String.class, String.class, String.class, Array.newInstance( - RegisterImageOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest", - new RegisterImageOptions().withDescription("description")); + public void testRegisterImageFromManifestOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", String.class, String.class, + String.class, Array.newInstance(RegisterImageOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest", new RegisterImageOptions() + .withDescription("description")); 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, - "Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name&Description=description", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name&Description=description", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); @@ -191,19 +179,17 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testRegisterImageBackedByEBS() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", - String.class, String.class, String.class, Array.newInstance( - RegisterImageBackedByEbsOptions.class, 0).getClass()); + public void testRegisterImageBackedByEBS() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", String.class, + String.class, String.class, Array.newInstance(RegisterImageBackedByEbsOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "imageName", "snapshotId"); 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, - "Version=2010-06-15&Action=RegisterImage&RootDeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.DeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.Ebs.SnapshotId=snapshotId&Name=imageName", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=RegisterImage&RootDeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.DeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.Ebs.SnapshotId=snapshotId&Name=imageName", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertExceptionParserClassEquals(method, null); @@ -211,22 +197,19 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testRegisterImageBackedByEBSOptions() throws SecurityException, - NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", - String.class, String.class, String.class, Array.newInstance( - RegisterImageBackedByEbsOptions.class, 0).getClass()); + public void testRegisterImageBackedByEBSOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", String.class, + String.class, String.class, Array.newInstance(RegisterImageBackedByEbsOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "imageName", "snapshotId", - new RegisterImageBackedByEbsOptions().withDescription("description") - .addBlockDeviceFromSnapshot("/dev/device", null, "snapshot") - .addNewBlockDevice("/dev/newdevice", "newblock", 100)); + new RegisterImageBackedByEbsOptions().withDescription("description").addBlockDeviceFromSnapshot( + "/dev/device", null, "snapshot").addNewBlockDevice("/dev/newdevice", "newblock", 100)); 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, - "Version=2010-06-15&Action=RegisterImage&RootDeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.DeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.Ebs.SnapshotId=snapshotId&Name=imageName&Description=description&BlockDeviceMapping.1.Ebs.DeleteOnTermination=false&BlockDeviceMapping.1.DeviceName=%2Fdev%2Fdevice&BlockDeviceMapping.1.Ebs.SnapshotId=snapshot&BlockDeviceMapping.2.Ebs.DeleteOnTermination=false&BlockDeviceMapping.2.DeviceName=%2Fdev%2Fnewdevice&BlockDeviceMapping.2.VirtualName=newblock&BlockDeviceMapping.2.Ebs.VolumeSize=100", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=RegisterImage&RootDeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.DeviceName=%2Fdev%2Fsda1&BlockDeviceMapping.0.Ebs.SnapshotId=snapshotId&Name=imageName&Description=description&BlockDeviceMapping.1.Ebs.DeleteOnTermination=false&BlockDeviceMapping.1.DeviceName=%2Fdev%2Fdevice&BlockDeviceMapping.1.Ebs.SnapshotId=snapshot&BlockDeviceMapping.2.Ebs.DeleteOnTermination=false&BlockDeviceMapping.2.DeviceName=%2Fdev%2Fnewdevice&BlockDeviceMapping.2.VirtualName=newblock&BlockDeviceMapping.2.Ebs.VolumeSize=100", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); @@ -235,18 +218,15 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testGetProductCodesForImage() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("getProductCodesForImageInRegion", - String.class, String.class); + public void testGetProductCodesForImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("getProductCodesForImageInRegion", String.class, String.class); HttpRequest request = processor.createRequest(method, null, "imageId"); 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, - "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=productCodes&ImageId=imageId", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=productCodes&ImageId=imageId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ProductCodesHandler.class); @@ -255,18 +235,16 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testGetBlockDeviceMappingsForImage() throws SecurityException, - NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("getBlockDeviceMappingsForImageInRegion", - String.class, String.class); + public void testGetBlockDeviceMappingsForImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("getBlockDeviceMappingsForImageInRegion", String.class, + String.class); HttpRequest request = processor.createRequest(method, null, "imageId"); 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, - "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=blockDeviceMapping&ImageId=imageId", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=blockDeviceMapping&ImageId=imageId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, BlockDeviceMappingHandler.class); @@ -275,18 +253,15 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testGetLaunchPermissionForImage() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("getLaunchPermissionForImageInRegion", - String.class, String.class); + public void testGetLaunchPermissionForImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("getLaunchPermissionForImageInRegion", String.class, String.class); HttpRequest request = processor.createRequest(method, null, "imageId"); 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, - "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=launchPermission&ImageId=imageId", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=launchPermission&ImageId=imageId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, PermissionHandler.class); @@ -295,24 +270,23 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testAddLaunchPermissionsToImage() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("addLaunchPermissionsToImageInRegion", - String.class, Iterable.class, Iterable.class, String.class); - HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), - ImmutableList.of("all"), "imageId"); + public void testAddLaunchPermissionsToImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("addLaunchPermissionsToImageInRegion", String.class, + Iterable.class, Iterable.class, String.class); + HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList + .of("all"), "imageId"); 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, - "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=add&Attribute=launchPermission&ImageId=imageId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=add&Attribute=launchPermission&ImageId=imageId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", + "application/x-www-form-urlencoded", false); filter.filter(request); assertPayloadEquals( - request, - "Action=ModifyImageAttribute&Attribute=launchPermission&ImageId=imageId&OperationType=add&Signature=WZzNWOC1KHbuySvXEuLTiBA%2BVUfKpSBN2Lud6MrhlCQ%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&UserGroup.1=all&UserId.1=bob&UserId.2=sue&Version=2010-06-15&AWSAccessKeyId=identity", - "application/x-www-form-urlencoded", false); + request, + "Action=ModifyImageAttribute&Attribute=launchPermission&ImageId=imageId&OperationType=add&Signature=WZzNWOC1KHbuySvXEuLTiBA%2BVUfKpSBN2Lud6MrhlCQ%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&UserGroup.1=all&UserId.1=bob&UserId.2=sue&Version=2010-06-15&AWSAccessKeyId=identity", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -321,19 +295,18 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testRemoveLaunchPermissionsFromImage() throws SecurityException, - NoSuchMethodException, IOException { - Method method = AMIAsyncClient.class.getMethod("removeLaunchPermissionsFromImageInRegion", - String.class, Iterable.class, Iterable.class, String.class); - HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), - ImmutableList.of("all"), "imageId"); + public void testRemoveLaunchPermissionsFromImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("removeLaunchPermissionsFromImageInRegion", String.class, + Iterable.class, Iterable.class, String.class); + HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList + .of("all"), "imageId"); 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, - "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=remove&Attribute=launchPermission&ImageId=imageId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=remove&Attribute=launchPermission&ImageId=imageId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); @@ -341,18 +314,16 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testResetLaunchPermissionsOnImage() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("resetLaunchPermissionsOnImageInRegion", - String.class, String.class); + public void testResetLaunchPermissionsOnImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("resetLaunchPermissionsOnImageInRegion", String.class, + String.class); HttpRequest request = processor.createRequest(method, null, "imageId"); 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, - "Version=2010-06-15&Action=ResetImageAttribute&Attribute=launchPermission&ImageId=imageId", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=ResetImageAttribute&Attribute=launchPermission&ImageId=imageId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); @@ -360,19 +331,17 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testAddProductCodesToImage() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("addProductCodesToImageInRegion", - String.class, Iterable.class, String.class); - HttpRequest request = processor.createRequest(method, null, ImmutableList - .of("code1", "code2"), "imageId"); + public void testAddProductCodesToImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("addProductCodesToImageInRegion", String.class, Iterable.class, + String.class); + HttpRequest request = processor.createRequest(method, null, ImmutableList.of("code1", "code2"), "imageId"); 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, - "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=add&Attribute=productCodes&ImageId=imageId&ProductCode.1=code1&ProductCode.2=code2", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=add&Attribute=productCodes&ImageId=imageId&ProductCode.1=code1&ProductCode.2=code2", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -381,19 +350,17 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { checkFilters(request); } - public void testRemoveProductCodesFromImage() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AMIAsyncClient.class.getMethod("removeProductCodesFromImageInRegion", - String.class, Iterable.class, String.class); - HttpRequest request = processor.createRequest(method, null, ImmutableList - .of("code1", "code2"), "imageId"); + public void testRemoveProductCodesFromImage() throws SecurityException, NoSuchMethodException, IOException { + Method method = AMIAsyncClient.class.getMethod("removeProductCodesFromImageInRegion", String.class, + Iterable.class, String.class); + HttpRequest request = processor.createRequest(method, null, ImmutableList.of("code1", "code2"), "imageId"); 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, - "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=remove&Attribute=productCodes&ImageId=imageId&ProductCode.1=code1&ProductCode.2=code2", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=ModifyImageAttribute&OperationType=remove&Attribute=productCodes&ImageId=imageId&ProductCode.1=code1&ProductCode.2=code2", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionAsyncClientTest.java index 543b39dcca..55515daeef 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionAsyncClientTest.java @@ -45,19 +45,17 @@ import com.google.inject.TypeLiteral; */ @Test(groups = "unit", testName = "ec2.AvailabilityZoneAndRegionAsyncClientTest") public class AvailabilityZoneAndRegionAsyncClientTest extends - BaseEC2AsyncClientTest { + BaseEC2AsyncClientTest { - public void testDescribeAvailabilityZones() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod( - "describeAvailabilityZonesInRegion", String.class, Array.newInstance( - DescribeAvailabilityZonesOptions.class, 0).getClass()); + public void testDescribeAvailabilityZones() throws SecurityException, NoSuchMethodException, IOException { + Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeAvailabilityZonesInRegion", + String.class, Array.newInstance(DescribeAvailabilityZonesOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, Region.US_WEST_1); assertRequestLineEquals(request, "POST https://ec2.us-west-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-west-1.amazonaws.com\n"); assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeAvailabilityZones", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeAvailabilityZonesResponseHandler.class); @@ -66,20 +64,17 @@ public class AvailabilityZoneAndRegionAsyncClientTest extends checkFilters(request); } - public void testDescribeAvailabilityZonesOptions() throws SecurityException, - NoSuchMethodException, IOException { - Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod( - "describeAvailabilityZonesInRegion", String.class, Array.newInstance( - DescribeAvailabilityZonesOptions.class, 0).getClass()); + public void testDescribeAvailabilityZonesOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeAvailabilityZonesInRegion", + String.class, Array.newInstance(DescribeAvailabilityZonesOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, Region.US_EAST_1, availabilityZones( - AvailabilityZone.US_EAST_1A, AvailabilityZone.US_EAST_1B)); + AvailabilityZone.US_EAST_1A, AvailabilityZone.US_EAST_1B)); 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, - "Version=2010-06-15&Action=DescribeAvailabilityZones&ZoneName.1=us-east-1a&ZoneName.2=us-east-1b", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=DescribeAvailabilityZones&ZoneName.1=us-east-1a&ZoneName.2=us-east-1b", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeAvailabilityZonesResponseHandler.class); @@ -89,14 +84,14 @@ public class AvailabilityZoneAndRegionAsyncClientTest extends } public void testDescribeRegions() throws SecurityException, NoSuchMethodException, IOException { - Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array - .newInstance(DescribeRegionsOptions.class, 0).getClass()); + Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array.newInstance( + DescribeRegionsOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method); 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, "Version=2010-06-15&Action=DescribeRegions", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeRegions", "application/x-www-form-urlencoded", + false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeRegionsResponseHandler.class); @@ -105,19 +100,16 @@ public class AvailabilityZoneAndRegionAsyncClientTest extends checkFilters(request); } - public void testDescribeRegionsOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array - .newInstance(DescribeRegionsOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, regions(Region.US_EAST_1, - Region.US_WEST_1)); + public void testDescribeRegionsOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array.newInstance( + DescribeRegionsOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, regions(Region.US_EAST_1, Region.US_WEST_1)); 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, - "Version=2010-06-15&Action=DescribeRegions&RegionName.1=us-east-1&RegionName.2=us-west-1", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=DescribeRegions&RegionName.1=us-east-1&RegionName.2=us-west-1", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeRegionsResponseHandler.class); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/BaseEC2AsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/BaseEC2AsyncClientTest.java index 94071dec03..8b22a2c328 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/BaseEC2AsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/BaseEC2AsyncClientTest.java @@ -58,21 +58,20 @@ public abstract class BaseEC2AsyncClientTest extends RestClientTest { @Override protected String provideTimeStamp(final DateService dateService, - @Named(Constants.PROPERTY_SESSION_INTERVAL) final int expiration) { + @Named(Constants.PROPERTY_SESSION_INTERVAL) final int expiration) { return "2009-11-08T15:54:08.897Z"; } @Override protected Map provideRegions(Injector client) { - return ImmutableMap. of(Region.EU_WEST_1, URI - .create("https://ec2.eu-west-1.amazonaws.com"), Region.US_EAST_1, URI - .create("https://ec2.us-east-1.amazonaws.com"), Region.US_WEST_1, URI - .create("https://ec2.us-west-1.amazonaws.com")); + return ImmutableMap. of(Region.EU_WEST_1, URI.create("https://ec2.eu-west-1.amazonaws.com"), + Region.US_EAST_1, URI.create("https://ec2.us-east-1.amazonaws.com"), Region.US_WEST_1, URI + .create("https://ec2.us-west-1.amazonaws.com")); } @Override protected Map provideAvailabilityZoneToRegions(EC2Client client, - @org.jclouds.aws.Region Map regions) { + @org.jclouds.aws.Region Map regions) { return ImmutableMap. of(AvailabilityZone.US_EAST_1A, Region.US_EAST_1); } } @@ -103,8 +102,7 @@ public abstract class BaseEC2AsyncClientTest extends RestClientTest { @Override public ContextSpec createContextSpec() { - return new RestContextFactory().createContextSpec("ec2", "identity", "credential", - new Properties()); + return new RestContextFactory().createContextSpec("ec2", "identity", "credential", new Properties()); } } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreAsyncClientTest.java index 81cdb0045c..93dbf62300 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreAsyncClientTest.java @@ -51,19 +51,35 @@ import com.google.inject.TypeLiteral; * @author Adrian Cole */ @Test(groups = "unit", testName = "ec2.ElasticBlockStoreAsyncClientTest") -public class ElasticBlockStoreAsyncClientTest extends - BaseEC2AsyncClientTest { +public class ElasticBlockStoreAsyncClientTest extends BaseEC2AsyncClientTest { public void testCreateVolume() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "createVolumeInAvailabilityZone", String.class, int.class); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("createVolumeInAvailabilityZone", String.class, + int.class); HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 20); + 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, "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&Size=20", + "application/x-www-form-urlencoded", false); + + assertResponseParserClassEquals(method, request, ParseSax.class); + assertSaxResponseParserClassEquals(method, CreateVolumeResponseHandler.class); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateVolumeFromSnapShot() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("createVolumeFromSnapshotInAvailabilityZone", + String.class, String.class); + HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, "snapshotId"); + 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, - "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&Size=20", - "application/x-www-form-urlencoded", false); + "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, CreateVolumeResponseHandler.class); @@ -72,40 +88,16 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testCreateVolumeFromSnapShot() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "createVolumeFromSnapshotInAvailabilityZone", String.class, String.class); - HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, - "snapshotId"); + public void testCreateVolumeFromSnapShotWithSize() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("createVolumeFromSnapshotInAvailabilityZone", + String.class, int.class, String.class); + HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 15, "snapshotId"); 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, - "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId", - "application/x-www-form-urlencoded", false); - - assertResponseParserClassEquals(method, request, ParseSax.class); - assertSaxResponseParserClassEquals(method, CreateVolumeResponseHandler.class); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testCreateVolumeFromSnapShotWithSize() throws SecurityException, - NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "createVolumeFromSnapshotInAvailabilityZone", String.class, int.class, String.class); - HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 15, - "snapshotId"); - - 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, - "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId&Size=15", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId&Size=15", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, CreateVolumeResponseHandler.class); @@ -115,14 +107,13 @@ public class ElasticBlockStoreAsyncClientTest extends } public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("deleteVolumeInRegion", - String.class, String.class); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("deleteVolumeInRegion", String.class, String.class); HttpRequest request = processor.createRequest(method, null, "id"); 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, "Version=2010-06-15&Action=DeleteVolume&VolumeId=id", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -132,14 +123,14 @@ public class ElasticBlockStoreAsyncClientTest extends } public void testDescribeVolumes() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", - String.class, Array.newInstance(String.class, 0).getClass()); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", String.class, Array + .newInstance(String.class, 0).getClass()); HttpRequest request = processor.createRequest(method, (String) null); 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, "Version=2010-06-15&Action=DescribeVolumes", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeVolumes", "application/x-www-form-urlencoded", + false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeVolumesResponseHandler.class); @@ -148,17 +139,15 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testDescribeVolumesArgs() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", - String.class, Array.newInstance(String.class, 0).getClass()); + public void testDescribeVolumesArgs() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", String.class, Array + .newInstance(String.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "1", "2"); 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, - "Version=2010-06-15&Action=DescribeVolumes&VolumeId.1=1&VolumeId.2=2", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeVolumes&VolumeId.1=1&VolumeId.2=2", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeVolumesResponseHandler.class); @@ -168,16 +157,15 @@ public class ElasticBlockStoreAsyncClientTest extends } public void testAttachVolume() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("attachVolumeInRegion", - String.class, String.class, String.class, String.class); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("attachVolumeInRegion", String.class, String.class, + String.class, String.class); HttpRequest request = processor.createRequest(method, null, "id", "instanceId", "/device"); 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, - "Version=2010-06-15&Action=AttachVolume&InstanceId=instanceId&VolumeId=id&Device=%2Fdevice", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=AttachVolume&InstanceId=instanceId&VolumeId=id&Device=%2Fdevice", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, AttachmentHandler.class); @@ -187,16 +175,14 @@ public class ElasticBlockStoreAsyncClientTest extends } public void testDetachVolume() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", - String.class, String.class, boolean.class, Array.newInstance( - DetachVolumeOptions.class, 0).getClass()); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", String.class, String.class, + boolean.class, Array.newInstance(DetachVolumeOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "id", false); 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, - "Version=2010-06-15&Action=DetachVolume&Force=false&VolumeId=id", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DetachVolume&Force=false&VolumeId=id", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -205,20 +191,17 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testDetachVolumeOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", - String.class, String.class, boolean.class, Array.newInstance( - DetachVolumeOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, null, "id", true, fromInstance( - "instanceId").fromDevice("/device")); + public void testDetachVolumeOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", String.class, String.class, + boolean.class, Array.newInstance(DetachVolumeOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, "id", true, fromInstance("instanceId").fromDevice( + "/device")); 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, - "Version=2010-06-15&Action=DetachVolume&Force=true&VolumeId=id&InstanceId=instanceId&Device=%2Fdevice", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=DetachVolume&Force=true&VolumeId=id&InstanceId=instanceId&Device=%2Fdevice", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -228,15 +211,14 @@ public class ElasticBlockStoreAsyncClientTest extends } public void testCreateSnapshot() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", - String.class, String.class, Array.newInstance(CreateSnapshotOptions.class, 0) - .getClass()); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", String.class, + String.class, Array.newInstance(CreateSnapshotOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "volumeId"); 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, "Version=2010-06-15&Action=CreateSnapshot&VolumeId=volumeId", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, SnapshotHandler.class); @@ -245,20 +227,17 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testCreateSnapshotOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", - String.class, String.class, Array.newInstance(CreateSnapshotOptions.class, 0) - .getClass()); - HttpRequest request = processor.createRequest(method, null, "volumeId", - CreateSnapshotOptions.Builder.withDescription("description")); + public void testCreateSnapshotOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", String.class, + String.class, Array.newInstance(CreateSnapshotOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, "volumeId", CreateSnapshotOptions.Builder + .withDescription("description")); 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, - "Version=2010-06-15&Action=CreateSnapshot&VolumeId=volumeId&Description=description", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=CreateSnapshot&VolumeId=volumeId&Description=description", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, SnapshotHandler.class); @@ -268,14 +247,14 @@ public class ElasticBlockStoreAsyncClientTest extends } public void testDescribeSnapshots() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", - String.class, Array.newInstance(DescribeSnapshotsOptions.class, 0).getClass()); + Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", String.class, Array + .newInstance(DescribeSnapshotsOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, (String) null); 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, "Version=2010-06-15&Action=DescribeSnapshots", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeSnapshots", "application/x-www-form-urlencoded", + false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeSnapshotsResponseHandler.class); @@ -284,19 +263,18 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testDescribeSnapshotsArgs() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", - String.class, Array.newInstance(DescribeSnapshotsOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, null, ownedBy("o1", "o2").restorableBy( - "r1", "r2").snapshotIds("s1", "s2")); + public void testDescribeSnapshotsArgs() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", String.class, Array + .newInstance(DescribeSnapshotsOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, ownedBy("o1", "o2").restorableBy("r1", "r2") + .snapshotIds("s1", "s2")); 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, - "Version=2010-06-15&Action=DescribeSnapshots&Owner.1=o1&Owner.2=o2&RestorableBy.1=r1&RestorableBy.2=r2&SnapshotId.1=s1&SnapshotId.2=s2", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=DescribeSnapshots&Owner.1=o1&Owner.2=o2&RestorableBy.1=r1&RestorableBy.2=r2&SnapshotId.1=s1&SnapshotId.2=s2", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeSnapshotsResponseHandler.class); @@ -305,18 +283,17 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testGetCreateVolumePermissionForSnapshot() throws SecurityException, - NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "getCreateVolumePermissionForSnapshotInRegion", String.class, String.class); + public void testGetCreateVolumePermissionForSnapshot() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("getCreateVolumePermissionForSnapshotInRegion", + String.class, String.class); HttpRequest request = processor.createRequest(method, null, "snapshotId"); 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, - "Version=2010-06-15&Action=DescribeSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=DescribeSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, PermissionHandler.class); @@ -325,20 +302,18 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testAddCreateVolumePermissionsToSnapshot() throws SecurityException, - NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "addCreateVolumePermissionsToSnapshotInRegion", String.class, Iterable.class, - Iterable.class, String.class); - HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), - ImmutableList.of("all"), "snapshotId"); + public void testAddCreateVolumePermissionsToSnapshot() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("addCreateVolumePermissionsToSnapshotInRegion", + String.class, Iterable.class, Iterable.class, String.class); + HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList + .of("all"), "snapshotId"); 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, - "Version=2010-06-15&Action=ModifySnapshotAttribute&OperationType=add&Attribute=createVolumePermission&SnapshotId=snapshotId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=ModifySnapshotAttribute&OperationType=add&Attribute=createVolumePermission&SnapshotId=snapshotId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -347,20 +322,19 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testRemoveCreateVolumePermissionsFromSnapshot() throws SecurityException, - NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "removeCreateVolumePermissionsFromSnapshotInRegion", String.class, Iterable.class, - Iterable.class, String.class); - HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), - ImmutableList.of("all"), "snapshotId"); + public void testRemoveCreateVolumePermissionsFromSnapshot() throws SecurityException, NoSuchMethodException, + IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("removeCreateVolumePermissionsFromSnapshotInRegion", + String.class, Iterable.class, Iterable.class, String.class); + HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList + .of("all"), "snapshotId"); 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, - "Version=2010-06-15&Action=ModifySnapshotAttribute&OperationType=remove&Attribute=createVolumePermission&SnapshotId=snapshotId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", - "application/x-www-form-urlencoded", false); + request, + "Version=2010-06-15&Action=ModifySnapshotAttribute&OperationType=remove&Attribute=createVolumePermission&SnapshotId=snapshotId&UserGroup.1=all&UserId.1=bob&UserId.2=sue", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); @@ -368,18 +342,17 @@ public class ElasticBlockStoreAsyncClientTest extends checkFilters(request); } - public void testResetCreateVolumePermissionsOnSnapshot() throws SecurityException, - NoSuchMethodException, IOException { - Method method = ElasticBlockStoreAsyncClient.class.getMethod( - "resetCreateVolumePermissionsOnSnapshotInRegion", String.class, String.class); + public void testResetCreateVolumePermissionsOnSnapshot() throws SecurityException, NoSuchMethodException, + IOException { + Method method = ElasticBlockStoreAsyncClient.class.getMethod("resetCreateVolumePermissionsOnSnapshotInRegion", + String.class, String.class); HttpRequest request = processor.createRequest(method, null, "snapshotId"); 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, - "Version=2010-06-15&Action=ResetSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2010-06-15&Action=ResetSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressAsyncClientTest.java index 83a38be889..287ea63bd3 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressAsyncClientTest.java @@ -38,20 +38,17 @@ import com.google.inject.TypeLiteral; * @author Adrian Cole */ @Test(groups = "unit", testName = "ec2.ElasticIPAddressAsyncClientTest") -public class ElasticIPAddressAsyncClientTest extends - BaseEC2AsyncClientTest { +public class ElasticIPAddressAsyncClientTest extends BaseEC2AsyncClientTest { - public void testDisassociateAddress() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ElasticIPAddressAsyncClient.class.getMethod("disassociateAddressInRegion", - String.class, String.class); + public void testDisassociateAddress() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticIPAddressAsyncClient.class.getMethod("disassociateAddressInRegion", String.class, + String.class); HttpRequest request = processor.createRequest(method, null, "127.0.0.1"); 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, - "Version=2010-06-15&Action=DisassociateAddress&PublicIp=127.0.0.1", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DisassociateAddress&PublicIp=127.0.0.1", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -61,15 +58,14 @@ public class ElasticIPAddressAsyncClientTest extends } public void testAssociateAddress() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticIPAddressAsyncClient.class.getMethod("associateAddressInRegion", - String.class, String.class, String.class); + Method method = ElasticIPAddressAsyncClient.class.getMethod("associateAddressInRegion", String.class, + String.class, String.class); HttpRequest request = processor.createRequest(method, null, "127.0.0.1", "me"); 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, - "Version=2010-06-15&Action=AssociateAddress&InstanceId=me&PublicIp=127.0.0.1", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=AssociateAddress&InstanceId=me&PublicIp=127.0.0.1", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -79,14 +75,13 @@ public class ElasticIPAddressAsyncClientTest extends } public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticIPAddressAsyncClient.class.getMethod("releaseAddressInRegion", - String.class, String.class); + Method method = ElasticIPAddressAsyncClient.class.getMethod("releaseAddressInRegion", String.class, String.class); HttpRequest request = processor.createRequest(method, null, "127.0.0.1"); 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, "Version=2010-06-15&Action=ReleaseAddress&PublicIp=127.0.0.1", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -96,15 +91,14 @@ public class ElasticIPAddressAsyncClientTest extends } public void testDescribeAddresses() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticIPAddressAsyncClient.class.getMethod("describeAddressesInRegion", - String.class, Array.newInstance(String.class, 0).getClass()); + Method method = ElasticIPAddressAsyncClient.class.getMethod("describeAddressesInRegion", String.class, Array + .newInstance(String.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "127.0.0.1"); 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, - "Version=2010-06-15&Action=DescribeAddresses&PublicIp.1=127.0.0.1", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeAddresses&PublicIp.1=127.0.0.1", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeAddressesResponseHandler.class); @@ -114,14 +108,13 @@ public class ElasticIPAddressAsyncClientTest extends } public void testAllocateAddress() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticIPAddressAsyncClient.class.getMethod("allocateAddressInRegion", - String.class); + Method method = ElasticIPAddressAsyncClient.class.getMethod("allocateAddressInRegion", String.class); HttpRequest request = processor.createRequest(method, (String) null); 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, "Version=2010-06-15&Action=AllocateAddress", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=AllocateAddress", "application/x-www-form-urlencoded", + false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, AllocateAddressResponseHandler.class); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceAsyncClientTest.java index 1e5b2cd639..3b8b1889b9 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceAsyncClientTest.java @@ -54,14 +54,14 @@ import com.google.inject.TypeLiteral; @Test(groups = "unit", testName = "ec2.InstanceAsyncClientTest") public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest { public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException { - Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", - String.class, Array.newInstance(String.class, 0).getClass()); + Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", String.class, Array.newInstance( + String.class, 0).getClass()); HttpRequest request = processor.createRequest(method, (String) null); 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, "Version=2010-06-15&Action=DescribeInstances", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeInstances", "application/x-www-form-urlencoded", + false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class); @@ -70,17 +70,15 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest { public void testDeleteKeyPair() throws SecurityException, NoSuchMethodException, IOException { - Method method = KeyPairAsyncClient.class.getMethod("deleteKeyPairInRegion", String.class, - String.class); + Method method = KeyPairAsyncClient.class.getMethod("deleteKeyPairInRegion", String.class, String.class); HttpRequest request = processor.createRequest(method, null, "mykey"); 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, "Version=2010-06-15&Action=DeleteKeyPair&KeyName=mykey", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -57,14 +56,14 @@ public class KeyPairAsyncClientTest extends BaseEC2AsyncClientTest { - public void testUnmonitorInstances() throws SecurityException, NoSuchMethodException, - IOException { - Method method = MonitoringAsyncClient.class.getMethod("unmonitorInstancesInRegion", - String.class, String.class, Array.newInstance(String.class, 0).getClass()); + public void testUnmonitorInstances() throws SecurityException, NoSuchMethodException, IOException { + Method method = MonitoringAsyncClient.class.getMethod("unmonitorInstancesInRegion", String.class, String.class, + Array.newInstance(String.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "instance1", "instance2"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); @@ -57,16 +56,15 @@ public class MonitoringAsyncClientTest extends BaseEC2AsyncClientTest { - public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, - IOException { - Method method = SecurityGroupAsyncClient.class.getMethod("deleteSecurityGroupInRegion", - String.class, String.class); + public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, IOException { + Method method = SecurityGroupAsyncClient.class.getMethod("deleteSecurityGroupInRegion", String.class, + String.class); HttpRequest request = processor.createRequest(method, null, "name"); 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, "Version=2010-06-15&Action=DeleteSecurityGroup&GroupName=name", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -60,18 +59,16 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest expected = ImmutableSet. of( - new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1A, "available", Region.US_EAST_1, - ImmutableSet. of()), new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1B, - "available", Region.US_EAST_1, ImmutableSet. of()), + new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1A, "available", Region.US_EAST_1, ImmutableSet. of()), + new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1B, "available", Region.US_EAST_1, ImmutableSet + . of()), - new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1C, "available", Region.US_EAST_1, - ImmutableSet. of("our service is awesome")), + new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1C, "available", Region.US_EAST_1, ImmutableSet + . of("our service is awesome")), - new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1D, "downlikeaclown", Region.US_EAST_1, - ImmutableSet. of())); + new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1D, "downlikeaclown", Region.US_EAST_1, ImmutableSet + . of())); Set result = factory.create( - injector.getInstance(DescribeAvailabilityZonesResponseHandler.class)).parse(is); + injector.getInstance(DescribeAvailabilityZonesResponseHandler.class)).parse(is); assertEquals(result, expected); } diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/BaseS3AsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/BaseS3AsyncClientTest.java index 456cc6f9fe..04471e6bae 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/BaseS3AsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/BaseS3AsyncClientTest.java @@ -39,7 +39,6 @@ public abstract class BaseS3AsyncClientTest extends RestClientTest createContextSpec() { - return new RestContextFactory().createContextSpec("s3", "identity", "credential", - new Properties()); + return new RestContextFactory().createContextSpec("s3", "identity", "credential", new Properties()); } - } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/S3AsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/S3AsyncClientTest.java index 01c52ae074..89351f4f3b 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/S3AsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/S3AsyncClientTest.java @@ -81,8 +81,8 @@ import com.google.inject.Module; public class S3AsyncClientTest extends BaseS3AsyncClientTest { public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, - String.class, Array.newInstance(PutBucketOptions.class, 0).getClass()); + Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array.newInstance( + PutBucketOptions.class, 0).getClass()); for (String region : Region.ALL_S3) { processor.createRequest(method, region, "bucket-name"); } @@ -100,8 +100,8 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/?location HTTP/1.1"); assertNonPayloadHeadersEqual( - request, - "Authorization: AWS identity:2fFTeYJTDwiJmaAkKj732RjNbOg=\nDate: 2009-11-08T15:54:08.897Z\nHost: bucket.s3.amazonaws.com\n"); + request, + "Authorization: AWS identity:2fFTeYJTDwiJmaAkKj732RjNbOg=\nDate: 2009-11-08T15:54:08.897Z\nHost: bucket.s3.amazonaws.com\n"); assertPayloadEquals(request, null, null, false); assertResponseParserClassEquals(method, request, ParseSax.class); @@ -115,8 +115,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { Method method = S3AsyncClient.class.getMethod("getBucketPayer", String.class); HttpRequest request = processor.createRequest(method, "bucket"); - assertRequestLineEquals(request, - "GET https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1"); + assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertPayloadEquals(request, null, null, false); @@ -127,18 +126,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testSetBucketPayerOwner() throws SecurityException, NoSuchMethodException, - IOException { + public void testSetBucketPayerOwner() throws SecurityException, NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("setBucketPayer", String.class, Payer.class); HttpRequest request = processor.createRequest(method, "bucket", Payer.BUCKET_OWNER); - assertRequestLineEquals(request, - "PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1"); + assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertPayloadEquals( - request, - "BucketOwner", - "text/xml", false); + request, + "BucketOwner", + "text/xml", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -147,18 +144,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testSetBucketPayerRequester() throws SecurityException, NoSuchMethodException, - IOException { + public void testSetBucketPayerRequester() throws SecurityException, NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("setBucketPayer", String.class, Payer.class); HttpRequest request = processor.createRequest(method, "bucket", Payer.REQUESTER); - assertRequestLineEquals(request, - "PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1"); + assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertPayloadEquals( - request, - "Requester", - "text/xml", false); + request, + "Requester", + "text/xml", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -169,7 +164,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { public void testListBucket() throws SecurityException, NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("listBucket", String.class, Array.newInstance( - ListBucketOptions.class, 0).getClass()); + ListBucketOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "bucket"); assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/ HTTP/1.1"); @@ -199,28 +194,24 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } @Test(expectedExceptions = IllegalArgumentException.class) - public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, - SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class - .getMethod("copyObject", String.class, String.class, String.class, String.class, - Array.newInstance(CopyObjectOptions.class, 0).getClass()); - processor.createRequest(method, "sourceBucket", "sourceObject", "destinationBucket", - "destinationObject"); + public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, SecurityException, + IllegalArgumentException, NoSuchMethodException, IOException { + Method method = S3AsyncClient.class.getMethod("copyObject", String.class, String.class, String.class, + String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass()); + processor.createRequest(method, "sourceBucket", "sourceObject", "destinationBucket", "destinationObject"); } - public void testCopyObject() throws ArrayIndexOutOfBoundsException, SecurityException, - IllegalArgumentException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class - .getMethod("copyObject", String.class, String.class, String.class, String.class, - Array.newInstance(CopyObjectOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, "sourceBucket", "sourceObject", - "destinationbucket", "destinationObject"); + public void testCopyObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, + NoSuchMethodException, IOException { + Method method = S3AsyncClient.class.getMethod("copyObject", String.class, String.class, String.class, + String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, "sourceBucket", "sourceObject", "destinationbucket", + "destinationObject"); - assertRequestLineEquals(request, - "PUT https://destinationbucket.s3.amazonaws.com/destinationObject HTTP/1.1"); + assertRequestLineEquals(request, "PUT https://destinationbucket.s3.amazonaws.com/destinationObject HTTP/1.1"); assertNonPayloadHeadersEqual(request, - "Host: destinationbucket.s3.amazonaws.com\nx-amz-copy-source: /sourceBucket/sourceObject\n"); + "Host: destinationbucket.s3.amazonaws.com\nx-amz-copy-source: /sourceBucket/sourceObject\n"); assertPayloadEquals(request, null, null, false); assertResponseParserClassEquals(method, request, ParseSax.class); @@ -230,8 +221,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testDeleteBucketIfEmpty() throws SecurityException, NoSuchMethodException, - IOException { + public void testDeleteBucketIfEmpty() throws SecurityException, NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("deleteBucketIfEmpty", String.class); HttpRequest request = processor.createRequest(method, "bucket"); @@ -277,10 +267,10 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testGetObject() throws ArrayIndexOutOfBoundsException, SecurityException, - IllegalArgumentException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("getObject", String.class, String.class, Array - .newInstance(GetOptions.class, 0).getClass()); + public void testGetObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, + NoSuchMethodException, IOException { + Method method = S3AsyncClient.class.getMethod("getObject", String.class, String.class, Array.newInstance( + GetOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "bucket", "object"); assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/object HTTP/1.1"); @@ -363,17 +353,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } public void testPutBucketACL() throws SecurityException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("putBucketACL", String.class, - AccessControlList.class); - HttpRequest request = processor.createRequest(method, "bucket", AccessControlList - .fromCannedAccessPolicy(CannedAccessPolicy.PRIVATE, "1234")); + Method method = S3AsyncClient.class.getMethod("putBucketACL", String.class, AccessControlList.class); + HttpRequest request = processor.createRequest(method, "bucket", AccessControlList.fromCannedAccessPolicy( + CannedAccessPolicy.PRIVATE, "1234")); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?acl HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertPayloadEquals( - request, - "12341234FULL_CONTROL", - "text/xml", false); + request, + "12341234FULL_CONTROL", + "text/xml", false); assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); assertSaxResponseParserClassEquals(method, null); @@ -383,9 +372,9 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } public void testPutBucketDefault() throws ArrayIndexOutOfBoundsException, SecurityException, - IllegalArgumentException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, - String.class, Array.newInstance(PutBucketOptions.class, 0).getClass()); + IllegalArgumentException, NoSuchMethodException, IOException { + Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array.newInstance( + PutBucketOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, (String) null, "bucket"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/ HTTP/1.1"); @@ -399,18 +388,17 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testPutBucketEu() throws ArrayIndexOutOfBoundsException, SecurityException, - IllegalArgumentException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, - String.class, Array.newInstance(PutBucketOptions.class, 0).getClass()); + public void testPutBucketEu() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, + NoSuchMethodException, IOException { + Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array.newInstance( + PutBucketOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "EU", "bucket"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); - assertPayloadEquals( - request, - "EU", - "text/xml", false); + assertPayloadEquals(request, + "EU", + "text/xml", false); assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); assertSaxResponseParserClassEquals(method, null); @@ -419,13 +407,13 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, - IllegalArgumentException, NoSuchMethodException, IOException { + public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, + NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("putObject", String.class, S3Object.class, - PutObjectOptions[].class); + Method method = S3AsyncClient.class + .getMethod("putObject", String.class, S3Object.class, PutObjectOptions[].class); HttpRequest request = processor.createRequest(method, "bucket", blobToS3Object - .apply(BindBlobToMultipartFormTest.TEST_BLOB)); + .apply(BindBlobToMultipartFormTest.TEST_BLOB)); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/hello HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); @@ -439,17 +427,17 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } public void testPutObjectACL() throws SecurityException, NoSuchMethodException, IOException { - Method method = S3AsyncClient.class.getMethod("putObjectACL", String.class, String.class, - AccessControlList.class); - HttpRequest request = processor.createRequest(method, "bucket", "key", AccessControlList - .fromCannedAccessPolicy(CannedAccessPolicy.PRIVATE, "1234")); + Method method = S3AsyncClient.class + .getMethod("putObjectACL", String.class, String.class, AccessControlList.class); + HttpRequest request = processor.createRequest(method, "bucket", "key", AccessControlList.fromCannedAccessPolicy( + CannedAccessPolicy.PRIVATE, "1234")); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/key?acl HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertPayloadEquals( - request, - "12341234FULL_CONTROL", - "text/xml", false); + request, + "12341234FULL_CONTROL", + "text/xml", false); assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); assertSaxResponseParserClassEquals(method, null); @@ -473,16 +461,14 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testDisableBucketLogging() throws SecurityException, NoSuchMethodException, - IOException { + public void testDisableBucketLogging() throws SecurityException, NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("disableBucketLogging", String.class); HttpRequest request = processor.createRequest(method, "bucket"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?logging HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); - assertPayloadEquals(request, - "", - "text/xml", false); + assertPayloadEquals(request, "", + "text/xml", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -491,18 +477,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { checkFilters(request); } - public void testEnableBucketLoggingOwner() throws SecurityException, NoSuchMethodException, - IOException { - Method method = S3AsyncClient.class.getMethod("enableBucketLogging", String.class, - BucketLogging.class); - HttpRequest request = processor.createRequest(method, "bucket", new BucketLogging("mylogs", - "access_log-", ImmutableSet. of(new Grant(new EmailAddressGrantee( - "adrian@jclouds.org"), Permission.FULL_CONTROL)))); + public void testEnableBucketLoggingOwner() throws SecurityException, NoSuchMethodException, IOException { + Method method = S3AsyncClient.class.getMethod("enableBucketLogging", String.class, BucketLogging.class); + HttpRequest request = processor + .createRequest(method, "bucket", new BucketLogging("mylogs", "access_log-", ImmutableSet + . of(new Grant(new EmailAddressGrantee("adrian@jclouds.org"), Permission.FULL_CONTROL)))); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?logging HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream( - "/s3/bucket_logging.xml")), "text/xml", false); + assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream("/s3/bucket_logging.xml")), + "text/xml", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); diff --git a/aws/core/src/test/java/org/jclouds/aws/sqs/SQSAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/sqs/SQSAsyncClientTest.java index b75e1dbb9e..b53ebc8a7e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/sqs/SQSAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/sqs/SQSAsyncClientTest.java @@ -69,21 +69,19 @@ public class SQSAsyncClientTest extends RestClientTest { @Override protected String provideTimeStamp(final DateService dateService, - @Named(Constants.PROPERTY_SESSION_INTERVAL) int expiration) { + @Named(Constants.PROPERTY_SESSION_INTERVAL) int expiration) { return "2009-11-08T15:54:08.897Z"; } } - public void testListQueuesInRegion() throws SecurityException, NoSuchMethodException, - IOException { - Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array - .newInstance(ListQueuesOptions.class, 0).getClass()); + public void testListQueuesInRegion() throws SecurityException, NoSuchMethodException, IOException { + Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array.newInstance( + ListQueuesOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, (String) null); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); - assertPayloadEquals(request, "Version=2009-02-01&Action=ListQueues", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, "Version=2009-02-01&Action=ListQueues", "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, RegexListQueuesResponseHandler.class); assertSaxResponseParserClassEquals(method, null); @@ -92,17 +90,15 @@ public class SQSAsyncClientTest extends RestClientTest { checkFilters(request); } - public void testListQueuesInRegionOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array - .newInstance(ListQueuesOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, null, ListQueuesOptions.Builder - .queuePrefix("prefix")); + public void testListQueuesInRegionOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array.newInstance( + ListQueuesOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, ListQueuesOptions.Builder.queuePrefix("prefix")); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, "Version=2009-02-01&Action=ListQueues&QueueNamePrefix=prefix", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, RegexListQueuesResponseHandler.class); assertSaxResponseParserClassEquals(method, null); @@ -111,16 +107,15 @@ public class SQSAsyncClientTest extends RestClientTest { checkFilters(request); } - public void testCreateQueueInRegion() throws SecurityException, NoSuchMethodException, - IOException { - Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, - String.class, Array.newInstance(CreateQueueOptions.class, 0).getClass()); + public void testCreateQueueInRegion() throws SecurityException, NoSuchMethodException, IOException { + Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, String.class, Array + .newInstance(CreateQueueOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "queueName"); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, "Version=2009-02-01&Action=CreateQueue&QueueName=queueName", - "application/x-www-form-urlencoded", false); + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, RegexQueueHandler.class); assertSaxResponseParserClassEquals(method, null); @@ -129,19 +124,17 @@ public class SQSAsyncClientTest extends RestClientTest { checkFilters(request); } - public void testCreateQueueInRegionOptions() throws SecurityException, NoSuchMethodException, - IOException { - Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, - String.class, Array.newInstance(CreateQueueOptions.class, 0).getClass()); - HttpRequest request = processor.createRequest(method, null, "queueName", - CreateQueueOptions.Builder.defaultVisibilityTimeout(45)); + public void testCreateQueueInRegionOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, String.class, Array + .newInstance(CreateQueueOptions.class, 0).getClass()); + HttpRequest request = processor.createRequest(method, null, "queueName", CreateQueueOptions.Builder + .defaultVisibilityTimeout(45)); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); - assertPayloadEquals( - request, - "Version=2009-02-01&Action=CreateQueue&QueueName=queueName&DefaultVisibilityTimeout=45", - "application/x-www-form-urlencoded", false); + assertPayloadEquals(request, + "Version=2009-02-01&Action=CreateQueue&QueueName=queueName&DefaultVisibilityTimeout=45", + "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, RegexQueueHandler.class); assertSaxResponseParserClassEquals(method, null); @@ -151,8 +144,8 @@ public class SQSAsyncClientTest extends RestClientTest { } public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException { - Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, - String.class, Array.newInstance(CreateQueueOptions.class, 0).getClass()); + Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, String.class, Array + .newInstance(CreateQueueOptions.class, 0).getClass()); for (String region : Iterables.filter(Region.ALL_SQS, not(equalTo("us-standard")))) { processor.createRequest(method, region, "queueName"); } @@ -177,8 +170,7 @@ public class SQSAsyncClientTest extends RestClientTest { @Override public ContextSpec createContextSpec() { - return new RestContextFactory().createContextSpec("sqs", "identity", "credential", - new Properties()); + return new RestContextFactory().createContextSpec("sqs", "identity", "credential", new Properties()); } } diff --git a/aws/core/src/test/resources/ec2/eucalyptus_images.xml b/aws/core/src/test/resources/ec2/eucalyptus_images.xml index 8dddf47a41..b13bfdbf43 100644 --- a/aws/core/src/test/resources/ec2/eucalyptus_images.xml +++ b/aws/core/src/test/resources/ec2/eucalyptus_images.xml @@ -1,189 +1,49 @@ - - 7b893acf-7752-4e - 2c-8c1a-3287a011b0df + + 2564fc86-9a73-4727-9298-f0b9eb9b57c8 emi-9ACB1363 - centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml - - available - + centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml + available admin true x86_64 - - machine - - eki-6CBD12F2 - eri-A97113E4 - instance-store - /dev/sda1 - - - - emi-D2D610D1 - martin_try1/martin_try1.manifest.xml - - available - - dominic - true - - x86_64 machine eki-6CBD12F2 eri-A97113E4 - instance-store - /dev/sda1 - eri-A97113E4 - initrd-64/initrd.img-2.6.28-11-generic.manifest.xml - + initrd-64/initrd.img-2.6.28-11-generic.manifest.xml available admin true x86_64 ramdisk - - instance-store - - /dev/sda1 - - emi-B9A40FF6 - ulteo4/ubuntu804-32-test.manifest.xml - available - gaelduval - true - - - i386 - - machine - instance-store - /dev/sda1 - - - - - emi-D1991835 - - jamestyj-test/Eucalyptus_Guest.x86_64-0.0.2.raw.manifest.xml - - available - jamestyj - true - - x86_64 - machine - - instance-store - - /dev/sda1 - - - - emi-D8AB1044 - test/ubuntu.9-04.x86-64.img.manifest.xml - - available - mymq0206 - true - - - x86_64 - - machine - instance-store - /dev/sda1 - - - - - emi-CBEA100C - - Lean/ubuntu.9-04.x86-64.img.manifest.xml - - available - - mashaobing1 - - true - - x86_64 - machine - eki-6CBD12F2 - eri-A97113E4 - instance-store - /dev/sda1 - - - - emi-D176182B - jamestyj-test/Eucalyptus_Guest.x86_64-0.0.3.raw.manifest.xml - - available - - jamestyj - - true - - x86_64 - machine - instance-store - /dev/sda1 - - - - emi-D25E10CA - - biolinux/biolinux.qcow2.manifest.xml - - available - brainstorm - true - - x86_64 - machine - instance-store - /dev/sda1 - - - - - eki-6CBD12F2 - - kernel-64/vmlinuz-2.6.28-11-generic.manifest.xml - + eki-6CBD12F2 + kernel-64/vmlinuz-2.6.28-11-generic.manifest.xml available admin true x86_64 kernel - instance-store - /dev/sda1 - - emi-2EDC1606 - - ulteo2/Ulteo-SM-Scalability-Test-19feb2010.manifest.xml - + emi-B5C5103A + shashi-test/RTestSmall.manifest.xml available - gaelduval + admin true - i386 + x86_64 machine - instance-store - /dev/sda1 - + eki-6CBD12F2 + eri-A97113E4 \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClientTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClientTest.java index cdbae035d8..260938a3d7 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClientTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClientTest.java @@ -64,8 +64,7 @@ public class AzureBlobAsyncClientTest extends RestClientTest createContextSpec() { - return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", - new Properties()); + return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties()); } } diff --git a/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueAsyncClientTest.java b/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueAsyncClientTest.java index e1a8a89e73..24344195a1 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueAsyncClientTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueAsyncClientTest.java @@ -57,12 +57,10 @@ import com.google.inject.TypeLiteral; public class AzureQueueAsyncClientTest extends RestClientTest { public void testGetMessages() throws SecurityException, NoSuchMethodException, IOException { - Method method = AzureQueueAsyncClient.class.getMethod("getMessages", String.class, - GetOptions[].class); + Method method = AzureQueueAsyncClient.class.getMethod("getMessages", String.class, GetOptions[].class); HttpRequest request = processor.createRequest(method, "myqueue"); - assertRequestLineEquals(request, - "GET https://identity.queue.core.windows.net/myqueue/messages HTTP/1.1"); + assertRequestLineEquals(request, "GET https://identity.queue.core.windows.net/myqueue/messages HTTP/1.1"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertPayloadEquals(request, null, null, false); @@ -73,16 +71,12 @@ public class AzureQueueAsyncClientTest extends RestClientTestmessage", - "application/unknown", false); + assertPayloadEquals(request, "message", + "application/unknown", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -202,16 +186,15 @@ public class AzureQueueAsyncClientTest extends RestClientTestmessage", - "application/unknown", false); + assertPayloadEquals(request, "message", + "application/unknown", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -225,8 +208,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest createContextSpec() { - return new RestContextFactory().createContextSpec("azurequeue", "identity", "credential", - new Properties()); + return new RestContextFactory().createContextSpec("azurequeue", "identity", "credential", new Properties()); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java index fe8c8ef4e9..a88b901e00 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java @@ -45,8 +45,8 @@ import com.google.common.base.Function; /** * @author Adrian Cole */ -public class ParseSystemAndUserMetadataFromHeaders implements - Function, InvocationContext { +public class ParseSystemAndUserMetadataFromHeaders implements Function, + InvocationContext { private final String metadataPrefix; private final DateService dateParser; private final Provider metadataFactory; @@ -55,9 +55,8 @@ public class ParseSystemAndUserMetadataFromHeaders implements private GeneratedHttpRequest request; @Inject - public ParseSystemAndUserMetadataFromHeaders(Provider metadataFactory, - DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix, - @Named(PROPERTY_API_VERSION) String apiVersion) { + public ParseSystemAndUserMetadataFromHeaders(Provider metadataFactory, DateService dateParser, + @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix, @Named(PROPERTY_API_VERSION) String apiVersion) { this.metadataFactory = metadataFactory; this.dateParser = dateParser; this.metadataPrefix = metadataPrefix; @@ -81,9 +80,8 @@ public class ParseSystemAndUserMetadataFromHeaders implements void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().startsWith(metadataPrefix)) - metadata.getUserMetadata().put( - (header.getKey().substring(metadataPrefix.length())).toLowerCase(), - header.getValue()); + metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), + header.getValue()); } } @@ -93,12 +91,10 @@ public class ParseSystemAndUserMetadataFromHeaders implements } @VisibleForTesting - void parseLastModifiedOrThrowException(HttpResponse from, MutableBlobMetadata metadata) - throws HttpException { + void parseLastModifiedOrThrowException(HttpResponse from, MutableBlobMetadata metadata) throws HttpException { String lastModified = from.getFirstHeaderOrNull(HttpHeaders.LAST_MODIFIED); if (lastModified == null) - throw new HttpException(HttpHeaders.LAST_MODIFIED + " header not present in response: " - + from.getStatusLine()); + throw new HttpException(HttpHeaders.LAST_MODIFIED + " header not present in response: " + from.getStatusLine()); // Eucalyptus 1.6 returns iso8601 dates if (apiVersion.indexOf("Walrus-1.6") != -1) { metadata.setLastModified(dateParser.iso8601DateParse(lastModified.replace("+0000", "Z"))); @@ -107,8 +103,7 @@ public class ParseSystemAndUserMetadataFromHeaders implements } if (metadata.getLastModified() == null) - throw new HttpException("could not parse: " + HttpHeaders.LAST_MODIFIED + ": " - + lastModified); + throw new HttpException("could not parse: " + HttpHeaders.LAST_MODIFIED + ": " + lastModified); } @VisibleForTesting @@ -126,18 +121,16 @@ public class ParseSystemAndUserMetadataFromHeaders implements } @VisibleForTesting - void setContentTypeOrThrowException(HttpResponse from, MutableBlobMetadata metadata) - throws HttpException { + void setContentTypeOrThrowException(HttpResponse from, MutableBlobMetadata metadata) throws HttpException { if (from.getPayload() != null) metadata.setContentType(from.getPayload().getContentType()); - if (metadata.getContentType() == null - || "application/unknown".equals(metadata.getContentType())) + if (from.getStatusCode() != 204 && (metadata.getContentType() == null + || "application/unknown".equals(metadata.getContentType()))) throw new HttpException(HttpHeaders.CONTENT_TYPE + " not found in headers"); } public ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request) { - checkArgument(request instanceof GeneratedHttpRequest, - "note this handler requires a GeneratedHttpRequest"); + checkArgument(request instanceof GeneratedHttpRequest, "note this handler requires a GeneratedHttpRequest"); this.request = (GeneratedHttpRequest) request; return this; } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobMetadataFromHeadersTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java similarity index 91% rename from blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobMetadataFromHeadersTest.java rename to blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java index 0343d20c0a..c151c6e830 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobMetadataFromHeadersTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java @@ -43,7 +43,11 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; -public class ParseBlobMetadataFromHeadersTest { +/** + * @author Adrian Cole + */ +@Test(sequential = true) +public class ParseSystemAndUserMetadataFromHeadersTest { private ParseSystemAndUserMetadataFromHeaders parser; private Provider blobMetadataProvider = new Provider() { @@ -57,8 +61,8 @@ public class ParseBlobMetadataFromHeadersTest { @BeforeTest void setUp() { - parser = new ParseSystemAndUserMetadataFromHeaders(blobMetadataProvider, - new SimpleDateFormatDateService(), "prefix", "default"); + parser = new ParseSystemAndUserMetadataFromHeaders(blobMetadataProvider, new SimpleDateFormatDateService(), + "prefix", "default"); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); @@ -77,6 +81,13 @@ public class ParseBlobMetadataFromHeadersTest { assertEquals(metadata.getName(), "key"); } + @Test + public void testNoContentOn204IsOk() { + HttpResponse from = new HttpResponse(204, "ok", Payloads.newStringPayload("")); + from.getHeaders().put(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT"); + parser.apply(from); + } + @Test public void testSetContentLength() { HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload("")); @@ -116,7 +127,7 @@ public class ParseBlobMetadataFromHeadersTest { MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.parseLastModifiedOrThrowException(from, metadata); assertEquals(metadata.getLastModified(), new SimpleDateFormatDateService() - .rfc822DateParse("Wed, 09 Sep 2009 19:50:23 GMT")); + .rfc822DateParse("Wed, 09 Sep 2009 19:50:23 GMT")); } @Test(expectedExceptions = HttpException.class) diff --git a/boxdotnet/src/main/java/org/jclouds/boxdotnet/BoxDotNetAsyncClient.java b/boxdotnet/src/main/java/org/jclouds/boxdotnet/BoxDotNetAsyncClient.java index ed97eed8f0..00cd1cdba4 100644 --- a/boxdotnet/src/main/java/org/jclouds/boxdotnet/BoxDotNetAsyncClient.java +++ b/boxdotnet/src/main/java/org/jclouds/boxdotnet/BoxDotNetAsyncClient.java @@ -23,12 +23,10 @@ */ package org.jclouds.boxdotnet; -import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; -import javax.ws.rs.core.MediaType; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.ExceptionParser; @@ -47,7 +45,6 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adrian Cole */ @RequestFilters(BasicAuthentication.class) -@Consumes(MediaType.APPLICATION_JSON) public interface BoxDotNetAsyncClient { /* * TODO: define interface methods for BoxDotNet diff --git a/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java b/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java index 7754509a7c..5319a906f4 100644 --- a/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java +++ b/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java @@ -57,7 +57,7 @@ public class BoxDotNetAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying @@ -65,9 +65,10 @@ public class BoxDotNetAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, 1); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items/1 HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest, null, null, false); // TODO: insert expected response class, which probably extends ParseJson @@ -101,9 +102,8 @@ public class BoxDotNetAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, 1); - assertRequestLineEquals(httpRequest, - "DELETE https://www.box.net/api/1.0/rest/items/1 HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertRequestLineEquals(httpRequest, "DELETE https://www.box.net/api/1.0/rest/items/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest, null, null, false); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); @@ -128,7 +128,7 @@ public class BoxDotNetAsyncClientTest extends RestClientTest createContextSpec() { - return contextSpec("boxdotnet", "https://www.box.net/api/1.0/rest", "1.0", "identity", - "credential", BoxDotNetClient.class, BoxDotNetAsyncClient.class); + return contextSpec("boxdotnet", "https://www.box.net/api/1.0/rest", "1.0", "identity", "credential", + BoxDotNetClient.class, BoxDotNetAsyncClient.class); } } diff --git a/chef/src/main/java/org/jclouds/chef/ChefAsyncClient.java b/chef/src/main/java/org/jclouds/chef/ChefAsyncClient.java index 8c79b4791c..94fe4a6867 100644 --- a/chef/src/main/java/org/jclouds/chef/ChefAsyncClient.java +++ b/chef/src/main/java/org/jclouds/chef/ChefAsyncClient.java @@ -40,21 +40,22 @@ import org.jclouds.chef.binders.BindChecksumsToJsonPayload; import org.jclouds.chef.binders.BindClientnameToJsonPayload; import org.jclouds.chef.binders.BindGenerateKeyForClientToJsonPayload; import org.jclouds.chef.binders.BindIsCompletedToJsonPayload; +import org.jclouds.chef.binders.NodeName; import org.jclouds.chef.domain.CookbookVersion; +import org.jclouds.chef.domain.Node; import org.jclouds.chef.domain.Sandbox; import org.jclouds.chef.domain.UploadSandbox; import org.jclouds.chef.filters.SignedHeaderAuth; -import org.jclouds.chef.functions.ParseCookbookVersionFromJson; import org.jclouds.chef.functions.ParseKeyFromJson; import org.jclouds.chef.functions.ParseKeySetFromJson; -import org.jclouds.chef.functions.ParseSandboxFromJson; -import org.jclouds.chef.functions.ParseUploadSiteFromJson; -import org.jclouds.chef.functions.ParseValueSetFromJson; +import org.jclouds.http.functions.ReturnStringIf2xx; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.Headers; +import org.jclouds.rest.annotations.ParamParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.annotations.Unwrap; import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; @@ -71,8 +72,8 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adrian Cole */ @RequestFilters(SignedHeaderAuth.class) -@Consumes(MediaType.APPLICATION_JSON) @Headers(keys = "X-Chef-Version", values = ChefAsyncClient.VERSION) +@Consumes(MediaType.APPLICATION_JSON) public interface ChefAsyncClient { public static final String VERSION = "0.9.6"; @@ -81,22 +82,19 @@ public interface ChefAsyncClient { */ @POST @Path("sandboxes") - @ResponseParser(ParseUploadSiteFromJson.class) ListenableFuture getUploadSandboxForChecksums( - @BinderParam(BindChecksumsToJsonPayload.class) Set> md5s); + @BinderParam(BindChecksumsToJsonPayload.class) Set> md5s); @PUT - ListenableFuture uploadContent( - @BinderParam(BindChecksumsToJsonPayload.class) Set> md5s); + ListenableFuture uploadContent(@BinderParam(BindChecksumsToJsonPayload.class) Set> md5s); /** * @see ChefClient#commitSandbox */ @PUT @Path("sandboxes/{id}") - @ResponseParser(ParseSandboxFromJson.class) ListenableFuture commitSandbox(@PathParam("id") String id, - @BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted); + @BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted); /** * @see ChefCookbooks#listCookbooks @@ -112,8 +110,7 @@ public interface ChefAsyncClient { @PUT @Path("cookbooks/{cookbookname}/{version}") ListenableFuture updateCookbook(@PathParam("cookbookname") String cookbookName, - @PathParam("version") String version, - @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook); + @PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook); /** * @see ChefCookbook#deleteCookbook(String) @@ -122,27 +119,25 @@ public interface ChefAsyncClient { @Path("cookbooks/{cookbookname}/{version}") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteCookbook(@PathParam("cookbookname") String cookbookName, - @PathParam("version") String version); + @PathParam("version") String version); /** * @see ChefCookbook#getVersionsOfCookbook */ @GET @Path("cookbooks/{cookbookname}") - @ResponseParser(ParseValueSetFromJson.class) + @Unwrap @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture> getVersionsOfCookbook( - @PathParam("cookbookname") String cookbookName); + ListenableFuture> getVersionsOfCookbook(@PathParam("cookbookname") String cookbookName); /** * @see ChefCookbook#getCookbook */ @GET @Path("cookbooks/{cookbookname}/{version}") - @ResponseParser(ParseCookbookVersionFromJson.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture getCookbook(@PathParam("cookbookname") String cookbookName, - @PathParam("version") String version); + @PathParam("version") String version); /** * @see ChefClient#createClient @@ -150,8 +145,7 @@ public interface ChefAsyncClient { @POST @Path("clients") @ResponseParser(ParseKeyFromJson.class) - ListenableFuture createClient( - @BinderParam(BindClientnameToJsonPayload.class) String clientname); + ListenableFuture createClient(@BinderParam(BindClientnameToJsonPayload.class) String clientname); /** * @see ChefClient#generateKeyForClient @@ -160,7 +154,7 @@ public interface ChefAsyncClient { @Path("clients/{clientname}") @ResponseParser(ParseKeyFromJson.class) ListenableFuture generateKeyForClient( - @PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname); + @PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname); /** * @see ChefClient#clientExists @@ -184,6 +178,8 @@ public interface ChefAsyncClient { @DELETE @Path("clients/{clientname}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(ReturnStringIf2xx.class) + // TODO: why string? ListenableFuture deleteClient(@PathParam("clientname") String clientname); /** @@ -194,4 +190,51 @@ public interface ChefAsyncClient { @ResponseParser(ParseKeySetFromJson.class) ListenableFuture> listClients(); + /** + * @see ChefClient#createNode + */ + @POST + @Path("nodes") + ListenableFuture createNode(@BinderParam(BindToJsonPayload.class) Node node); + + /** + * @see ChefClient#updateNode + */ + @PUT + @Path("nodes/{nodename}") + ListenableFuture updateNode( + @PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node); + + /** + * @see ChefNode#nodeExists + */ + @HEAD + @Path("nodes/{nodename}") + @ExceptionParser(ReturnFalseOnNotFoundOr404.class) + ListenableFuture nodeExists(@PathParam("nodename") String nodename); + + /** + * @see ChefNode#getNode + */ + @GET + @Path("nodes/{nodename}") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getNode(@PathParam("nodename") String nodename); + + /** + * @see ChefNode#deleteNode + */ + @DELETE + @Path("nodes/{nodename}") + // TODO why string?! + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture deleteNode(@PathParam("nodename") String nodename); + + /** + * @see ChefNode#listNodes + */ + @GET + @Path("nodes") + @ResponseParser(ParseKeySetFromJson.class) + ListenableFuture> listNodes(); } diff --git a/chef/src/main/java/org/jclouds/chef/binders/NodeName.java b/chef/src/main/java/org/jclouds/chef/binders/NodeName.java new file mode 100644 index 0000000000..69b1bfc6dc --- /dev/null +++ b/chef/src/main/java/org/jclouds/chef/binders/NodeName.java @@ -0,0 +1,38 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.chef.binders; + +import javax.inject.Singleton; + +import org.jclouds.chef.domain.Node; + +import com.google.common.base.Function; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class NodeName implements Function { + + public String apply(Object from) { + return ((Node) from).getName(); + } + +} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java b/chef/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java index 043fee16b2..b4ff8634d9 100644 --- a/chef/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java +++ b/chef/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java @@ -130,7 +130,6 @@ public class BaseChefRestClientModule extends RestClientModule { @Override protected void configure() { - install(new ChefTypeAdapterModule()); bind(DateAdapter.class).to(Iso8601DateAdapter.class); super.configure(); } diff --git a/chef/src/main/java/org/jclouds/chef/config/ChefTypeAdapterModule.java b/chef/src/main/java/org/jclouds/chef/config/ChefTypeAdapterModule.java deleted file mode 100644 index 8b8570397a..0000000000 --- a/chef/src/main/java/org/jclouds/chef/config/ChefTypeAdapterModule.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.config; - -import static org.jclouds.Constants.PROPERTY_GSON_ADAPTERS; - -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.encryption.EncryptionService; - -import com.google.common.collect.Maps; -import com.google.common.primitives.Bytes; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.reflect.TypeToken; -import com.google.inject.AbstractModule; -import com.google.inject.Provides; - -/** - * Configures the Chef connection. - * - * @author Adrian Cole - */ - -public class ChefTypeAdapterModule extends AbstractModule { - - @Override - protected void configure() { - - } - - @Provides - @Singleton - @Named(PROPERTY_GSON_ADAPTERS) - public Map provideCustomAdapterBindings(HexByteListAdapter byteListAdapter, - HexByteArrayAdapter byteArrayAdapter) { - Map bindings = Maps.newHashMap(); - bindings.put(new TypeToken>() { - }.getType(), byteListAdapter); - bindings.put(byte[].class, byteArrayAdapter); - return bindings; - } - - @Singleton - public static class HexByteListAdapter implements JsonDeserializer>, - JsonSerializer> { - private final EncryptionService encryptionService; - - @Inject - HexByteListAdapter(EncryptionService encryptionService) { - this.encryptionService = encryptionService; - } - - @Override - public List deserialize(JsonElement json, Type typeOfT, - JsonDeserializationContext context) throws JsonParseException { - return Bytes.asList(encryptionService.fromHex(json.getAsString())); - } - - @Override - public JsonElement serialize(List src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive(encryptionService.hex(Bytes.toArray(src))); - } - - } - - @Singleton - public static class HexByteArrayAdapter implements JsonDeserializer, - JsonSerializer { - private final EncryptionService encryptionService; - - @Inject - HexByteArrayAdapter(EncryptionService encryptionService) { - this.encryptionService = encryptionService; - } - - @Override - public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - return encryptionService.fromHex(json.getAsString()); - } - - @Override - public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive(encryptionService.hex(src)); - } - } - -} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/domain/Node.java b/chef/src/main/java/org/jclouds/chef/domain/Node.java new file mode 100644 index 0000000000..a4fd6ef2bd --- /dev/null +++ b/chef/src/main/java/org/jclouds/chef/domain/Node.java @@ -0,0 +1,162 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.chef.domain; + +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.gson.annotations.SerializedName; + +/** + * Sandbox object. + * + * @author Adrian Cole + */ +public class Node { + + private String name; + private Map normal = Maps.newLinkedHashMap(); + private Map override = Maps.newLinkedHashMap(); + @SerializedName("default") + private Map defaultA = Maps.newLinkedHashMap(); + private Map automatic = Maps.newLinkedHashMap(); + @SerializedName("run_list") + private List runList = Lists.newArrayList(); + + // internal + @SuppressWarnings("unused") + @SerializedName("json_class") + private String _jsonClass = "Chef::Node"; + + public Node(String name, Map normal, + Map override, Map defaultA, + Map automatic, Iterable runList) { + this.name = name; + this.normal.putAll(normal); + this.override.putAll(override); + this.defaultA.putAll(defaultA); + this.automatic.putAll(automatic); + Iterables.addAll(this.runList, runList); + } + + @Override + public String toString() { + return "Node [name=" + name + ", runList=" + runList + ", normal=" + + normal + ", default=" + defaultA + ", override=" + override + + ", automatic=" + automatic + "]"; + } + + public Node(String name, Iterable runList) { + this.name = name; + Iterables.addAll(this.runList, runList); + } + + // hidden but needs to be here for json deserialization to work + Node() { + + } + + public String getName() { + return name; + } + + public Map getNormal() { + return normal; + } + + public Map getOverride() { + return override; + } + + public Map getDefault() { + return defaultA; + } + + public Map getAutomatic() { + return automatic; + } + + public List getRunList() { + return runList; + } + + @SerializedName("chef_type") + @SuppressWarnings("unused") + private String _chefType = "node"; + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((automatic == null) ? 0 : automatic.hashCode()); + result = prime * result + ((defaultA == null) ? 0 : defaultA.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((normal == null) ? 0 : normal.hashCode()); + result = prime * result + ((override == null) ? 0 : override.hashCode()); + result = prime * result + ((runList == null) ? 0 : runList.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Node other = (Node) obj; + if (automatic == null) { + if (other.automatic != null) + return false; + } else if (!automatic.equals(other.automatic)) + return false; + if (defaultA == null) { + if (other.defaultA != null) + return false; + } else if (!defaultA.equals(other.defaultA)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (normal == null) { + if (other.normal != null) + return false; + } else if (!normal.equals(other.normal)) + return false; + if (override == null) { + if (other.override != null) + return false; + } else if (!override.equals(other.override)) + return false; + if (runList == null) { + if (other.runList != null) + return false; + } else if (!runList.equals(other.runList)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookVersionFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookVersionFromJson.java deleted file mode 100644 index 5f5301498e..0000000000 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookVersionFromJson.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.functions; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.http.functions.ParseJson; - -import com.google.gson.Gson; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ParseCookbookVersionFromJson extends ParseJson { - @Inject - public ParseCookbookVersionFromJson(Gson gson) { - super(gson); - } - - @Override - protected CookbookVersion apply(InputStream stream) { - try { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), CookbookVersion.class); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - } -} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java index 1fcf30ee5b..b3e212ccc6 100644 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java +++ b/chef/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java @@ -41,41 +41,33 @@ */ package org.jclouds.chef.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; /** * @author Adrian Cole */ @Singleton -public class ParseKeySetFromJson extends ParseJson> { +public class ParseKeySetFromJson implements Function> { + + private final ParseJson> json; + @Inject - public ParseKeySetFromJson(Gson gson) { - super(gson); + ParseKeySetFromJson(ParseJson> json) { + this.json = json; } - @SuppressWarnings("unchecked") @Override - protected Set apply(InputStream stream) { - try { - Type map = new TypeToken>() { - }.getType(); - return ((Map) gson.fromJson(new InputStreamReader(stream, "UTF-8"), map)) - .keySet(); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } + public Set apply(HttpResponse arg0) { + return json.apply(arg0).keySet(); + } } \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseOrganizationFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseOrganizationFromJson.java deleted file mode 100644 index 115e3b1888..0000000000 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseOrganizationFromJson.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.functions; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Organization; -import org.jclouds.http.functions.ParseJson; - -import com.google.gson.Gson; - -/** - * @author Adrian Cole - */ -@Singleton -public class ParseOrganizationFromJson extends ParseJson { - @Inject - public ParseOrganizationFromJson(Gson gson) { - super(gson); - } - - @Override - protected Organization apply(InputStream stream) { - try { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), Organization.class); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - } -} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseSandboxFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseSandboxFromJson.java deleted file mode 100644 index 8ee77038ef..0000000000 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseSandboxFromJson.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.functions; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Sandbox; -import org.jclouds.http.functions.ParseJson; - -import com.google.gson.Gson; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ParseSandboxFromJson extends ParseJson { - @Inject - public ParseSandboxFromJson(Gson gson) { - super(gson); - } - - @Override - protected Sandbox apply(InputStream stream) { - try { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), Sandbox.class); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - } -} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseUploadSiteFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseUploadSiteFromJson.java deleted file mode 100644 index 449f8ace32..0000000000 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseUploadSiteFromJson.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.functions; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.http.functions.ParseJson; - -import com.google.gson.Gson; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ParseUploadSiteFromJson extends ParseJson { - @Inject - public ParseUploadSiteFromJson(Gson gson) { - super(gson); - } - - @Override - protected UploadSandbox apply(InputStream stream) { - try { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), UploadSandbox.class); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - } -} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseUserFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseUserFromJson.java deleted file mode 100644 index 8f0e4dc55e..0000000000 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseUserFromJson.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.functions; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.User; -import org.jclouds.http.functions.ParseJson; - -import com.google.gson.Gson; - -/** - * @author Adrian Cole - */ -@Singleton -public class ParseUserFromJson extends ParseJson { - @Inject - public ParseUserFromJson(Gson gson) { - super(gson); - } - - @Override - protected User apply(InputStream stream) { - - try { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), User.class); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - } -} \ No newline at end of file diff --git a/chef/src/main/java/org/jclouds/chef/functions/ParseValueSetFromJson.java b/chef/src/main/java/org/jclouds/chef/functions/ParseValueSetFromJson.java deleted file mode 100644 index 2722c5b0f7..0000000000 --- a/chef/src/main/java/org/jclouds/chef/functions/ParseValueSetFromJson.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - */ -package org.jclouds.chef.functions; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.http.functions.ParseJson; - -import com.google.common.collect.Iterables; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * @author Adrian Cole - */ -@Singleton -public class ParseValueSetFromJson extends ParseJson> { - @Inject - public ParseValueSetFromJson(Gson gson) { - super(gson); - } - - @SuppressWarnings("unchecked") - @Override - protected Set apply(InputStream stream) { - try { - Type map = new TypeToken>>() { - }.getType(); - return Iterables.get( - ((Map>) gson.fromJson(new InputStreamReader(stream, "UTF-8"), - map)).entrySet(), 0).getValue(); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - } -} \ No newline at end of file diff --git a/chef/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java b/chef/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java index 146c841840..73e98628c5 100644 --- a/chef/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java +++ b/chef/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java @@ -34,15 +34,13 @@ import org.jclouds.chef.config.ChefRestClientModule; import org.jclouds.chef.domain.CookbookVersion; import org.jclouds.chef.filters.SignedHeaderAuth; import org.jclouds.chef.filters.SignedHeaderAuthTest; -import org.jclouds.chef.functions.ParseCookbookVersionFromJson; import org.jclouds.chef.functions.ParseKeyFromJson; import org.jclouds.chef.functions.ParseKeySetFromJson; -import org.jclouds.chef.functions.ParseSandboxFromJson; -import org.jclouds.chef.functions.ParseUploadSiteFromJson; import org.jclouds.date.TimeStamp; import org.jclouds.encryption.EncryptionService; import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReturnStringIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx; @@ -75,13 +73,13 @@ public class ChefAsyncClientTest extends RestClientTest { Method method = ChefAsyncClient.class.getMethod("commitSandbox", String.class, boolean.class); GeneratedHttpRequest httpRequest = processor.createRequest(method, - "0189e76ccc476701d6b374e5a1a27347", true); + "0189e76ccc476701d6b374e5a1a27347", true); assertRequestLineEquals(httpRequest, - "PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1"); + "PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertPayloadEquals(httpRequest, "{\"is_completed\":\"true\"}", "application/json", false); - assertResponseParserClassEquals(method, httpRequest, ParseSandboxFromJson.class); + assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); @@ -89,26 +87,21 @@ public class ChefAsyncClientTest extends RestClientTest { } - public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, - IOException { + public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException { EncryptionService encryptionService = injector.getInstance(EncryptionService.class); Method method = ChefAsyncClient.class.getMethod("getUploadSandboxForChecksums", Set.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, - ImmutableSet - .of(Bytes.asList(encryptionService - .fromHex("0189e76ccc476701d6b374e5a1a27347")), Bytes - .asList(encryptionService - .fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes - .asList(encryptionService - .fromHex("1dda05ed139664f1f89b9dec482b77c0")))); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableSet.of(Bytes + .asList(encryptionService.fromHex("0189e76ccc476701d6b374e5a1a27347")), Bytes.asList(encryptionService + .fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes.asList(encryptionService + .fromHex("1dda05ed139664f1f89b9dec482b77c0")))); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertPayloadEquals( - httpRequest, - "{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}", - "application/json", false); + httpRequest, + "{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}", + "application/json", false); - assertResponseParserClassEquals(method, httpRequest, ParseUploadSiteFromJson.class); + assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); @@ -118,14 +111,12 @@ public class ChefAsyncClientTest extends RestClientTest { public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException { Method method = ChefAsyncClient.class.getMethod("getCookbook", String.class, String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, - "cookbook", "1.0.0"); - assertRequestLineEquals(httpRequest, - "GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "cookbook", "1.0.0"); + assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertPayloadEquals(httpRequest, null, null, false); - assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionFromJson.class); + assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); @@ -135,10 +126,8 @@ public class ChefAsyncClientTest extends RestClientTest { public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException { Method method = ChefAsyncClient.class.getMethod("deleteCookbook", String.class, String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, - "cookbook", "1.0.0"); - assertRequestLineEquals(httpRequest, - "DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "cookbook", "1.0.0"); + assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -152,17 +141,16 @@ public class ChefAsyncClientTest extends RestClientTest { public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException { Method method = ChefAsyncClient.class.getMethod("updateCookbook", String.class, String.class, - CookbookVersion.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, - "cookbook", "1.0.1", new CookbookVersion("cookbook", "1.0.1")); + CookbookVersion.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "cookbook", "1.0.1", + new CookbookVersion("cookbook", "1.0.1")); - assertRequestLineEquals(httpRequest, - "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1"); + assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertPayloadEquals( - httpRequest, - "{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},\"platforms\":{},\"recipes\":{},\"replacing\":{},\"groupings\":{},\"attributes\":{},\"recommendations\":{}},\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],\"libraries\":[],\"version\":\"1.0.1\",\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\",\"chef_type\":\"cookbook_version\"}", - "application/json", false); + httpRequest, + "{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},\"platforms\":{},\"recipes\":{},\"replacing\":{},\"groupings\":{},\"attributes\":{},\"recommendations\":{}},\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],\"libraries\":[],\"version\":\"1.0.1\",\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\",\"chef_type\":\"cookbook_version\"}", + "application/json", false); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, null); @@ -217,14 +205,12 @@ public class ChefAsyncClientTest extends RestClientTest { } - public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, - IOException { + public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException { Method method = ChefAsyncClient.class.getMethod("generateKeyForClient", String.class); GeneratedHttpRequest httpRequest = processor.createRequest(method, "client"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/clients/client HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); - assertPayloadEquals(httpRequest, "{\"clientname\":\"client\", \"private_key\": true}", - "application/json", false); + assertPayloadEquals(httpRequest, "{\"clientname\":\"client\", \"private_key\": true}", "application/json", false); assertResponseParserClassEquals(method, httpRequest, ParseKeyFromJson.class); assertSaxResponseParserClassEquals(method, null); @@ -295,7 +281,7 @@ public class ChefAsyncClientTest extends RestClientTest { @Override public ContextSpec createContextSpec() { - return new RestContextFactory().createContextSpec("chef", "user", - SignedHeaderAuthTest.PRIVATE_KEY, new Properties()); + return new RestContextFactory().createContextSpec("chef", "user", SignedHeaderAuthTest.PRIVATE_KEY, + new Properties()); } } diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java index 4c474ae16d..786bc4c721 100644 --- a/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java +++ b/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java @@ -6,7 +6,6 @@ import java.io.IOException; import java.net.URI; import java.util.Set; -import org.jclouds.chef.config.ChefTypeAdapterModule; import org.jclouds.chef.domain.Attribute; import org.jclouds.chef.domain.CookbookVersion; import org.jclouds.chef.domain.Metadata; @@ -14,6 +13,7 @@ import org.jclouds.chef.domain.Resource; import org.jclouds.encryption.EncryptionService; import org.jclouds.http.HttpResponse; import org.jclouds.http.Payloads; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.config.ParserModule; import org.jclouds.util.Utils; import org.testng.annotations.BeforeTest; @@ -24,6 +24,8 @@ import com.google.common.collect.ImmutableSet; import com.google.gson.Gson; import com.google.inject.Guice; import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseCookbookVersionFromJson} @@ -33,92 +35,100 @@ import com.google.inject.Injector; @Test(groups = "unit", sequential = true, testName = "chef.ParseCookbookVersionFromJsonTest") public class ParseCookbookVersionFromJsonTest { - private ParseCookbookVersionFromJson handler; + private ParseJson handler; private Injector injector; @BeforeTest protected void setUpInjector() throws IOException { - injector = Guice.createInjector(new ParserModule(), new ChefTypeAdapterModule()); - handler = injector.getInstance(ParseCookbookVersionFromJson.class); + injector = Guice.createInjector(new ParserModule()); + handler = injector.getInstance(Key + .get(new TypeLiteral>() { + })); } + @Test(enabled = false) public void testBrew() throws IOException { - CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class - .getResourceAsStream("/brew-cookbook.json")))); + CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", + Payloads.newPayload(ParseCookbookVersionFromJsonTest.class + .getResourceAsStream("/brew-cookbook.json")))); - assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils - .toInputStream(new Gson().toJson(cookbook)))))); + assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads + .newPayload(Utils.toInputStream(new Gson().toJson(cookbook)))))); } @Test(enabled = false) public void testTomcat() { - CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class - .getResourceAsStream("/tomcat-cookbook.json")))); + CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", + Payloads.newPayload(ParseCookbookVersionFromJsonTest.class + .getResourceAsStream("/tomcat-cookbook.json")))); - assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils - .toInputStream(new Gson().toJson(cookbook)))))); + assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads + .newPayload(Utils.toInputStream(new Gson().toJson(cookbook)))))); } @Test(enabled = false) public void testMysql() throws IOException { - CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class - .getResourceAsStream("/mysql-cookbook.json")))); + CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", + Payloads.newPayload(ParseCookbookVersionFromJsonTest.class + .getResourceAsStream("/mysql-cookbook.json")))); - assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils - .toInputStream(new Gson().toJson(cookbook)))))); + assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads + .newPayload(Utils.toInputStream(new Gson().toJson(cookbook)))))); } @Test(enabled = false) public void testApache() { - EncryptionService encryptionService = injector.getInstance(EncryptionService.class); + EncryptionService encryptionService = injector + .getInstance(EncryptionService.class); assertEquals( - handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class - .getResourceAsStream("/apache-chef-demo-cookbook.json")))), - new CookbookVersion( - "apache-chef-demo-0.0.0", - ImmutableSet. of(), - ImmutableSet. of(), - ImmutableSet. of(), - new Metadata("Apache v2.0", "Your Name", - ImmutableMap. of(), ImmutableMap - .> of(), "youremail@example.com", - ImmutableMap.> of(), - "A fabulous new cookbook", - ImmutableMap.> of(), ImmutableMap - .> of(), "0.0.0", ImmutableMap - . of(), ImmutableMap - .> of(), "apache-chef-demo", - ImmutableMap. of(), "", ImmutableMap - . of(), ImmutableMap - . of()), - ImmutableSet. of(), - "apache-chef-demo", - ImmutableSet. of(), - ImmutableSet. of(), - ImmutableSet. of(), - "0.0.0", - ImmutableSet. of(), - ImmutableSet - . of( - new Resource( - "README", - URI - .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D"), - encryptionService - .fromHex("11637f98942eafbf49c71b7f2f048b78"), - "README", "default"), - new Resource( - "Rakefile", - URI - .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D"), - encryptionService - .fromHex("ebcf925a1651b4e04b9cd8aac2bc54eb"), - "Rakefile", "default")))); + handler + .apply(new HttpResponse( + 200, + "ok", + Payloads + .newPayload(ParseCookbookVersionFromJsonTest.class + .getResourceAsStream("/apache-chef-demo-cookbook.json")))), + new CookbookVersion( + "apache-chef-demo-0.0.0", + ImmutableSet. of(), + ImmutableSet. of(), + ImmutableSet. of(), + new Metadata("Apache v2.0", "Your Name", ImmutableMap + . of(), ImmutableMap + .> of(), "youremail@example.com", + ImmutableMap.> of(), + "A fabulous new cookbook", ImmutableMap + .> of(), ImmutableMap + .> of(), "0.0.0", + ImmutableMap. of(), ImmutableMap + .> of(), "apache-chef-demo", + ImmutableMap. of(), "", ImmutableMap + . of(), ImmutableMap + . of()), + ImmutableSet. of(), + "apache-chef-demo", + ImmutableSet. of(), + ImmutableSet. of(), + ImmutableSet. of(), + "0.0.0", + ImmutableSet. of(), + ImmutableSet + . of( + new Resource( + "README", + URI + .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D"), + encryptionService + .fromHex("11637f98942eafbf49c71b7f2f048b78"), + "README", "default"), + new Resource( + "Rakefile", + URI + .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D"), + encryptionService + .fromHex("ebcf925a1651b4e04b9cd8aac2bc54eb"), + "Rakefile", "default")))); } } diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseOrganizationFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseOrganizationFromJsonTest.java index fb8899ffd3..c4ee4a348e 100644 --- a/chef/src/test/java/org/jclouds/chef/functions/ParseOrganizationFromJsonTest.java +++ b/chef/src/test/java/org/jclouds/chef/functions/ParseOrganizationFromJsonTest.java @@ -25,6 +25,7 @@ import java.io.IOException; import org.jclouds.chef.domain.Organization; import org.jclouds.http.HttpResponse; import org.jclouds.http.Payloads; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.config.ParserModule; import org.jclouds.util.Utils; import org.testng.annotations.BeforeTest; @@ -32,6 +33,8 @@ import org.testng.annotations.Test; import com.google.inject.Guice; import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseOrganizationFromJson} @@ -41,12 +44,14 @@ import com.google.inject.Injector; @Test(groups = "unit", sequential = true, testName = "chef.ParseOrganizationFromJsonTest") public class ParseOrganizationFromJsonTest { - private ParseOrganizationFromJson handler; + private ParseJson handler; @BeforeTest protected void setUpInjector() throws IOException { Injector injector = Guice.createInjector(new ParserModule()); - handler = injector.getInstance(ParseOrganizationFromJson.class); + handler = injector.getInstance(Key + .get(new TypeLiteral>() { + })); } public void test() { @@ -58,7 +63,7 @@ public class ParseOrganizationFromJsonTest { String toParse = "{\"name\": \"opscode\",\"full_name\": \"Opscode, Inc.\", \"org_type\": \"Business\",\"clientname\": \"opscode-validator\" }"; - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils - .toInputStream(toParse)))), org); + assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads + .newPayload(Utils.toInputStream(toParse)))), org); } } diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java index 39c8484d05..404833d867 100644 --- a/chef/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java +++ b/chef/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java @@ -8,6 +8,7 @@ import org.jclouds.chef.domain.Sandbox; import org.jclouds.date.DateService; import org.jclouds.http.HttpResponse; import org.jclouds.http.Payloads; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule.DateAdapter; import org.jclouds.http.functions.config.ParserModule.Iso8601DateAdapter; @@ -18,6 +19,8 @@ import com.google.common.collect.ImmutableSet; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseSandboxFromJson} @@ -27,29 +30,33 @@ import com.google.inject.Injector; @Test(groups = "unit", sequential = true, testName = "chef.ParseSandboxFromJsonTest") public class ParseSandboxFromJsonTest { - private ParseSandboxFromJson handler; + private ParseJson handler; private DateService dateService; @BeforeTest protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ParserModule(), new AbstractModule() { + Injector injector = Guice.createInjector(new ParserModule(), + new AbstractModule() { - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } + @Override + protected void configure() { + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } - }); - handler = injector.getInstance(ParseSandboxFromJson.class); + }); + handler = injector.getInstance(Key + .get(new TypeLiteral>() { + })); dateService = injector.getInstance(DateService.class); } public void test() { assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseSandboxFromJsonTest.class.getResourceAsStream("/sandbox.json")))), - new Sandbox("1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, dateService - .iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"), ImmutableSet - . of(), "f9d6d9b72bae465890aae87969f98a9c", - "f9d6d9b72bae465890aae87969f98a9c")); + .newPayload(ParseSandboxFromJsonTest.class + .getResourceAsStream("/sandbox.json")))), new Sandbox( + "1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, dateService + .iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"), + ImmutableSet. of(), "f9d6d9b72bae465890aae87969f98a9c", + "f9d6d9b72bae465890aae87969f98a9c")); } } diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java new file mode 100644 index 0000000000..601e576d17 --- /dev/null +++ b/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java @@ -0,0 +1,74 @@ +package org.jclouds.chef.functions; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; +import java.util.List; + +import org.jclouds.chef.domain.ChecksumStatus; +import org.jclouds.chef.domain.UploadSandbox; +import org.jclouds.encryption.EncryptionService; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.Payloads; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.http.functions.config.ParserModule; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.primitives.Bytes; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; + +/** + * Tests behavior of {@code ParseUploadSiteFromJson} + * + * @author Adrian Cole + */ +@Test(groups = "unit", sequential = true, testName = "chef.ParseUploadSiteFromJsonTest") +public class ParseUploadSandboxFromJsonTest { + + private ParseJson handler; + private Injector injector; + + @BeforeTest + protected void setUpInjector() throws IOException { + injector = Guice.createInjector(new ParserModule()); + handler = injector.getInstance(Key + .get(new TypeLiteral>() { + })); + } + + public void test() { + EncryptionService encryptionService = injector + .getInstance(EncryptionService.class); + assertEquals( + handler.apply(new HttpResponse(200, "ok", Payloads + .newPayload(ParseUploadSandboxFromJsonTest.class + .getResourceAsStream("/upload-site.json")))), + new UploadSandbox( + URI + .create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"), + ImmutableMap + ., ChecksumStatus> of( + Bytes + .asList(encryptionService + .fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), + new ChecksumStatus( + URI + .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D"), + true), + Bytes + .asList(encryptionService + .fromHex("0189e76ccc476701d6b374e5a1a27347")), + new ChecksumStatus(), + Bytes + .asList(encryptionService + .fromHex("1dda05ed139664f1f89b9dec482b77c0")), + new ChecksumStatus()), + "d454f71e2a5f400c808d0c5d04c2c88c")); + } +} diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSiteFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSiteFromJsonTest.java deleted file mode 100644 index ad676104ac..0000000000 --- a/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSiteFromJsonTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.net.URI; -import java.util.List; - -import org.jclouds.chef.config.ChefTypeAdapterModule; -import org.jclouds.chef.domain.ChecksumStatus; -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.encryption.EncryptionService; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.Payloads; -import org.jclouds.http.functions.config.ParserModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.primitives.Bytes; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code ParseUploadSiteFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseUploadSiteFromJsonTest") -public class ParseUploadSiteFromJsonTest { - - private ParseUploadSiteFromJson handler; - private Injector injector; - - @BeforeTest - protected void setUpInjector() throws IOException { - injector = Guice.createInjector(new ParserModule(), new ChefTypeAdapterModule()); - handler = injector.getInstance(ParseUploadSiteFromJson.class); - } - - public void test() { - EncryptionService encryptionService = injector.getInstance(EncryptionService.class); - assertEquals( - handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseUploadSiteFromJsonTest.class - .getResourceAsStream("/upload-site.json")))), - new UploadSandbox( - URI - .create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"), - ImmutableMap - ., ChecksumStatus> of( - Bytes.asList(encryptionService - .fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), - new ChecksumStatus( - URI - .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D"), - true), Bytes.asList(encryptionService - .fromHex("0189e76ccc476701d6b374e5a1a27347")), - new ChecksumStatus(), Bytes.asList(encryptionService - .fromHex("1dda05ed139664f1f89b9dec482b77c0")), - new ChecksumStatus()), "d454f71e2a5f400c808d0c5d04c2c88c")); - } -} diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseUserFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseUserFromJsonTest.java index 415a29d4cd..ca4b14cc50 100644 --- a/chef/src/test/java/org/jclouds/chef/functions/ParseUserFromJsonTest.java +++ b/chef/src/test/java/org/jclouds/chef/functions/ParseUserFromJsonTest.java @@ -7,6 +7,7 @@ import java.io.IOException; import org.jclouds.chef.domain.User; import org.jclouds.http.HttpResponse; import org.jclouds.http.Payloads; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.config.ParserModule; import org.jclouds.util.Utils; import org.testng.annotations.BeforeTest; @@ -14,6 +15,8 @@ import org.testng.annotations.Test; import com.google.inject.Guice; import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseUserFromJson} @@ -23,12 +26,14 @@ import com.google.inject.Injector; @Test(groups = "unit", sequential = true, testName = "chef.ParseUserFromJsonTest") public class ParseUserFromJsonTest { - private ParseUserFromJson handler; + private ParseJson handler; @BeforeTest protected void setUpInjector() throws IOException { Injector injector = Guice.createInjector(new ParserModule()); - handler = injector.getInstance(ParseUserFromJson.class); + handler = injector.getInstance(Key + .get(new TypeLiteral>() { + })); } public void test() { @@ -42,7 +47,7 @@ public class ParseUserFromJsonTest { String toParse = "{\n\"username\": \"bobo\",\n\"first_name\": \"Bobo\",\n\"middle_name\": \"Tiberion\",\n\"last_name\": \"Clown\",\n\"display_name\": \"Bobo T. Clown\",\n\"email\": \"bobo@clownco.com\" \n}"; - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils - .toInputStream(toParse)))), user); + assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads + .newPayload(Utils.toInputStream(toParse)))), user); } } diff --git a/chef/src/test/java/org/jclouds/chef/functions/ParseValueSetFromJsonTest.java b/chef/src/test/java/org/jclouds/chef/functions/ParseValueSetFromJsonTest.java deleted file mode 100644 index 3bea425411..0000000000 --- a/chef/src/test/java/org/jclouds/chef/functions/ParseValueSetFromJsonTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.http.HttpResponse; -import org.jclouds.http.Payloads; -import org.jclouds.http.functions.config.ParserModule; -import org.jclouds.util.Utils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code ParseValueSetFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseValueSetFromJsonTest") -public class ParseValueSetFromJsonTest { - - private ParseValueSetFromJson handler; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ParserModule()); - handler = injector.getInstance(ParseValueSetFromJson.class); - } - - public void testRegex() { - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils - .toInputStream("{\"runit\":[\"0.7.0\",\"0.7.1\"]}")))), ImmutableSet.of("0.7.0", - "0.7.1")); - } -} diff --git a/compute/src/main/java/org/jclouds/compute/internal/TemplateBuilderImpl.java b/compute/src/main/java/org/jclouds/compute/internal/TemplateBuilderImpl.java index 49232c1373..856c9334c1 100644 --- a/compute/src/main/java/org/jclouds/compute/internal/TemplateBuilderImpl.java +++ b/compute/src/main/java/org/jclouds/compute/internal/TemplateBuilderImpl.java @@ -19,6 +19,11 @@ package org.jclouds.compute.internal; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.and; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.find; +import static com.google.common.collect.Lists.newArrayList; +import static org.jclouds.util.Utils.multiMax; import java.util.Arrays; import java.util.List; @@ -42,15 +47,12 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; -import com.google.common.base.Predicates; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.primitives.Doubles; @@ -65,12 +67,12 @@ public class TemplateBuilderImpl implements TemplateBuilder { @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final Provider> images; - private final Provider> sizes; - private final Provider> locations; + protected final Provider> images; + protected final Provider> sizes; + protected final Provider> locations; protected final Provider optionsProvider; - private final Provider defaultTemplateProvider; - private final Location defaultLocation; + protected final Provider defaultTemplateProvider; + protected final Location defaultLocation; @VisibleForTesting protected OsFamily os; @@ -102,10 +104,8 @@ public class TemplateBuilderImpl implements TemplateBuilder { protected TemplateOptions options; @Inject - protected TemplateBuilderImpl(Provider> locations, - Provider> images, - Provider> sizes, Location defaultLocation, - Provider optionsProvider, + protected TemplateBuilderImpl(Provider> locations, Provider> images, + Provider> sizes, Location defaultLocation, Provider optionsProvider, @Named("DEFAULT") Provider defaultTemplateProvider) { this.locations = locations; this.images = images; @@ -172,15 +172,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { returnVal = false; else returnVal = input.getOsDescription().contains(osDescription) - || input.getOsDescription().matches(osDescription); /* - * note: - * matches - * () - * expects - * a - * regex - * ! - */ + || input.getOsDescription().matches(osDescription); } return returnVal; } @@ -193,13 +185,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { if (input.getVersion() == null) returnVal = false; else - returnVal = input.getVersion().contains(imageVersion) - || input.getVersion().matches(imageVersion); /* - * note: - * matches() - * expects a - * regex! - */ + returnVal = input.getVersion().contains(imageVersion) || input.getVersion().matches(imageVersion); } return returnVal; } @@ -212,11 +198,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { if (input.getName() == null) returnVal = false; else - returnVal = input.getName().contains(imageName) - || input.getName().matches(imageName); /* - * note: matches() - * expects a regex! - */ + returnVal = input.getName().contains(imageName) || input.getName().matches(imageName); } return returnVal; } @@ -231,15 +213,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { else returnVal = input.getDescription().equals(imageDescription) || input.getDescription().contains(imageDescription) - || input.getDescription().matches(imageDescription); /* - * note: - * matches - * () - * expects - * a - * regex - * ! - */ + || input.getDescription().matches(imageDescription); } return returnVal; } @@ -272,15 +246,13 @@ public class TemplateBuilderImpl implements TemplateBuilder { return input.getRam() >= TemplateBuilderImpl.this.minRam; } }; - private final Predicate sizePredicate = Predicates.and( - sizeIdPredicate, locationPredicate, sizeCoresPredicate, + private final Predicate sizePredicate = and(sizeIdPredicate, locationPredicate, sizeCoresPredicate, sizeRamPredicate); static final Ordering DEFAULT_SIZE_ORDERING = new Ordering() { public int compare(Size left, Size right) { - return ComparisonChain.start().compare(left.getCores(), - right.getCores()).compare(left.getRam(), right.getRam()) - .compare(left.getDisk(), right.getDisk()).result(); + return ComparisonChain.start().compare(left.getCores(), right.getCores()).compare(left.getRam(), + right.getRam()).compare(left.getDisk(), right.getDisk()).result(); } }; static final Ordering BY_CORES_ORDERING = new Ordering() { @@ -290,13 +262,11 @@ public class TemplateBuilderImpl implements TemplateBuilder { }; static final Ordering DEFAULT_IMAGE_ORDERING = new Ordering() { public int compare(Image left, Image right) { - return ComparisonChain.start().compare(left.getName(), - right.getName(), Ordering. natural().nullsLast()) - .compare(left.getVersion(), right.getVersion(), - Ordering. natural().nullsLast()).compare( - left.getOsDescription(), right.getOsDescription(), - Ordering. natural().nullsLast()).compare( - left.getArchitecture(), right.getArchitecture()).result(); + return ComparisonChain.start().compare(left.getName(), right.getName(), + Ordering. natural().nullsLast()).compare(left.getVersion(), right.getVersion(), + Ordering. natural().nullsLast()).compare(left.getOsDescription(), right.getOsDescription(), + Ordering. natural().nullsLast()).compare(left.getArchitecture(), right.getArchitecture()) + .result(); } }; @@ -415,17 +385,8 @@ public class TemplateBuilderImpl implements TemplateBuilder { options = optionsProvider.get(); logger.debug(">> searching params(%s)", this); Location location = resolveLocation(); - List images = resolveImages(); - final Size size = resolveSize(sizeSorter(), images); - - Image image = Iterables.find(images, new Predicate() { - - @Override - public boolean apply(Image input) { - return size.supportsImage(input); - } - - }); + Size size = resolveSize(sizeSorter(), getImages()); + Image image = resolveImage(size); logger.debug("<< matched image(%s)", image); // ensure we have an architecture matching @@ -434,52 +395,41 @@ public class TemplateBuilderImpl implements TemplateBuilder { } protected Location resolveLocation() { - Location location = Iterables.find(locations.get(), - new Predicate() { + Location location = find(locations.get(), new Predicate() { - @Override - public boolean apply(Location input) { - return input.getId().equals(locationId); - } + @Override + public boolean apply(Location input) { + return input.getId().equals(locationId); + } - }); + }); logger.debug("<< matched location(%s)", location); return location; } - protected Size resolveSize(Ordering sizeOrdering, - final List images) { + protected Size resolveSize(Ordering sizeOrdering, final Iterable images) { Size size; try { - Iterable sizesThatAreCompatibleWithOurImages = Iterables - .filter(sizes.get(), new Predicate() { - @Override - public boolean apply(final Size size) { - boolean returnVal = false; - if (size != null) - returnVal = Iterables.any(images, - new Predicate() { + Iterable sizesThatAreCompatibleWithOurImages = filter(sizes.get(), new Predicate() { + @Override + public boolean apply(final Size size) { + boolean returnVal = false; + if (size != null) { + returnVal = Iterables.any(images, new Predicate() { - @Override - public boolean apply(Image input) { - boolean returnVal = size - .supportsImage(input); - if (!returnVal && input.getId().equals("us-east-1/ami-7ea24a17")) { - System.err.println("goo"); - } - return returnVal; + @Override + public boolean apply(Image input) { + return size.supportsImage(input); + } - } - - }); - return returnVal; - } - }); - size = sizeOrdering.max(Iterables.filter( - sizesThatAreCompatibleWithOurImages, sizePredicate)); + }); + } + return returnVal; + } + }); + size = sizeOrdering.max(filter(sizesThatAreCompatibleWithOurImages, sizePredicate)); } catch (NoSuchElementException exception) { - throw new NoSuchElementException("size didn't match: " + toString() - + "\n" + sizes.get()); + throw new NoSuchElementException("size didn't match: " + toString() + "\n" + sizes.get()); } logger.debug("<< matched size(%s)", size); return size; @@ -490,36 +440,44 @@ public class TemplateBuilderImpl implements TemplateBuilder { if (!biggest) sizeOrdering = sizeOrdering.reverse(); if (fastest) - sizeOrdering = Ordering.compound(ImmutableList.of(BY_CORES_ORDERING, - sizeOrdering)); + sizeOrdering = Ordering.compound(ImmutableList.of(BY_CORES_ORDERING, sizeOrdering)); return sizeOrdering; } /** * + * @param size * @throws NoSuchElementException * if there's no image that matches the predicate */ - protected List resolveImages() { - Predicate imagePredicate = buildImagePredicate(); + protected Image resolveImage(final Size size) { + Predicate imagePredicate = and(buildImagePredicate(), new Predicate() { + + @Override + public boolean apply(Image arg0) { + return size.supportsImage(arg0); + } + + }); try { - Iterable matchingImages = Iterables.filter(images - .get(), imagePredicate); + Iterable matchingImages = filter(getImages(), imagePredicate); if (logger.isTraceEnabled()) logger.trace("<< matched images(%s)", matchingImages); - List maxImages = Utils.multiMax( - DEFAULT_IMAGE_ORDERING, matchingImages); + List maxImages = multiMax(DEFAULT_IMAGE_ORDERING, matchingImages); if (logger.isTraceEnabled()) logger.trace("<< best images(%s)", maxImages); - return maxImages; + return maxImages.get(maxImages.size() - 1); } catch (NoSuchElementException exception) { - throw new NoSuchElementException("image didn't match: " + toString() - + "\n" + images.get()); + throw new NoSuchElementException("image didn't match: " + toString() + "\n" + getImages()); } } + protected Set getImages() { + return images.get(); + } + private Predicate buildImagePredicate() { - List> predicates = Lists.newArrayList(); + List> predicates = newArrayList(); if (imageId != null) { predicates.add(idPredicate); } else { @@ -539,7 +497,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { predicates.add(imageDescriptionPredicate); } - Predicate imagePredicate = Predicates.and(predicates); + Predicate imagePredicate = and(predicates); return imagePredicate; } @@ -650,11 +608,9 @@ public class TemplateBuilderImpl implements TemplateBuilder { @VisibleForTesting boolean nothingChangedExceptOptions() { - return os == null && arch == null && locationId == null - && imageId == null && sizeId == null && osDescription == null - && imageVersion == null && imageName == null - && imageDescription == null && minCores == 0 && minRam == 0 - && !biggest && !fastest; + return os == null && arch == null && locationId == null && imageId == null && sizeId == null + && osDescription == null && imageVersion == null && imageName == null && imageDescription == null + && minCores == 0 && minRam == 0 && !biggest && !fastest; } /** @@ -667,11 +623,9 @@ public class TemplateBuilderImpl implements TemplateBuilder { @Override public String toString() { - return "[arch=" + arch + ", biggest=" + biggest + ", fastest=" + fastest - + ", imageName=" + imageName + ", imageDescription=" - + imageDescription + ", imageId=" + imageId + ", imageVersion=" - + imageVersion + ", location=" + locationId + ", minCores=" - + minCores + ", minRam=" + minRam + ", os=" + os + return "[arch=" + arch + ", biggest=" + biggest + ", fastest=" + fastest + ", imageName=" + imageName + + ", imageDescription=" + imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + + ", location=" + locationId + ", minCores=" + minCores + ", minRam=" + minRam + ", os=" + os + ", osDescription=" + osDescription + ", sizeId=" + sizeId + "]"; } diff --git a/compute/src/test/java/org/jclouds/compute/internal/TemplateBuilderImplTest.java b/compute/src/test/java/org/jclouds/compute/internal/TemplateBuilderImplTest.java index 3bf2bec1ca..68e09b218d 100644 --- a/compute/src/test/java/org/jclouds/compute/internal/TemplateBuilderImplTest.java +++ b/compute/src/test/java/org/jclouds/compute/internal/TemplateBuilderImplTest.java @@ -58,17 +58,14 @@ public class TemplateBuilderImplTest { Image image = createMock(Image.class); Image image2 = createMock(Image.class); - Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, - ImmutableMap. of(), 1.0, 0, 0, ImagePredicates - .any()); + Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap. of(), + 1.0, 0, 0, ImagePredicates.any()); - Provider> locations = Providers - .> of(ImmutableSet - . of(defaultLocation)); - Provider> images = Providers - .> of(ImmutableSet. of(image, image2)); - Provider> sizes = Providers - .> of(ImmutableSet. of(size)); + Provider> locations = Providers.> of(ImmutableSet + . of(defaultLocation)); + Provider> images = Providers.> of(ImmutableSet + . of(image, image2)); + Provider> sizes = Providers.> of(ImmutableSet. of(size)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -79,10 +76,8 @@ public class TemplateBuilderImplTest { expect(image2.getVersion()).andReturn("version"); expect(image.getOsDescription()).andReturn("osDescription"); expect(image2.getOsDescription()).andReturn("osDescription"); - expect(image.getArchitecture()).andReturn(Architecture.X86_64) - .atLeastOnce(); - expect(image2.getArchitecture()).andReturn(Architecture.X86_64) - .atLeastOnce(); + expect(image.getArchitecture()).andReturn(Architecture.X86_64).atLeastOnce(); + expect(image2.getArchitecture()).andReturn(Architecture.X86_64).atLeastOnce(); replay(image); replay(image2); @@ -91,10 +86,10 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); - assertEquals(template.resolveImages(), images.get()); + assertEquals(template.resolveImage(size), image2); verify(image); verify(image2); @@ -111,17 +106,14 @@ public class TemplateBuilderImplTest { Image image = createMock(Image.class); Image image2 = createMock(Image.class); - Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, - ImmutableMap. of(), 1.0, 0, 0, ImagePredicates - .any()); + Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap. of(), + 1.0, 0, 0, ImagePredicates.any()); - Provider> locations = Providers - .> of(ImmutableSet - . of(defaultLocation)); - Provider> images = Providers - .> of(ImmutableSet. of(image, image2)); - Provider> sizes = Providers - .> of(ImmutableSet. of(size)); + Provider> locations = Providers.> of(ImmutableSet + . of(defaultLocation)); + Provider> images = Providers.> of(ImmutableSet + . of(image, image2)); + Provider> sizes = Providers.> of(ImmutableSet. of(size)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -130,12 +122,10 @@ public class TemplateBuilderImplTest { expect(optionsProvider.get()).andReturn(new TemplateOptions()); expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce(); - expect(image.getArchitecture()).andReturn(Architecture.X86_32) - .atLeastOnce(); + expect(image.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce(); expect(image2.getLocation()).andReturn(defaultLocation).atLeastOnce(); - expect(image2.getArchitecture()).andReturn(Architecture.X86_64) - .atLeastOnce(); + expect(image2.getArchitecture()).andReturn(Architecture.X86_64).atLeastOnce(); replay(image); replay(image2); @@ -144,11 +134,10 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); - assertEquals(template.smallest().architecture(Architecture.X86_32) - .build().getImage(), image); + assertEquals(template.smallest().architecture(Architecture.X86_32).build().getImage(), image); verify(image); verify(image2); @@ -163,17 +152,13 @@ public class TemplateBuilderImplTest { public void testSizeWithImageIdPredicateOnlyAcceptsImage() { Location defaultLocation = createMock(Location.class); Image image = createMock(Image.class); - Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, - ImmutableMap. of(), 0, 0, 0, ImagePredicates - .idEquals("imageId")); + Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap. of(), 0, + 0, 0, ImagePredicates.idEquals("imageId")); - Provider> locations = Providers - .> of(ImmutableSet - . of(defaultLocation)); - Provider> images = Providers - .> of(ImmutableSet. of(image)); - Provider> sizes = Providers - .> of(ImmutableSet. of(size)); + Provider> locations = Providers.> of(ImmutableSet + . of(defaultLocation)); + Provider> images = Providers.> of(ImmutableSet. of(image)); + Provider> sizes = Providers.> of(ImmutableSet. of(size)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -195,8 +180,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); template.imageId("imageId").build(); @@ -212,17 +197,13 @@ public class TemplateBuilderImplTest { public void testSizeWithImageIdPredicateOnlyDoesntImage() { Location defaultLocation = createMock(Location.class); Image image = createMock(Image.class); - Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, - ImmutableMap. of(), 0, 0, 0, ImagePredicates - .idEquals("imageId")); + Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap. of(), 0, + 0, 0, ImagePredicates.idEquals("imageId")); - Provider> locations = Providers - .> of(ImmutableSet - . of(defaultLocation)); - Provider> images = Providers - .> of(ImmutableSet. of(image)); - Provider> sizes = Providers - .> of(ImmutableSet. of(size)); + Provider> locations = Providers.> of(ImmutableSet + . of(defaultLocation)); + Provider> images = Providers.> of(ImmutableSet. of(image)); + Provider> sizes = Providers.> of(ImmutableSet. of(size)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -230,13 +211,6 @@ public class TemplateBuilderImplTest { expect(defaultLocation.getId()).andReturn("locationId").atLeastOnce(); expect(optionsProvider.get()).andReturn(new TemplateOptions()); expect(image.getId()).andReturn("notImageId").atLeastOnce(); - expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce(); - expect(image.getOsFamily()).andReturn(null); - expect(image.getName()).andReturn(null); - expect(image.getDescription()).andReturn(null); - expect(image.getOsDescription()).andReturn(null); - expect(image.getVersion()).andReturn(null); - expect(image.getArchitecture()).andReturn(null).atLeastOnce(); replay(image); replay(defaultTemplate); @@ -244,8 +218,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); try { template.imageId("notImageId").build(); assert false; @@ -266,10 +240,8 @@ public class TemplateBuilderImplTest { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -285,8 +257,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); template.options(options).build(); @@ -302,10 +274,8 @@ public class TemplateBuilderImplTest { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); @@ -320,8 +290,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); template.build(); @@ -331,14 +301,11 @@ public class TemplateBuilderImplTest { verify(templateBuilderProvider); } - protected TemplateBuilderImpl createTemplateBuilder( - Provider> locations, - Provider> images, - Provider> sizes, Location defaultLocation, - Provider optionsProvider, - Provider templateBuilderProvider) { - TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + protected TemplateBuilderImpl createTemplateBuilder(Provider> locations, + Provider> images, Provider> sizes, Location defaultLocation, + Provider optionsProvider, Provider templateBuilderProvider) { + TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, sizes, defaultLocation, + optionsProvider, templateBuilderProvider); return template; } @@ -347,10 +314,8 @@ public class TemplateBuilderImplTest { public void testSuppliedLocationWithNoOptions() { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -363,8 +328,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); try { template.imageId("foo").locationId("location").build(); @@ -386,10 +351,8 @@ public class TemplateBuilderImplTest { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -400,12 +363,11 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); try { - template.imageId("foo").options(provideTemplateOptions()).locationId( - "location").build(); + template.imageId("foo").options(provideTemplateOptions()).locationId("location").build(); assert false; } catch (NoSuchElementException e) { @@ -421,10 +383,8 @@ public class TemplateBuilderImplTest { public void testDefaultLocationWithNoOptionsNoSuchElement() { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -438,8 +398,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); try { template.imageId("foo").build(); @@ -463,10 +423,8 @@ public class TemplateBuilderImplTest { public void testDefaultLocationWithOptions() { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); TemplateOptions from = provideTemplateOptions(); @@ -489,8 +447,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); try { template.imageId("foo").options(provideTemplateOptions()).build(); @@ -509,10 +467,8 @@ public class TemplateBuilderImplTest { public void testImageIdNullsEverythingElse() { Provider> locations = Providers .> of(ImmutableSet. of()); - Provider> images = Providers - .> of(ImmutableSet. of()); - Provider> sizes = Providers - .> of(ImmutableSet. of()); + Provider> images = Providers.> of(ImmutableSet. of()); + Provider> sizes = Providers.> of(ImmutableSet. of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -521,8 +477,8 @@ public class TemplateBuilderImplTest { replay(optionsProvider); replay(templateBuilderProvider); - TemplateBuilderImpl template = createTemplateBuilder(locations, images, - sizes, defaultLocation, optionsProvider, templateBuilderProvider); + TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, + templateBuilderProvider); template.architecture(Architecture.X86_32); template.imageDescriptionMatches("imageDescriptionMatches"); diff --git a/core/src/main/java/org/jclouds/http/HttpUtils.java b/core/src/main/java/org/jclouds/http/HttpUtils.java index de5094db86..3e67b1e02a 100644 --- a/core/src/main/java/org/jclouds/http/HttpUtils.java +++ b/core/src/main/java/org/jclouds/http/HttpUtils.java @@ -89,8 +89,7 @@ public class HttpUtils { @Inject(optional = true) @Named(Constants.PROPERTY_PROXY_SYSTEM) private boolean systemProxies = System.getProperty("java.net.useSystemProxies") != null ? Boolean - .parseBoolean(System.getProperty("java.net.useSystemProxies")) - : false; + .parseBoolean(System.getProperty("java.net.useSystemProxies")) : false; private final int globalMaxConnections; private final int globalMaxConnectionsPerHost; @@ -112,10 +111,10 @@ public class HttpUtils { @Inject public HttpUtils(EncryptionService encryptionService, - @Named(Constants.PROPERTY_CONNECTION_TIMEOUT) int connectionTimeout, - @Named(Constants.PROPERTY_SO_TIMEOUT) int soTimeout, - @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT) int globalMaxConnections, - @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST) int globalMaxConnectionsPerHost) { + @Named(Constants.PROPERTY_CONNECTION_TIMEOUT) int connectionTimeout, + @Named(Constants.PROPERTY_SO_TIMEOUT) int soTimeout, + @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT) int globalMaxConnections, + @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST) int globalMaxConnectionsPerHost) { this.encryptionService = encryptionService; this.soTimeout = soTimeout; this.connectionTimeout = connectionTimeout; @@ -176,20 +175,20 @@ public class HttpUtils { } /** - * keys to the map are only used for socket information, not path. In this case, you should - * remove any path or query details from the URI. + * keys to the map are only used for socket information, not path. In this + * case, you should remove any path or query details from the URI. */ public static URI createBaseEndpointFor(URI endpoint) { if (endpoint.getPort() == -1) { return URI.create(String.format("%s://%s", endpoint.getScheme(), endpoint.getHost())); } else { - return URI.create(String.format("%s://%s:%d", endpoint.getScheme(), endpoint.getHost(), - endpoint.getPort())); + return URI.create(String.format("%s://%s:%d", endpoint.getScheme(), endpoint.getHost(), endpoint.getPort())); } } /** - * Web browsers do not always handle '+' characters well, use the well-supported '%20' instead. + * Web browsers do not always handle '+' characters well, use the + * well-supported '%20' instead. */ public static String urlEncode(String in, char... skipEncode) { if (isUrlEncoded(in)) @@ -235,7 +234,8 @@ public class HttpUtils { } /** - * Content stream may need to be read. However, we should always close the http stream. + * Content stream may need to be read. However, we should always close the + * http stream. * * @throws IOException */ @@ -255,12 +255,11 @@ public class HttpUtils { String scheme = redirectURI.getScheme(); checkState(redirectURI.getScheme().startsWith("http"), String.format( - "header %s didn't parse an http scheme: [%s]", hostHeader, scheme)); - int port = redirectURI.getPort() > 0 ? redirectURI.getPort() : redirectURI.getScheme() - .equals("https") ? 443 : 80; + "header %s didn't parse an http scheme: [%s]", hostHeader, scheme)); + int port = redirectURI.getPort() > 0 ? redirectURI.getPort() : redirectURI.getScheme().equals("https") ? 443 : 80; String host = redirectURI.getHost(); - checkState(host.indexOf('/') == -1, String.format( - "header %s didn't parse an http host correctly: [%s]", hostHeader, host)); + checkState(host.indexOf('/') == -1, String.format("header %s didn't parse an http host correctly: [%s]", + hostHeader, host)); URI endPoint = URI.create(String.format("%s://%s:%d", scheme, host, port)); return endPoint; } @@ -270,10 +269,11 @@ public class HttpUtils { } /** - * Used to extract the URI and authentication data from a String. Note that the java URI class - * breaks, if there are special characters like '/' present. Otherwise, we wouldn't need this - * class, and we could simply use URI.create("uri").getUserData(); Also, URI breaks if there are - * curly braces. + * Used to extract the URI and authentication data from a String. Note that + * the java URI class breaks, if there are special characters like '/' + * present. Otherwise, we wouldn't need this class, and we could simply use + * URI.create("uri").getUserData(); Also, URI breaks if there are curly + * braces. * */ public static URI createUri(String uriPath) { @@ -305,8 +305,7 @@ public class HttpUtils { String rest = matcher.group(4); String identity = matcher.group(2); String key = matcher.group(3); - return URI.create(String.format("%s://%s:%s@%s", scheme, urlEncode(identity), - urlEncode(key), rest)); + return URI.create(String.format("%s://%s:%s@%s", scheme, urlEncode(identity), urlEncode(key), rest)); } else { throw new IllegalArgumentException("bad syntax"); } @@ -329,14 +328,12 @@ public class HttpUtils { } if (message.getPayload() != null) { if (message.getPayload().getContentType() != null) - logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_TYPE, message.getPayload() - .getContentType()); + logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_TYPE, message.getPayload().getContentType()); if (message.getPayload().getContentLength() != null) - logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_LENGTH, message.getPayload() - .getContentLength()); + logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_LENGTH, message.getPayload().getContentLength()); if (message.getPayload().getContentMD5() != null) - logger.debug("%s %s: %s", prefix, "Content-MD5", encryptionService.base64(message - .getPayload().getContentMD5())); + logger.debug("%s %s: %s", prefix, "Content-MD5", encryptionService.base64(message.getPayload() + .getContentMD5())); } } @@ -359,12 +356,13 @@ public class HttpUtils { } /** - * change the destination of the current http command. typically used in handling redirects. + * change the destination of the current http command. typically used in + * handling redirects. * * @param string */ - public static void changeSchemeHostAndPortTo(HttpRequest request, String scheme, String host, - int port, UriBuilder builder) { + public static void changeSchemeHostAndPortTo(HttpRequest request, String scheme, String host, int port, + UriBuilder builder) { builder.uri(request.getEndpoint()); builder.scheme(scheme); builder.host(host); @@ -389,18 +387,16 @@ public class HttpUtils { request.setMethod(HttpMethod.GET); } - public static void addQueryParamTo(HttpRequest request, String key, Object value, - UriBuilder builder) { + public static void addQueryParamTo(HttpRequest request, String key, Object value, UriBuilder builder) { addQueryParamTo(request, key, ImmutableSet. of(value), builder, request.getSkips()); } - public static void addQueryParamTo(HttpRequest request, String key, Iterable values, - UriBuilder builder) { + public static void addQueryParamTo(HttpRequest request, String key, Iterable values, UriBuilder builder) { addQueryParamTo(request, key, values, builder, request.getSkips()); } - public static void addQueryParamTo(HttpRequest request, String key, Iterable values, - UriBuilder builder, char... skips) { + public static void addQueryParamTo(HttpRequest request, String key, Iterable values, UriBuilder builder, + char... skips) { builder.uri(request.getEndpoint()); Multimap map = parseQueryToMap(request.getEndpoint().getQuery()); for (Object o : values) @@ -409,13 +405,11 @@ public class HttpUtils { request.setEndpoint(builder.build()); } - public static void replaceMatrixParam(HttpRequest request, String name, Object value, - UriBuilder builder) { + public static void replaceMatrixParam(HttpRequest request, String name, Object value, UriBuilder builder) { replaceMatrixParam(request, name, new Object[] { value }, builder); } - public static void replaceMatrixParam(HttpRequest request, String name, Object[] values, - UriBuilder builder) { + public static void replaceMatrixParam(HttpRequest request, String name, Object[] values, UriBuilder builder) { builder.uri(request.getEndpoint()); builder.replaceMatrixParam(name, values); request.setEndpoint(builder.build()); @@ -451,28 +445,25 @@ public class HttpUtils { return map; } - public static void parseKeyValueFromStringToMap(String stringToParse, - Multimap map) { + public static void parseKeyValueFromStringToMap(String stringToParse, Multimap map) { // note that '=' can be a valid part of the value int indexOfFirstEquals = stringToParse.indexOf('='); - String key = indexOfFirstEquals == -1 ? stringToParse : stringToParse.substring(0, - indexOfFirstEquals); - String value = indexOfFirstEquals == -1 ? null : stringToParse - .substring(indexOfFirstEquals + 1); + String key = indexOfFirstEquals == -1 ? stringToParse : stringToParse.substring(0, indexOfFirstEquals); + String value = indexOfFirstEquals == -1 ? null : stringToParse.substring(indexOfFirstEquals + 1); map.put(key, value); } - public static SortedSet> sortEntries( - Collection> in, Comparator> sorter) { + public static SortedSet> sortEntries(Collection> in, + Comparator> sorter) { SortedSet> entries = newTreeSet(sorter); entries.addAll(in); return entries; } public static String makeQueryLine(Multimap params, - @Nullable Comparator> sorter, char... skips) { - Iterator> pairs = ((sorter == null) ? params.entries() - : sortEntries(params.entries(), sorter)).iterator(); + @Nullable Comparator> sorter, char... skips) { + Iterator> pairs = ((sorter == null) ? params.entries() : sortEntries(params.entries(), + sorter)).iterator(); StringBuilder formBuilder = new StringBuilder(); while (pairs.hasNext()) { Map.Entry pair = pairs.next(); @@ -492,8 +483,7 @@ public class HttpUtils { boolean chunked = any(headers.entries(), new Predicate>() { @Override public boolean apply(Entry input) { - return "Transfer-Encoding".equalsIgnoreCase(input.getKey()) - && "chunked".equalsIgnoreCase(input.getValue()); + return "Transfer-Encoding".equalsIgnoreCase(input.getKey()) && "chunked".equalsIgnoreCase(input.getValue()); } }); @@ -514,25 +504,20 @@ public class HttpUtils { if (message instanceof HttpRequest) { checkArgument( - message.getPayload() == null - || message.getFirstHeaderOrNull(CONTENT_TYPE) == null, - "configuration error please use request.getPayload().setContentType(value) as opposed to adding a content type header: " - + message); + message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_TYPE) == null, + "configuration error please use request.getPayload().setContentType(value) as opposed to adding a content type header: " + + message); checkArgument( - message.getPayload() == null - || message.getFirstHeaderOrNull(CONTENT_LENGTH) == null, - "configuration error please use request.getPayload().setContentLength(value) as opposed to adding a content length header: " - + message); - checkArgument(message.getPayload() == null - || message.getPayload().getContentLength() != null - || "chunked".equalsIgnoreCase(message.getFirstHeaderOrNull("Transfer-Encoding")), - "either chunked encoding must be set on the http request or contentlength set on the payload: " - + message); - checkArgument( - message.getPayload() == null - || message.getFirstHeaderOrNull("Content-MD5") == null, - "configuration error please use request.getPayload().setContentMD5(value) as opposed to adding a content md5 header: " - + message); + message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_LENGTH) == null, + "configuration error please use request.getPayload().setContentLength(value) as opposed to adding a content length header: " + + message); + checkArgument(message.getPayload() == null || message.getPayload().getContentLength() != null + || "chunked".equalsIgnoreCase(message.getFirstHeaderOrNull("Transfer-Encoding")), + "either chunked encoding must be set on the http request or contentlength set on the payload: " + + message); + checkArgument(message.getPayload() == null || message.getFirstHeaderOrNull("Content-MD5") == null, + "configuration error please use request.getPayload().setContentMD5(value) as opposed to adding a content md5 header: " + + message); } } @@ -555,7 +540,7 @@ public class HttpUtils { public static Long attemptToParseSizeAndRangeFromHeaders(HttpResponse from) throws HttpException { String contentRange = from.getFirstHeaderOrNull("Content-Range"); - if (contentRange == null) { + if (contentRange == null && from.getPayload() != null) { return from.getPayload().getContentLength(); } else if (contentRange != null) { return Long.parseLong(contentRange.substring(contentRange.lastIndexOf('/') + 1)); diff --git a/core/src/main/java/org/jclouds/http/functions/ParseJson.java b/core/src/main/java/org/jclouds/http/functions/ParseJson.java index 524f3ef50d..1eb8f4f261 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseJson.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseJson.java @@ -21,6 +21,8 @@ package org.jclouds.http.functions; import static org.jclouds.http.HttpUtils.releasePayload; import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; import javax.annotation.Resource; import javax.inject.Inject; @@ -32,23 +34,26 @@ import org.jclouds.logging.Logger; import com.google.common.base.Function; import com.google.gson.Gson; +import com.google.inject.TypeLiteral; /** - * This object will parse the body of an HttpResponse and return the result of type back to the - * caller. + * This object will parse the body of an HttpResponse and return the result of + * type back to the caller. * * @author Adrian Cole */ @Singleton -public abstract class ParseJson implements Function { +public class ParseJson implements Function { @Resource protected Logger logger = Logger.NULL; protected final Gson gson; + protected final TypeLiteral type; @Inject - public ParseJson(Gson gson){ + public ParseJson(Gson gson, TypeLiteral type) { this.gson = gson; + this.type = type; } /** @@ -62,12 +67,21 @@ public abstract class ParseJson implements Function { StringBuilder message = new StringBuilder(); message.append("Error parsing input"); logger.error(e, message.toString()); - throw new HttpResponseException(message.toString() + "\n" + from, null, from, e); + throw new HttpResponseException(message.toString() + "\n" + from, + null, from, e); } finally { releasePayload(from); } } - protected abstract T apply(InputStream stream); + @SuppressWarnings("unchecked") + public T apply(InputStream stream) { + try { + return (T) gson.fromJson(new InputStreamReader(stream, "UTF-8"), type + .getType()); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("jclouds requires UTF-8 encoding", e); + } + } } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponse.java b/core/src/main/java/org/jclouds/http/functions/UnwrapOnlyJsonValue.java similarity index 52% rename from rackspace/src/main/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponse.java rename to core/src/main/java/org/jclouds/http/functions/UnwrapOnlyJsonValue.java index fe36d1b176..936ee755a4 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponse.java +++ b/core/src/main/java/org/jclouds/http/functions/UnwrapOnlyJsonValue.java @@ -16,42 +16,34 @@ * limitations under the License. * ==================================================================== */ -package org.jclouds.rackspace.cloudservers.functions; +package org.jclouds.http.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; +import java.util.Map; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.rackspace.cloudservers.domain.Image; - -import com.google.gson.Gson; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.http.HttpResponse; + +import com.google.common.base.Function; +import com.google.inject.internal.Iterables; + /** - * This parses {@link Image} from a gson string. - * * @author Adrian Cole */ @Singleton -public class ParseImageFromJsonResponse extends ParseJson { +public class UnwrapOnlyJsonValue implements Function { + + private final ParseJson> json; @Inject - public ParseImageFromJsonResponse(Gson gson) { - super(gson); + UnwrapOnlyJsonValue(ParseJson> json) { + this.json = json; } - private static class ImageListResponse { - Image image; - } - - public Image apply(InputStream stream) { - - try { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), ImageListResponse.class).image; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } + @Override + public T apply(HttpResponse arg0) { + Map map = json.apply(arg0); + return Iterables.getOnlyElement(map.values()); } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/http/functions/config/ParserModule.java b/core/src/main/java/org/jclouds/http/functions/config/ParserModule.java index bbc9c9f6fc..4b410936d6 100755 --- a/core/src/main/java/org/jclouds/http/functions/config/ParserModule.java +++ b/core/src/main/java/org/jclouds/http/functions/config/ParserModule.java @@ -20,6 +20,7 @@ package org.jclouds.http.functions.config; import java.lang.reflect.Type; import java.util.Date; +import java.util.List; import java.util.Map; import javax.inject.Inject; @@ -29,11 +30,13 @@ import javax.xml.parsers.SAXParserFactory; import org.jclouds.Constants; import org.jclouds.date.DateService; +import org.jclouds.encryption.EncryptionService; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax.HandlerWithResult; import org.xml.sax.XMLReader; import com.google.common.collect.Maps; +import com.google.common.primitives.Bytes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; @@ -43,6 +46,7 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import com.google.gson.reflect.TypeToken; import com.google.inject.AbstractModule; import com.google.inject.ImplementedBy; import com.google.inject.Provides; @@ -88,9 +92,13 @@ public class ParserModule extends AbstractModule { @Provides @Singleton - Gson provideGson(DateAdapter adapter, GsonAdapterBindings bindings) { + Gson provideGson(DateAdapter adapter, ByteListAdapter byteListAdapter, + ByteArrayAdapter byteArrayAdapter, GsonAdapterBindings bindings) { GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(Date.class, adapter); + gson.registerTypeAdapter(new TypeToken>() { + }.getType(), byteListAdapter); + gson.registerTypeAdapter(byte[].class, byteArrayAdapter); for (Map.Entry binding : bindings.getBindings().entrySet()) { gson.registerTypeAdapter(binding.getKey(), binding.getValue()); } @@ -98,10 +106,68 @@ public class ParserModule extends AbstractModule { } @ImplementedBy(CDateAdapter.class) - public static interface DateAdapter extends JsonSerializer, JsonDeserializer { + public static interface DateAdapter extends JsonSerializer, + JsonDeserializer { } + @ImplementedBy(HexByteListAdapter.class) + public static interface ByteListAdapter extends JsonSerializer>, + JsonDeserializer> { + + } + + @ImplementedBy(HexByteArrayAdapter.class) + public static interface ByteArrayAdapter extends JsonSerializer, + JsonDeserializer { + + } + + @Singleton + public static class HexByteListAdapter implements ByteListAdapter { + private final EncryptionService encryptionService; + + @Inject + HexByteListAdapter(EncryptionService encryptionService) { + this.encryptionService = encryptionService; + } + + @Override + public List deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { + return Bytes.asList(encryptionService.fromHex(json.getAsString())); + } + + @Override + public JsonElement serialize(List src, Type typeOfSrc, + JsonSerializationContext context) { + return new JsonPrimitive(encryptionService.hex(Bytes.toArray(src))); + } + + } + + @Singleton + public static class HexByteArrayAdapter implements ByteArrayAdapter { + private final EncryptionService encryptionService; + + @Inject + HexByteArrayAdapter(EncryptionService encryptionService) { + this.encryptionService = encryptionService; + } + + @Override + public byte[] deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { + return encryptionService.fromHex(json.getAsString()); + } + + @Override + public JsonElement serialize(byte[] src, Type typeOfSrc, + JsonSerializationContext context) { + return new JsonPrimitive(encryptionService.hex(src)); + } + } + @Singleton public static class Iso8601DateAdapter implements DateAdapter { private final DateService dateService; @@ -111,12 +177,13 @@ public class ParserModule extends AbstractModule { this.dateService = dateService; } - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(Date src, Type typeOfSrc, + JsonSerializationContext context) { return new JsonPrimitive(dateService.iso8601DateFormat(src)); } - public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + public Date deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { String toParse = json.getAsJsonPrimitive().getAsString(); try { return dateService.iso8601DateParse(toParse); @@ -136,12 +203,13 @@ public class ParserModule extends AbstractModule { this.dateService = dateService; } - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(Date src, Type typeOfSrc, + JsonSerializationContext context) { return new JsonPrimitive(dateService.cDateFormat(src)); } - public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + public Date deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { String toParse = json.getAsJsonPrimitive().getAsString(); Date toReturn = dateService.cDateParse(toParse); return toReturn; @@ -152,12 +220,13 @@ public class ParserModule extends AbstractModule { @Singleton public static class LongDateAdapter implements DateAdapter { - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(Date src, Type typeOfSrc, + JsonSerializationContext context) { return new JsonPrimitive(src.getTime()); } - public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + public Date deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { long toParse = json.getAsJsonPrimitive().getAsLong(); Date toReturn = new Date(toParse); return toReturn; @@ -170,7 +239,8 @@ public class ParserModule extends AbstractModule { private final Map bindings = Maps.newHashMap(); @com.google.inject.Inject(optional = true) - public void setBindings(@Named(Constants.PROPERTY_GSON_ADAPTERS) Map bindings) { + public void setBindings( + @Named(Constants.PROPERTY_GSON_ADAPTERS) Map bindings) { this.bindings.putAll(bindings); } diff --git a/core/src/main/java/org/jclouds/rest/annotations/Unwrap.java b/core/src/main/java/org/jclouds/rest/annotations/Unwrap.java new file mode 100644 index 0000000000..6d98a5ca41 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/annotations/Unwrap.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.jclouds.rest.annotations; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Unwraps the only value in the json reponse + * + * ex. { "foo" :"bar" } becomes "bar" + * + * @author Adrian Cole + */ +@Target(METHOD) +@Retention(RUNTIME) +public @interface Unwrap { +} diff --git a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java index 5e4c9f1e48..c64aec1792 100755 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -41,8 +41,12 @@ import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; import java.net.URI; import java.util.Collection; +import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; @@ -62,6 +66,7 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; @@ -73,12 +78,14 @@ import org.jclouds.http.HttpUtils; import org.jclouds.http.Payload; import org.jclouds.http.PayloadEnclosing; import org.jclouds.http.Payloads; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReturnInputStream; import org.jclouds.http.functions.ReturnStringIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.functions.ParseSax.HandlerWithResult; import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.http.payloads.MultipartForm; @@ -106,6 +113,7 @@ import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.Unwrap; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; @@ -123,6 +131,7 @@ import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; +import com.google.inject.util.Types; /** * Creates http methods based on annotations on a class or interface. @@ -151,37 +160,30 @@ public class RestAnnotationProcessor { static Map>> createMethodToIndexOfParamToAnnotation( final Class annotation) { - return new MapMaker() - .makeComputingMap(new Function>>() { - public Map> apply(final Method method) { - return new MapMaker() - .makeComputingMap(new GetAnnotationsForMethodParameterIndex( - method, annotation)); - } - }); + return new MapMaker().makeComputingMap(new Function>>() { + public Map> apply(final Method method) { + return new MapMaker().makeComputingMap(new GetAnnotationsForMethodParameterIndex(method, annotation)); + } + }); } - static class GetAnnotationsForMethodParameterIndex implements - Function> { + static class GetAnnotationsForMethodParameterIndex implements Function> { private final Method method; private final Class clazz; - protected GetAnnotationsForMethodParameterIndex(Method method, - Class clazz) { + protected GetAnnotationsForMethodParameterIndex(Method method, Class clazz) { this.method = method; this.clazz = clazz; } public Set apply(final Integer index) { Set keys = new HashSet(); - List parameterAnnotations = newArrayList(method - .getParameterAnnotations()[index]); - Collection filtered = filter(parameterAnnotations, - new Predicate() { - public boolean apply(Annotation input) { - return input.annotationType().equals(clazz); - } - }); + List parameterAnnotations = newArrayList(method.getParameterAnnotations()[index]); + Collection filtered = filter(parameterAnnotations, new Predicate() { + public boolean apply(Annotation input) { + return input.annotationType().equals(clazz); + } + }); for (Annotation annotation : filtered) { keys.add(annotation); } @@ -208,8 +210,7 @@ public class RestAnnotationProcessor { Set toReturn = newHashSet(); for (int index = 0; index < method.getParameterTypes().length; index++) { Class type = method.getParameterTypes()[index]; - if (HttpRequestOptions.class.isAssignableFrom(type) - || optionsVarArgsClass.isAssignableFrom(type)) + if (HttpRequestOptions.class.isAssignableFrom(type) || optionsVarArgsClass.isAssignableFrom(type)) toReturn.add(index); } return toReturn; @@ -226,15 +227,13 @@ public class RestAnnotationProcessor { private InputParamValidator inputParamValidator; @VisibleForTesting - Function createResponseParser(Method method, - HttpRequest request) { + Function createResponseParser(Method method, HttpRequest request) { return createResponseParser(parserFactory, injector, method, request); } @VisibleForTesting - public static Function createResponseParser( - ParseSax.Factory parserFactory, Injector injector, Method method, - HttpRequest request) { + public static Function createResponseParser(ParseSax.Factory parserFactory, Injector injector, + Method method, HttpRequest request) { Function transformer; Class> handler = getSaxResponseParserClassOrNull(method); if (handler != null) { @@ -243,17 +242,14 @@ public class RestAnnotationProcessor { transformer = injector.getInstance(getParserOrThrowException(method)); } if (transformer instanceof InvocationContext) { - ((InvocationContext) transformer) - .setContext((GeneratedHttpRequest) request); + ((InvocationContext) transformer).setContext((GeneratedHttpRequest) request); } return transformer; } @VisibleForTesting - Function createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation( - Method method) { - return createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation( - injector, method); + Function createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(Method method) { + return createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(injector, method); } @VisibleForTesting @@ -268,8 +264,7 @@ public class RestAnnotationProcessor { @SuppressWarnings("unchecked") @Inject - public RestAnnotationProcessor(Injector injector, - ParseSax.Factory parserFactory, HttpUtils utils, + public RestAnnotationProcessor(Injector injector, ParseSax.Factory parserFactory, HttpUtils utils, TypeLiteral typeLiteral) { this.declaring = (Class) typeLiteral.getRawType(); this.injector = injector; @@ -294,27 +289,17 @@ public class RestAnnotationProcessor { for (Method method : methods) { if (isHttpMethod(method)) { for (int index = 0; index < method.getParameterTypes().length; index++) { - methodToIndexOfParamToDecoratorParamAnnotation.get(method).get( - index); - methodToIndexOfParamToHeaderParamAnnotations.get(method).get( - index); - methodToIndexOfParamToMatrixParamAnnotations.get(method).get( - index); - methodToIndexOfParamToFormParamAnnotations.get(method) - .get(index); - methodToIndexOfParamToQueryParamAnnotations.get(method).get( - index); + methodToIndexOfParamToDecoratorParamAnnotation.get(method).get(index); + methodToIndexOfParamToHeaderParamAnnotations.get(method).get(index); + methodToIndexOfParamToMatrixParamAnnotations.get(method).get(index); + methodToIndexOfParamToFormParamAnnotations.get(method).get(index); + methodToIndexOfParamToQueryParamAnnotations.get(method).get(index); methodToIndexOfParamToEndpointAnnotations.get(method).get(index); - methodToIndexOfParamToEndpointParamAnnotations.get(method).get( - index); - methodToIndexOfParamToPathParamAnnotations.get(method) - .get(index); - methodToIndexOfParamToPostParamAnnotations.get(method) - .get(index); - methodToIndexOfParamToParamParserAnnotations.get(method).get( - index); - methodToIndexOfParamToPartParamAnnotations.get(method) - .get(index); + methodToIndexOfParamToEndpointParamAnnotations.get(method).get(index); + methodToIndexOfParamToPathParamAnnotations.get(method).get(index); + methodToIndexOfParamToPostParamAnnotations.get(method).get(index); + methodToIndexOfParamToParamParserAnnotations.get(method).get(index); + methodToIndexOfParamToPartParamAnnotations.get(method).get(index); methodToIndexesOfOptions.get(method); } delegationMap.put(new MethodKey(method), method); @@ -325,9 +310,7 @@ public class RestAnnotationProcessor { } else if (method.isAnnotationPresent(Delegate.class)) { logger.debug("skipping delegate method %s", method); } else if (!method.getName().startsWith("new")) { - logger.trace( - "Method is not annotated as either http or constant: %s", - method); + logger.trace("Method is not annotated as either http or constant: %s", method); } } } @@ -381,8 +364,7 @@ public class RestAnnotationProcessor { seedCache(caller.getMethod().getDeclaringClass()); this.caller = caller; try { - callerEndpoint = getEndpointFor(caller.getMethod(), caller.getArgs(), - injector); + callerEndpoint = getEndpointFor(caller.getMethod(), caller.getArgs(), injector); } catch (IllegalStateException e) { } } @@ -395,8 +377,7 @@ public class RestAnnotationProcessor { if (endpoint == null) endpoint = getEndpointFor(method, args, injector); } catch (IllegalStateException e) { - endpoint = injector.getInstance(Key.get(URI.class, - org.jclouds.rest.annotations.Provider.class)); + endpoint = injector.getInstance(Key.get(URI.class, org.jclouds.rest.annotations.Provider.class)); } String httpMethod = getHttpMethodOrConstantOrThrowException(method); @@ -405,44 +386,32 @@ public class RestAnnotationProcessor { Multimap tokenValues = LinkedHashMultimap.create(); if (caller != null) { - builder.path(getPath(caller.getMethod().getDeclaringClass(), caller - .getMethod(), caller.getArgs())); + builder.path(getPath(caller.getMethod().getDeclaringClass(), caller.getMethod(), caller.getArgs())); } tokenValues.putAll(addPathAndGetTokens(declaring, method, args, builder)); - Multimap formParams = addFormParams( - tokenValues.entries(), method, args); - Multimap queryParams = addQueryParams(tokenValues - .entries(), method, args); + Multimap formParams = addFormParams(tokenValues.entries(), method, args); + Multimap queryParams = addQueryParams(tokenValues.entries(), method, args); addMatrixParams(builder, tokenValues.entries(), method, args); - Multimap headers = buildHeaders(tokenValues.entries(), - method, args); + Multimap headers = buildHeaders(tokenValues.entries(), method, args); Payload payload = null; HttpRequestOptions options = findOptionsIn(method, args); if (options != null) { injector.injectMembers(options);// TODO test case - for (Entry header : options.buildRequestHeaders() - .entries()) { - headers.put(header.getKey(), replaceTokens(header.getValue(), - tokenValues.entries())); + for (Entry header : options.buildRequestHeaders().entries()) { + headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues.entries())); } - for (Entry matrix : options.buildMatrixParameters() - .entries()) { - builder.matrixParam(matrix.getKey(), replaceTokens(matrix - .getValue(), tokenValues.entries())); + for (Entry matrix : options.buildMatrixParameters().entries()) { + builder.matrixParam(matrix.getKey(), replaceTokens(matrix.getValue(), tokenValues.entries())); } - for (Entry query : options.buildQueryParameters() - .entries()) { - queryParams.put(query.getKey(), replaceTokens(query.getValue(), - tokenValues.entries())); + for (Entry query : options.buildQueryParameters().entries()) { + queryParams.put(query.getKey(), replaceTokens(query.getValue(), tokenValues.entries())); } - for (Entry form : options.buildFormParameters() - .entries()) { - formParams.put(form.getKey(), replaceTokens(form.getValue(), - tokenValues.entries())); + for (Entry form : options.buildFormParameters().entries()) { + formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues.entries())); } String pathSuffix = options.buildPathSuffix(); @@ -466,20 +435,17 @@ public class RestAnnotationProcessor { throw new IllegalStateException(e); } - GeneratedHttpRequest request = new GeneratedHttpRequest(httpMethod, - endpoint, skips, declaring, method, args); - addHostHeaderIfAnnotatedWithVirtualHost(headers, request.getEndpoint() - .getHost(), method); + GeneratedHttpRequest request = new GeneratedHttpRequest(httpMethod, endpoint, skips, declaring, method, + args); + addHostHeaderIfAnnotatedWithVirtualHost(headers, request.getEndpoint().getHost(), method); addFiltersIfAnnotated(method, request); if (payload == null) payload = findPayloadInArgs(args); - List parts = getParts(method, args, Iterables.concat( - tokenValues.entries(), formParams.entries())); + List parts = getParts(method, args, Iterables.concat(tokenValues.entries(), formParams.entries())); if (parts.size() > 0) { if (formParams.size() > 0) { - parts = newLinkedList(Iterables.concat(Iterables.transform( - formParams.entries(), ENTRY_TO_PART), parts)); + parts = newLinkedList(Iterables.concat(Iterables.transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(BOUNDARY, parts); } else if (formParams.size() > 0) { @@ -499,35 +465,29 @@ public class RestAnnotationProcessor { if (clazz.isAnnotationPresent(Path.class)) builder.path(clazz); builder.path(method); - return builder.buildFromEncodedMap( - convertUnsafe(encodeValues(getPathParamKeyValues(method, args), - skips))).getPath(); + return builder.buildFromEncodedMap(convertUnsafe(encodeValues(getPathParamKeyValues(method, args), skips))) + .getPath(); } - private Multimap addPathAndGetTokens(Class clazz, - Method method, Object[] args, UriBuilder builder) { + private Multimap addPathAndGetTokens(Class clazz, Method method, Object[] args, UriBuilder builder) { if (clazz.isAnnotationPresent(Path.class)) builder.path(clazz); builder.path(method); return encodeValues(getPathParamKeyValues(method, args), skips); } - public URI replaceQuery(URI in, String newQuery, - @Nullable Comparator> sorter) { + public URI replaceQuery(URI in, String newQuery, @Nullable Comparator> sorter) { return replaceQuery(uriBuilderProvider, in, newQuery, sorter, skips); } - public static URI replaceQuery(Provider uriBuilderProvider, - URI in, String newQuery, + public static URI replaceQuery(Provider uriBuilderProvider, URI in, String newQuery, @Nullable Comparator> sorter, char... skips) { UriBuilder builder = uriBuilderProvider.get().uri(in); - builder.replaceQuery(makeQueryLine(parseQueryToMap(newQuery), sorter, - skips)); + builder.replaceQuery(makeQueryLine(parseQueryToMap(newQuery), sorter, skips)); return builder.build(); } - private void addMatrixParams(UriBuilder builder, - Collection> tokenValues, Method method, + private void addMatrixParams(UriBuilder builder, Collection> tokenValues, Method method, Object... args) { if (declaring.isAnnotationPresent(MatrixParams.class)) { MatrixParams matrix = declaring.getAnnotation(MatrixParams.class); @@ -539,15 +499,12 @@ public class RestAnnotationProcessor { addMatrix(builder, matrix, tokenValues); } - for (Entry matrix : getMatrixParamKeyValues(method, args) - .entries()) { - builder.matrixParam(matrix.getKey(), replaceTokens(matrix.getValue(), - tokenValues)); + for (Entry matrix : getMatrixParamKeyValues(method, args).entries()) { + builder.matrixParam(matrix.getKey(), replaceTokens(matrix.getValue(), tokenValues)); } } - private Multimap addFormParams( - Collection> tokenValues, Method method, + private Multimap addFormParams(Collection> tokenValues, Method method, Object... args) { Multimap formMap = LinkedListMultimap.create(); if (declaring.isAnnotationPresent(FormParams.class)) { @@ -560,16 +517,13 @@ public class RestAnnotationProcessor { addForm(formMap, form, tokenValues); } - for (Entry form : getFormParamKeyValues(method, args) - .entries()) { - formMap - .put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); + for (Entry form : getFormParamKeyValues(method, args).entries()) { + formMap.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } return formMap; } - private Multimap addQueryParams( - Collection> tokenValues, Method method, + private Multimap addQueryParams(Collection> tokenValues, Method method, Object... args) { Multimap queryMap = LinkedListMultimap.create(); if (declaring.isAnnotationPresent(QueryParams.class)) { @@ -582,10 +536,8 @@ public class RestAnnotationProcessor { addQuery(queryMap, query, tokenValues); } - for (Entry query : getQueryParamKeyValues(method, args) - .entries()) { - queryMap.put(query.getKey(), replaceTokens(query.getValue(), - tokenValues)); + for (Entry query : getQueryParamKeyValues(method, args).entries()) { + queryMap.put(query.getKey(), replaceTokens(query.getValue(), tokenValues)); } return queryMap; } @@ -597,102 +549,82 @@ public class RestAnnotationProcessor { formParams.removeAll(form.keys()[i]); formParams.put(form.keys()[i], null); } else { - formParams.put(form.keys()[i], replaceTokens(form.values()[i], - tokenValues)); + formParams.put(form.keys()[i], replaceTokens(form.values()[i], tokenValues)); } } } - private void addQuery(Multimap queryParams, - QueryParams query, Collection> tokenValues) { + private void addQuery(Multimap queryParams, QueryParams query, + Collection> tokenValues) { for (int i = 0; i < query.keys().length; i++) { if (query.values()[i].equals(QueryParams.NULL)) { queryParams.removeAll(query.keys()[i]); queryParams.put(query.keys()[i], null); } else { - queryParams.put(query.keys()[i], replaceTokens(query.values()[i], - tokenValues)); + queryParams.put(query.keys()[i], replaceTokens(query.values()[i], tokenValues)); } } } - private void addMatrix(UriBuilder builder, MatrixParams matrix, - Collection> tokenValues) { + private void addMatrix(UriBuilder builder, MatrixParams matrix, Collection> tokenValues) { for (int i = 0; i < matrix.keys().length; i++) { if (matrix.values()[i].equals(MatrixParams.NULL)) { builder.replaceMatrix(matrix.keys()[i]); } else { - builder.matrixParam(matrix.keys()[i], replaceTokens( - matrix.values()[i], tokenValues)); + builder.matrixParam(matrix.keys()[i], replaceTokens(matrix.values()[i], tokenValues)); } } } private void addFiltersIfAnnotated(Method method, HttpRequest request) { if (declaring.isAnnotationPresent(RequestFilters.class)) { - for (Class clazz : declaring - .getAnnotation(RequestFilters.class).value()) { + for (Class clazz : declaring.getAnnotation(RequestFilters.class).value()) { HttpRequestFilter instance = injector.getInstance(clazz); request.getFilters().add(instance); - logger.trace("%s - adding filter %s from annotation on %s", - request, instance, declaring.getName()); + logger.trace("%s - adding filter %s from annotation on %s", request, instance, declaring.getName()); } } if (method.isAnnotationPresent(RequestFilters.class)) { if (method.isAnnotationPresent(OverrideRequestFilters.class)) request.getFilters().clear(); - for (Class clazz : method.getAnnotation( - RequestFilters.class).value()) { + for (Class clazz : method.getAnnotation(RequestFilters.class).value()) { HttpRequestFilter instance = injector.getInstance(clazz); request.getFilters().add(instance); - logger.trace("%s - adding filter %s from annotation on %s", - request, instance, method.getName()); + logger.trace("%s - adding filter %s from annotation on %s", request, instance, method.getName()); } } } @VisibleForTesting - public static URI getEndpointInParametersOrNull(Method method, - Object[] args, Injector injector) { - Map> map = RestAnnotationProcessor - .indexWithOnlyOneAnnotation( - method, - "@EndpointParam", - RestAnnotationProcessor.methodToIndexOfParamToEndpointParamAnnotations); + public static URI getEndpointInParametersOrNull(Method method, Object[] args, Injector injector) { + Map> map = RestAnnotationProcessor.indexWithOnlyOneAnnotation(method, "@EndpointParam", + RestAnnotationProcessor.methodToIndexOfParamToEndpointParamAnnotations); if (map.size() == 1 && args.length > 0) { - EndpointParam annotation = (EndpointParam) map.values().iterator() - .next().iterator().next(); + EndpointParam annotation = (EndpointParam) map.values().iterator().next().iterator().next(); int index = map.keySet().iterator().next(); - Function parser = injector.getInstance(annotation - .parser()); + Function parser = injector.getInstance(annotation.parser()); try { URI returnVal = parser.apply(args[index]); - checkArgument(returnVal != null, String.format( - "endpoint for [%s] not configured for %s", args[index], + checkArgument(returnVal != null, String.format("endpoint for [%s] not configured for %s", args[index], method)); return returnVal; } catch (NullPointerException e) { - throw new IllegalArgumentException(String.format( - "argument at index %d on method %s", index, method), e); + throw new IllegalArgumentException(String.format("argument at index %d on method %s", index, method), e); } } return null; } - public static URI getEndpointFor(Method method, Object[] args, - Injector injector) { + public static URI getEndpointFor(Method method, Object[] args, Injector injector) { URI endpoint = getEndpointInParametersOrNull(method, args, injector); if (endpoint == null) { Endpoint annotation; if (method.isAnnotationPresent(Endpoint.class)) { annotation = method.getAnnotation(Endpoint.class); - } else if (method.getDeclaringClass().isAnnotationPresent( - Endpoint.class)) { - annotation = method.getDeclaringClass().getAnnotation( - Endpoint.class); + } else if (method.getDeclaringClass().isAnnotationPresent(Endpoint.class)) { + annotation = method.getDeclaringClass().getAnnotation(Endpoint.class); } else { - throw new IllegalStateException( - "no annotations on class or method: " + method); + throw new IllegalStateException("no annotations on class or method: " + method); } return injector.getInstance(Key.get(URI.class, annotation.value())); } @@ -712,52 +644,59 @@ public class RestAnnotationProcessor { public static final TypeLiteral> futureInputStreamLiteral = new TypeLiteral>() { }; - public static Class> getParserOrThrowException( - Method method) { + @SuppressWarnings("unchecked") + public static Key> getParserOrThrowException(Method method) { ResponseParser annotation = method.getAnnotation(ResponseParser.class); if (annotation == null) { - if (method.getReturnType().equals(boolean.class) - || method.getReturnType().equals(Boolean.class) - || TypeLiteral.get(method.getGenericReturnType()).equals( - futureBooleanLiteral)) { - return ReturnTrueIf2xx.class; - } else if (method.getReturnType().equals(String.class) - || TypeLiteral.get(method.getGenericReturnType()).equals( - futureStringLiteral)) { - return ReturnStringIf2xx.class; - } else if (method.getReturnType().equals(void.class) - || TypeLiteral.get(method.getGenericReturnType()).equals( - futureVoidLiteral)) { - return ReleasePayloadAndReturn.class; - } else if (method.getReturnType().equals(URI.class) - || TypeLiteral.get(method.getGenericReturnType()).equals( - futureURILiteral)) { - return ParseURIFromListOrLocationHeaderIf20x.class; + if (method.getReturnType().equals(void.class) + || TypeLiteral.get(method.getGenericReturnType()).equals(futureVoidLiteral)) { + return Key.get(ReleasePayloadAndReturn.class); + } else if (method.getReturnType().equals(boolean.class) || method.getReturnType().equals(Boolean.class) + || TypeLiteral.get(method.getGenericReturnType()).equals(futureBooleanLiteral)) { + return Key.get(ReturnTrueIf2xx.class); } else if (method.getReturnType().equals(InputStream.class) - || TypeLiteral.get(method.getGenericReturnType()).equals( - futureInputStreamLiteral)) { - return ReturnInputStream.class; + || TypeLiteral.get(method.getGenericReturnType()).equals(futureInputStreamLiteral)) { + return Key.get(ReturnInputStream.class); + } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) { + Type returnVal; + if (method.getReturnType().getTypeParameters().length == 0) { + returnVal = method.getReturnType(); + } else if (method.getReturnType().equals(ListenableFuture.class)) { + ParameterizedType futureType = ((ParameterizedType) method.getGenericReturnType()); + returnVal = futureType.getActualTypeArguments()[0]; + if (returnVal instanceof WildcardType) + returnVal = WildcardType.class.cast(returnVal).getUpperBounds()[0]; + } else { + returnVal = method.getGenericReturnType(); + } + ParameterizedType parserType; + if (method.isAnnotationPresent(Unwrap.class)) + parserType = Types.newParameterizedType(UnwrapOnlyJsonValue.class, returnVal); + else + parserType = Types.newParameterizedType(ParseJson.class, returnVal); + return (Key>) Key.get(parserType); + } else if (method.getReturnType().equals(String.class) + || TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) { + return Key.get(ReturnStringIf2xx.class); + } else if (method.getReturnType().equals(URI.class) + || TypeLiteral.get(method.getGenericReturnType()).equals(futureURILiteral)) { + return Key.get(ParseURIFromListOrLocationHeaderIf20x.class); } else { - throw new IllegalStateException( - "You must specify a ResponseTransformer annotation on: " - + method.toString()); + throw new IllegalStateException("You must specify a ResponseParser annotation on: " + method.toString()); } } - return annotation.value(); + return Key.get(annotation.value()); } - public static Class> getSaxResponseParserClassOrNull( - Method method) { - XMLResponseParser annotation = method - .getAnnotation(XMLResponseParser.class); + public static Class> getSaxResponseParserClassOrNull(Method method) { + XMLResponseParser annotation = method.getAnnotation(XMLResponseParser.class); if (annotation != null) { return annotation.value(); } return null; } - public org.jclouds.rest.MapBinder getMapPayloadBinderOrNull(Method method, - Object... args) { + public org.jclouds.rest.MapBinder getMapPayloadBinderOrNull(Method method, Object... args) { if (args != null) { for (Object arg : args) { if (arg instanceof Object[]) { @@ -771,9 +710,8 @@ public class RestAnnotationProcessor { } } else { if (postBinders[0] instanceof org.jclouds.rest.MapBinder) { - throw new IllegalArgumentException( - "we currently do not support multiple varargs postBinders in: " - + method.getName()); + throw new IllegalArgumentException("we currently do not support multiple varargs postBinders in: " + + method.getName()); } } } else if (arg instanceof org.jclouds.rest.MapBinder) { @@ -793,19 +731,16 @@ public class RestAnnotationProcessor { private Multimap constants = LinkedHashMultimap.create(); public boolean isHttpMethod(Method method) { - return method.isAnnotationPresent(Path.class) - || IsHttpMethod.getHttpMethods(method) != null; + return method.isAnnotationPresent(Path.class) || IsHttpMethod.getHttpMethods(method) != null; } public boolean isConstantDeclaration(Method method) { - return method.isAnnotationPresent(PathParam.class) - && method.isAnnotationPresent(Named.class); + return method.isAnnotationPresent(PathParam.class) && method.isAnnotationPresent(Named.class); } public void bindConstant(Method method) { String key = method.getAnnotation(PathParam.class).value(); - String value = injector.getInstance(Key.get(String.class, method - .getAnnotation(Named.class))); + String value = injector.getInstance(Key.get(String.class, method.getAnnotation(Named.class))); constants.put(key, value); } @@ -819,20 +754,15 @@ public class RestAnnotationProcessor { return requests.iterator().next(); } - public void addHostHeaderIfAnnotatedWithVirtualHost( - Multimap headers, String host, Method method) { - if (declaring.isAnnotationPresent(VirtualHost.class) - || method.isAnnotationPresent(VirtualHost.class)) { + public void addHostHeaderIfAnnotatedWithVirtualHost(Multimap headers, String host, Method method) { + if (declaring.isAnnotationPresent(VirtualHost.class) || method.isAnnotationPresent(VirtualHost.class)) { headers.put(HOST, host); } } - public void decorateRequest(GeneratedHttpRequest request, - Multimap headers) { - org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(request - .getJavaMethod(), request.getArgs()); - Map mapParams = buildPostParams(request.getJavaMethod(), - request.getArgs()); + public void decorateRequest(GeneratedHttpRequest request, Multimap headers) { + org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(request.getJavaMethod(), request.getArgs()); + Map mapParams = buildPostParams(request.getJavaMethod(), request.getArgs()); // MapPayloadBinder is only useful if there are parameters. We guard here // in case the // MapPayloadBinder is also an PayloadBinder. If so, it can be used with @@ -842,38 +772,27 @@ public class RestAnnotationProcessor { mapBinder.bindToRequest(request, mapParams); } else { OUTER: for (Entry> entry : filterValues( - methodToIndexOfParamToDecoratorParamAnnotation.get(request - .getJavaMethod()), new Predicate>() { + methodToIndexOfParamToDecoratorParamAnnotation.get(request.getJavaMethod()), + new Predicate>() { public boolean apply(Set input) { return input.size() >= 1; } }).entrySet()) { boolean shouldBreak = false; - BinderParam payloadAnnotation = (BinderParam) entry.getValue() - .iterator().next(); + BinderParam payloadAnnotation = (BinderParam) entry.getValue().iterator().next(); Binder binder = injector.getInstance(payloadAnnotation.value()); - if (request.getArgs().length >= entry.getKey() + 1 - && request.getArgs()[entry.getKey()] != null) { + if (request.getArgs().length >= entry.getKey() + 1 && request.getArgs()[entry.getKey()] != null) { Object input; - Class parameterType = request.getJavaMethod() - .getParameterTypes()[entry.getKey()]; - Class argType = request.getArgs()[entry - .getKey()].getClass(); - if (!argType.isArray() && request.getJavaMethod().isVarArgs() - && parameterType.isArray()) { - int arrayLength = request.getArgs().length - - request.getJavaMethod().getParameterTypes().length - + 1; + Class parameterType = request.getJavaMethod().getParameterTypes()[entry.getKey()]; + Class argType = request.getArgs()[entry.getKey()].getClass(); + if (!argType.isArray() && request.getJavaMethod().isVarArgs() && parameterType.isArray()) { + int arrayLength = request.getArgs().length - request.getJavaMethod().getParameterTypes().length + 1; if (arrayLength == 0) break OUTER; - input = (Object[]) Array.newInstance(request.getArgs()[entry - .getKey()].getClass(), arrayLength); - System.arraycopy(request.getArgs(), entry.getKey(), input, 0, - arrayLength); + input = (Object[]) Array.newInstance(request.getArgs()[entry.getKey()].getClass(), arrayLength); + System.arraycopy(request.getArgs(), entry.getKey(), input, 0, arrayLength); shouldBreak = true; - } else if (argType.isArray() - && request.getJavaMethod().isVarArgs() - && parameterType.isArray()) { + } else if (argType.isArray() && request.getJavaMethod().isVarArgs() && parameterType.isArray()) { input = request.getArgs()[entry.getKey()]; } else { input = request.getArgs()[entry.getKey()]; @@ -893,23 +812,19 @@ public class RestAnnotationProcessor { utils.setPayloadPropertiesFromHeaders(headers, request); } - public static Map> indexWithOnlyOneAnnotation( - Method method, String description, + public static Map> indexWithOnlyOneAnnotation(Method method, String description, Map>> toRefine) { - Map> indexToPayloadAnnotation = filterValues( - toRefine.get(method), new Predicate>() { + Map> indexToPayloadAnnotation = filterValues(toRefine.get(method), + new Predicate>() { public boolean apply(Set input) { return input.size() == 1; } }); if (indexToPayloadAnnotation.size() > 1) { - throw new IllegalStateException( - String - .format( - "You must not specify more than one %s annotation on: %s; found %s", - description, method.toString(), - indexToPayloadAnnotation)); + throw new IllegalStateException(String.format( + "You must not specify more than one %s annotation on: %s; found %s", description, method.toString(), + indexToPayloadAnnotation)); } return indexToPayloadAnnotation; } @@ -928,9 +843,8 @@ public class RestAnnotationProcessor { } } else { if (options[0] instanceof HttpRequestOptions) { - throw new IllegalArgumentException( - "we currently do not support multiple varargs options in: " - + method.getName()); + throw new IllegalArgumentException("we currently do not support multiple varargs options in: " + + method.getName()); } } } else { @@ -941,15 +855,12 @@ public class RestAnnotationProcessor { return null; } - public Multimap buildHeaders( - Collection> tokenValues, Method method, + public Multimap buildHeaders(Collection> tokenValues, Method method, final Object... args) { Multimap headers = LinkedHashMultimap.create(); addHeaderIfAnnotationPresentOnMethod(headers, method, tokenValues); - Map> indexToHeaderParam = methodToIndexOfParamToHeaderParamAnnotations - .get(method); - for (Entry> entry : indexToHeaderParam - .entrySet()) { + Map> indexToHeaderParam = methodToIndexOfParamToHeaderParamAnnotations.get(method); + for (Entry> entry : indexToHeaderParam.entrySet()) { for (Annotation key : entry.getValue()) { String value = args[entry.getKey()].toString(); value = replaceTokens(value, tokenValues); @@ -961,20 +872,26 @@ public class RestAnnotationProcessor { return headers; } - void addConsumesIfPresentOnTypeOrMethod(Multimap headers, - Method method) { - if (declaring.isAnnotationPresent(Consumes.class)) { - Consumes header = declaring.getAnnotation(Consumes.class); - headers.replaceValues(ACCEPT, asList(header.value())); + void addConsumesIfPresentOnTypeOrMethod(Multimap headers, Method method) { + List accept = getAcceptHeadersOrNull(method); + if (accept.size() > 0) + headers.replaceValues(ACCEPT, accept); + } + + private static List getAcceptHeadersOrNull(Method method) { + List accept = Collections.emptyList(); + if (method.getDeclaringClass().isAnnotationPresent(Consumes.class)) { + Consumes header = method.getDeclaringClass().getAnnotation(Consumes.class); + accept = asList(header.value()); } if (method.isAnnotationPresent(Consumes.class)) { Consumes header = method.getAnnotation(Consumes.class); - headers.replaceValues(ACCEPT, asList(header.value())); + accept = asList(header.value()); } + return accept; } - void addProducesIfPresentOnTypeOrMethod(Multimap headers, - Method method) { + void addProducesIfPresentOnTypeOrMethod(Multimap headers, Method method) { if (declaring.isAnnotationPresent(Produces.class)) { Produces header = declaring.getAnnotation(Produces.class); headers.replaceValues(CONTENT_TYPE, asList(header.value())); @@ -985,8 +902,7 @@ public class RestAnnotationProcessor { } } - public void addHeaderIfAnnotationPresentOnMethod( - Multimap headers, Method method, + public void addHeaderIfAnnotationPresentOnMethod(Multimap headers, Method method, Collection> tokenValues) { if (declaring.isAnnotationPresent(Headers.class)) { Headers header = declaring.getAnnotation(Headers.class); @@ -1016,11 +932,9 @@ public class RestAnnotationProcessor { return out; } - List getParts(Method method, Object[] args, - Iterable> iterable) { + List getParts(Method method, Object[] args, Iterable> iterable) { List parts = newLinkedList(); - Map> indexToPartParam = methodToIndexOfParamToPartParamAnnotations - .get(method); + Map> indexToPartParam = methodToIndexOfParamToPartParamAnnotations.get(method); for (Entry> entry : indexToPartParam.entrySet()) { for (Annotation key : entry.getValue()) { PartParam param = (PartParam) key; @@ -1029,8 +943,7 @@ public class RestAnnotationProcessor { options.contentType(param.contentType()); if (!PartParam.NO_FILENAME.equals(param.filename())) options.filename(replaceTokens(param.filename(), iterable)); - Part part = Part.create(param.name(), newPayload(args[entry - .getKey()]), options); + Part part = Part.create(param.name(), newPayload(args[entry.getKey()]), options); parts.add(part); } } @@ -1048,26 +961,20 @@ public class RestAnnotationProcessor { return null; } - private Multimap getPathParamKeyValues(Method method, - Object... args) { + private Multimap getPathParamKeyValues(Method method, Object... args) { Multimap pathParamValues = LinkedHashMultimap.create(); pathParamValues.putAll(constants); - Map> indexToPathParam = methodToIndexOfParamToPathParamAnnotations - .get(method); + Map> indexToPathParam = methodToIndexOfParamToPathParamAnnotations.get(method); - Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations - .get(method); + Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method); for (Entry> entry : indexToPathParam.entrySet()) { for (Annotation key : entry.getValue()) { - Set extractors = indexToParamExtractor.get(entry - .getKey()); + Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((PathParam) key).value(); String paramValue; if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator() - .next(); - paramValue = injector.getInstance(extractor.value()).apply( - args[entry.getKey()]); + ParamParser extractor = (ParamParser) extractors.iterator().next(); + paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); } else { paramValue = args[entry.getKey()].toString(); } @@ -1075,19 +982,16 @@ public class RestAnnotationProcessor { } } - if (method.isAnnotationPresent(PathParam.class) - && method.isAnnotationPresent(ParamParser.class)) { + if (method.isAnnotationPresent(PathParam.class) && method.isAnnotationPresent(ParamParser.class)) { String paramKey = method.getAnnotation(PathParam.class).value(); - String paramValue = injector.getInstance( - method.getAnnotation(ParamParser.class).value()).apply(args); + String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args); pathParamValues.put(paramKey, paramValue); } return pathParamValues; } - private Multimap encodeValues( - Multimap unencoded, char... skips) { + private Multimap encodeValues(Multimap unencoded, char... skips) { Multimap encoded = LinkedHashMultimap.create(); for (Entry entry : unencoded.entries()) { encoded.put(entry.getKey(), urlEncode(entry.getValue(), skips)); @@ -1095,27 +999,20 @@ public class RestAnnotationProcessor { return encoded; } - private Multimap getMatrixParamKeyValues(Method method, - Object... args) { + private Multimap getMatrixParamKeyValues(Method method, Object... args) { Multimap matrixParamValues = LinkedHashMultimap.create(); matrixParamValues.putAll(constants); - Map> indexToMatrixParam = methodToIndexOfParamToMatrixParamAnnotations - .get(method); + Map> indexToMatrixParam = methodToIndexOfParamToMatrixParamAnnotations.get(method); - Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations - .get(method); - for (Entry> entry : indexToMatrixParam - .entrySet()) { + Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method); + for (Entry> entry : indexToMatrixParam.entrySet()) { for (Annotation key : entry.getValue()) { - Set extractors = indexToParamExtractor.get(entry - .getKey()); + Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((MatrixParam) key).value(); String paramValue; if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator() - .next(); - paramValue = injector.getInstance(extractor.value()).apply( - args[entry.getKey()]); + ParamParser extractor = (ParamParser) extractors.iterator().next(); + paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); } else { paramValue = args[entry.getKey()].toString(); } @@ -1123,37 +1020,29 @@ public class RestAnnotationProcessor { } } - if (method.isAnnotationPresent(MatrixParam.class) - && method.isAnnotationPresent(ParamParser.class)) { + if (method.isAnnotationPresent(MatrixParam.class) && method.isAnnotationPresent(ParamParser.class)) { String paramKey = method.getAnnotation(MatrixParam.class).value(); - String paramValue = injector.getInstance( - method.getAnnotation(ParamParser.class).value()).apply(args); + String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args); matrixParamValues.put(paramKey, paramValue); } return matrixParamValues; } - private Multimap getFormParamKeyValues(Method method, - Object... args) { + private Multimap getFormParamKeyValues(Method method, Object... args) { Multimap formParamValues = LinkedHashMultimap.create(); formParamValues.putAll(constants); - Map> indexToFormParam = methodToIndexOfParamToFormParamAnnotations - .get(method); + Map> indexToFormParam = methodToIndexOfParamToFormParamAnnotations.get(method); - Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations - .get(method); + Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method); for (Entry> entry : indexToFormParam.entrySet()) { for (Annotation key : entry.getValue()) { - Set extractors = indexToParamExtractor.get(entry - .getKey()); + Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((FormParam) key).value(); String paramValue; if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator() - .next(); - paramValue = injector.getInstance(extractor.value()).apply( - args[entry.getKey()]); + ParamParser extractor = (ParamParser) extractors.iterator().next(); + paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); } else { paramValue = args[entry.getKey()].toString(); } @@ -1161,37 +1050,29 @@ public class RestAnnotationProcessor { } } - if (method.isAnnotationPresent(FormParam.class) - && method.isAnnotationPresent(ParamParser.class)) { + if (method.isAnnotationPresent(FormParam.class) && method.isAnnotationPresent(ParamParser.class)) { String paramKey = method.getAnnotation(FormParam.class).value(); - String paramValue = injector.getInstance( - method.getAnnotation(ParamParser.class).value()).apply(args); + String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args); formParamValues.put(paramKey, paramValue); } return formParamValues; } - private Multimap getQueryParamKeyValues(Method method, - Object... args) { + private Multimap getQueryParamKeyValues(Method method, Object... args) { Multimap queryParamValues = LinkedHashMultimap.create(); queryParamValues.putAll(constants); - Map> indexToQueryParam = methodToIndexOfParamToQueryParamAnnotations - .get(method); + Map> indexToQueryParam = methodToIndexOfParamToQueryParamAnnotations.get(method); - Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations - .get(method); + Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method); for (Entry> entry : indexToQueryParam.entrySet()) { for (Annotation key : entry.getValue()) { - Set extractors = indexToParamExtractor.get(entry - .getKey()); + Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((QueryParam) key).value(); String paramValue; if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator() - .next(); - paramValue = injector.getInstance(extractor.value()).apply( - args[entry.getKey()]); + ParamParser extractor = (ParamParser) extractors.iterator().next(); + paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); } else { paramValue = args[entry.getKey()].toString(); } @@ -1199,11 +1080,9 @@ public class RestAnnotationProcessor { } } - if (method.isAnnotationPresent(QueryParam.class) - && method.isAnnotationPresent(ParamParser.class)) { + if (method.isAnnotationPresent(QueryParam.class) && method.isAnnotationPresent(ParamParser.class)) { String paramKey = method.getAnnotation(QueryParam.class).value(); - String paramValue = injector.getInstance( - method.getAnnotation(ParamParser.class).value()).apply(args); + String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args); queryParamValues.put(paramKey, paramValue); } @@ -1212,21 +1091,16 @@ public class RestAnnotationProcessor { private Map buildPostParams(Method method, Object... args) { Map postParams = newHashMap(); - Map> indexToPathParam = methodToIndexOfParamToPostParamAnnotations - .get(method); - Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations - .get(method); + Map> indexToPathParam = methodToIndexOfParamToPostParamAnnotations.get(method); + Map> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method); for (Entry> entry : indexToPathParam.entrySet()) { for (Annotation key : entry.getValue()) { - Set extractors = indexToParamExtractor.get(entry - .getKey()); + Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((MapPayloadParam) key).value(); String paramValue; if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator() - .next(); - paramValue = injector.getInstance(extractor.value()).apply( - args[entry.getKey()]); + ParamParser extractor = (ParamParser) extractors.iterator().next(); + paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); } else { paramValue = args[entry.getKey()].toString(); diff --git a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java index bd78f6735a..fd93611b7a 100755 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -49,6 +49,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -85,14 +86,17 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.IOExceptionRetryHandler; import org.jclouds.http.Payload; import org.jclouds.http.PayloadEnclosing; +import org.jclouds.http.Payloads; import org.jclouds.http.RequiresHttp; import org.jclouds.http.TransformingHttpCommandExecutorService; +import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReturnInputStream; import org.jclouds.http.functions.ReturnStringIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.internal.PayloadEnclosingImpl; import org.jclouds.http.options.BaseHttpRequestOptions; import org.jclouds.http.options.GetOptions; @@ -119,6 +123,7 @@ import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.Unwrap; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.binders.BindAsHostPrefix; import org.jclouds.rest.binders.BindMapToMatrixParams; @@ -157,15 +162,13 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @ConfiguresRestClient protected static class CallerCalleeModule extends RestClientModule { CallerCalleeModule() { - super(Caller.class, AsyncCaller.class, ImmutableMap., Class> of(Callee.class, - AsyncCallee.class)); + super(Caller.class, AsyncCaller.class, ImmutableMap., Class> of(Callee.class, AsyncCallee.class)); } @Override protected void configure() { super.configure(); - bind(URI.class).annotatedWith(Localhost2.class).toInstance( - URI.create("http://localhost:1111")); + bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111")); bind(IOExceptionRetryHandler.class).toInstance(IOExceptionRetryHandler.NEVER_RETRY); } @@ -206,11 +209,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public AsyncCallee getCallee(); } - public void testDelegateAsync() throws SecurityException, NoSuchMethodException, - InterruptedException, ExecutionException { + public void testDelegateAsync() throws SecurityException, NoSuchMethodException, InterruptedException, + ExecutionException { Injector child = injectorForClient(); - TransformingHttpCommandExecutorService mock = child - .getInstance(TransformingHttpCommandExecutorService.class); + TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); ReleasePayloadAndReturn function = child.getInstance(ReleasePayloadAndReturn.class); @@ -222,12 +224,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } AsyncCaller caller = child.getInstance(AsyncCaller.class); - expect( - mock.submit(requestLineEquals("GET http://localhost:9999/goo/client/foo HTTP/1.1"), - eq(function))).andReturn(null).atLeastOnce(); - expect( - mock.submit(requestLineEquals("GET http://localhost:9999/client/foo HTTP/1.1"), - eq(function))).andReturn(null).atLeastOnce(); + expect(mock.submit(requestLineEquals("GET http://localhost:9999/goo/client/foo HTTP/1.1"), eq(function))) + .andReturn(null).atLeastOnce(); + expect(mock.submit(requestLineEquals("GET http://localhost:9999/client/foo HTTP/1.1"), eq(function))).andReturn( + null).atLeastOnce(); replay(mock); caller.getCallee("goo").onePath("foo"); @@ -256,11 +256,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { return null; } - public void testDelegateWithOverridingEndpoint() throws SecurityException, - NoSuchMethodException, InterruptedException, ExecutionException { + public void testDelegateWithOverridingEndpoint() throws SecurityException, NoSuchMethodException, + InterruptedException, ExecutionException { Injector child = injectorForClient(); - TransformingHttpCommandExecutorService mock = child - .getInstance(TransformingHttpCommandExecutorService.class); + TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); ReleasePayloadAndReturn function = child.getInstance(ReleasePayloadAndReturn.class); @@ -272,15 +271,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } Caller caller = child.getInstance(Caller.class); - expect( - mock.submit(requestLineEquals("GET http://localhost:1111/goo/client/foo HTTP/1.1"), - eq(function))).andReturn(Futures. immediateFuture(null)) - .atLeastOnce(); + expect(mock.submit(requestLineEquals("GET http://localhost:1111/goo/client/foo HTTP/1.1"), eq(function))) + .andReturn(Futures. immediateFuture(null)).atLeastOnce(); - expect( - mock.submit(requestLineEquals("GET http://localhost:1111/client/foo HTTP/1.1"), - eq(function))).andReturn(Futures. immediateFuture(null)) - .atLeastOnce(); + expect(mock.submit(requestLineEquals("GET http://localhost:1111/client/foo HTTP/1.1"), eq(function))).andReturn( + Futures. immediateFuture(null)).atLeastOnce(); replay(mock); caller.getCallee("goo").onePath("foo"); @@ -292,12 +287,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { private Injector injectorForClient() { - ContextSpec contextSpec = contextSpec("test", "http://localhost:9999", - "1", "userfoo", null, Caller.class, AsyncCaller.class); + ContextSpec contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, + Caller.class, AsyncCaller.class); return createContextBuilder(contextSpec, - ImmutableSet.of(new MockModule(), new NullLoggingModule(), new CallerCalleeModule())) - .buildInjector(); + ImmutableSet.of(new MockModule(), new NullLoggingModule(), new CallerCalleeModule())).buildInjector(); } @@ -312,12 +306,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public AsyncCallee getCallee(); } - public void testDelegateWithPathOnClass() throws SecurityException, NoSuchMethodException, - InterruptedException, ExecutionException { + public void testDelegateWithPathOnClass() throws SecurityException, NoSuchMethodException, InterruptedException, + ExecutionException { Injector child = injectorForClient(); - TransformingHttpCommandExecutorService mock = child - .getInstance(TransformingHttpCommandExecutorService.class); + TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); ReleasePayloadAndReturn function = child.getInstance(ReleasePayloadAndReturn.class); @@ -330,16 +323,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } CallerWithPathOnClass caller = factory.create(CallerWithPathOnClass.class); - expect( - mock - .submit( - requestLineEquals("GET http://localhost:9999/caller/goo/client/foo HTTP/1.1"), - eq(function))).andReturn(null).atLeastOnce(); + expect(mock.submit(requestLineEquals("GET http://localhost:9999/caller/goo/client/foo HTTP/1.1"), eq(function))) + .andReturn(null).atLeastOnce(); - expect( - mock.submit( - requestLineEquals("GET http://localhost:9999/caller/client/foo HTTP/1.1"), - eq(function))).andReturn(null).atLeastOnce(); + expect(mock.submit(requestLineEquals("GET http://localhost:9999/caller/client/foo HTTP/1.1"), eq(function))) + .andReturn(null).atLeastOnce(); replay(mock); caller.getCallee("goo").onePath("foo"); caller.getCallee().onePath("foo"); @@ -388,12 +376,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testUnEncodeQuery() { URI expects = URI - .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef:sushi&metadata=foo:bar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); + .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef:sushi&metadata=foo:bar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); URI start = URI - .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); - URI value = RestAnnotationProcessor.replaceQuery(uriBuilderProvider, start, start.getQuery(), - null, '/', ':'); + .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); + URI value = RestAnnotationProcessor.replaceQuery(uriBuilderProvider, start, start.getQuery(), null, '/', ':'); assertEquals(value, expects); } @@ -417,12 +404,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testQuery3() throws SecurityException, NoSuchMethodException { Method method = TestQuery.class.getMethod("foo3", String.class); - HttpRequest request = factory(TestQuery.class).createRequest(method, - new Object[] { "wonder" }); + HttpRequest request = factory(TestQuery.class).createRequest(method, new Object[] { "wonder" }); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), ""); - assertEquals(request.getEndpoint().getQuery(), - "x-ms-version=2009-07-17&foo=bar&fooble=baz&robbie=wonder"); + assertEquals(request.getEndpoint().getQuery(), "x-ms-version=2009-07-17&foo=bar&fooble=baz&robbie=wonder"); assertEquals(request.getMethod(), "FOO"); } @@ -435,48 +420,45 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } - public void testHttpRequestOptionsPayloadParam() throws SecurityException, - NoSuchMethodException, IOException { + public void testHttpRequestOptionsPayloadParam() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("post", HttpRequestOptions.class); verifyTestPostOptions(method); } - public void testPayloadParamVarargs() throws SecurityException, NoSuchMethodException, - IOException { - Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance( - HttpRequestOptions.class, 0).getClass()); + public void testPayloadParamVarargs() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0) + .getClass()); verifyTestPostOptions(method); } private void verifyTestPostOptions(Method method) throws IOException { - HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, - new HttpRequestOptions() { + HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, new HttpRequestOptions() { - public Multimap buildMatrixParameters() { - return LinkedHashMultimap.create(); - } + public Multimap buildMatrixParameters() { + return LinkedHashMultimap.create(); + } - public String buildPathSuffix() { - return null; - } + public String buildPathSuffix() { + return null; + } - public Multimap buildQueryParameters() { - return LinkedHashMultimap.create(); - } + public Multimap buildQueryParameters() { + return LinkedHashMultimap.create(); + } - public Multimap buildFormParameters() { - return LinkedHashMultimap.create(); - } + public Multimap buildFormParameters() { + return LinkedHashMultimap.create(); + } - public Multimap buildRequestHeaders() { - return LinkedHashMultimap.create(); - } + public Multimap buildRequestHeaders() { + return LinkedHashMultimap.create(); + } - public String buildStringPayload() { - return "fooya"; - } + public String buildStringPayload() { + return "fooya"; + } - }); + }); assertRequestLineEquals(request, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "fooya", "application/unknown", false); @@ -528,8 +510,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOverriddenEndpointMethod() throws SecurityException, NoSuchMethodException { Method method = TestOverriddenEndpoint.class.getMethod("foo"); - HttpRequest request = factory(TestOverriddenEndpoint.class).createRequest(method, - new Object[] {}); + HttpRequest request = factory(TestOverriddenEndpoint.class).createRequest(method, new Object[] {}); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPort(), 1111); assertEquals(request.getEndpoint().getPath(), ""); @@ -539,7 +520,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOverriddenEndpointParameter() throws SecurityException, NoSuchMethodException { Method method = TestOverriddenEndpoint.class.getMethod("foo", URI.class); HttpRequest request = factory(TestOverriddenEndpoint.class).createRequest(method, - new Object[] { URI.create("http://wowsa:8001") }); + new Object[] { URI.create("http://wowsa:8001") }); assertEquals(request.getEndpoint().getHost(), "wowsa"); assertEquals(request.getEndpoint().getPort(), 8001); assertEquals(request.getEndpoint().getPath(), ""); @@ -557,8 +538,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST @Path("{foo}") - public void postWithPath(@PathParam("foo") @MapPayloadParam("fooble") String path, - MapBinder content) { + public void postWithPath(@PathParam("foo") @MapPayloadParam("fooble") String path, MapBinder content) { } @POST @@ -577,8 +557,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "data", "application/unknown", false); } - public void testCreatePostRequestNullOk() throws SecurityException, NoSuchMethodException, - IOException { + public void testCreatePostRequestNullOk() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPost.class.getMethod("post", String.class); HttpRequest request = factory(TestPost.class).createRequest(method); @@ -587,8 +566,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, null, "application/unknown", false); } - public void testCreatePostJsonRequest() throws SecurityException, NoSuchMethodException, - IOException { + public void testCreatePostJsonRequest() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPost.class.getMethod("postAsJson", String.class); HttpRequest request = factory(TestPost.class).createRequest(method, "data"); @@ -597,25 +575,22 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "\"data\"", "application/json", false); } - public void testCreatePostWithPathRequest() throws SecurityException, NoSuchMethodException, - IOException { + public void testCreatePostWithPathRequest() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPost.class.getMethod("postWithPath", String.class, MapBinder.class); - HttpRequest request = factory(TestPost.class).createRequest(method, "data", - new org.jclouds.rest.MapBinder() { - public void bindToRequest(HttpRequest request, Map postParams) { - request.setPayload(postParams.get("fooble")); - } + HttpRequest request = factory(TestPost.class).createRequest(method, "data", new org.jclouds.rest.MapBinder() { + public void bindToRequest(HttpRequest request, Map postParams) { + request.setPayload(postParams.get("fooble")); + } - public void bindToRequest(HttpRequest request, Object toBind) { - throw new RuntimeException("this shouldn't be used in POST"); - } - }); + public void bindToRequest(HttpRequest request, Object toBind) { + throw new RuntimeException("this shouldn't be used in POST"); + } + }); assertRequestLineEquals(request, "POST http://localhost:9999/data HTTP/1.1"); assertPayloadEquals(request, "data", "application/unknown", false); } - public void testCreatePostWithMethodBinder() throws SecurityException, NoSuchMethodException, - IOException { + public void testCreatePostWithMethodBinder() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPost.class.getMethod("postWithMethodBinder", String.class); HttpRequest request = factory(TestPost.class).createRequest(method, "data"); @@ -636,162 +611,165 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST void withParamFileBinaryPart(@FormParam("name") String name, - @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path); + @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path); @POST void withParamByteArrayBinaryPart( - @FormParam("name") String name, - @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content); + @FormParam("name") String name, + @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content); } - public void testMultipartWithStringPart() throws SecurityException, NoSuchMethodException, - IOException { + public void testMultipartWithStringPart() throws SecurityException, NoSuchMethodException, IOException { Method method = TestMultipartForm.class.getMethod("withStringPart", String.class); - GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class) - .createRequest(method, "foobledata"); + GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, + "foobledata"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"fooble\"\r\n" + // - "\r\n" + // - "foobledata\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"fooble\"\r\n" + // + "\r\n" + // + "foobledata\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } - public void testMultipartWithParamStringPart() throws SecurityException, NoSuchMethodException, - IOException { - Method method = TestMultipartForm.class.getMethod("withParamStringPart", String.class, - String.class); - GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class) - .createRequest(method, "name", "foobledata"); + public void testMultipartWithParamStringPart() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestMultipartForm.class.getMethod("withParamStringPart", String.class, String.class); + GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, + "name", "foobledata"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"name\"\r\n" + // - "\r\n" + // - "name\r\n" + // / - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"file\"\r\n" + // - "\r\n" + // - "foobledata\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"\r\n" + // + "\r\n" + // + "foobledata\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } - public void testMultipartWithParamFilePart() throws SecurityException, NoSuchMethodException, - IOException { - Method method = TestMultipartForm.class.getMethod("withParamFilePart", String.class, - File.class); + public void testMultipartWithParamFilePart() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestMultipartForm.class.getMethod("withParamFilePart", String.class, File.class); File file = File.createTempFile("foo", "bar"); Files.append("foobledata", file, UTF_8); file.deleteOnExit(); - GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class) - .createRequest(method, "name", file); + GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, + "name", file); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" - + // - "Content-Disposition: form-data; name=\"name\"\r\n" - + // - "\r\n" - + // - "name\r\n" - + // / - "----JCLOUDS--\r\n" - + // - "Content-Disposition: form-data; name=\"file\"; filename=\"" - + file.getName() + "\"\r\n" + // - "\r\n" + // - "foobledata\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // + "\r\n" + // + "foobledata\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } - public void testMultipartWithParamByteArrayPart() throws SecurityException, - NoSuchMethodException, IOException { - Method method = TestMultipartForm.class.getMethod("withParamByteArrayBinaryPart", - String.class, byte[].class); - GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class) - .createRequest(method, "name", "goo".getBytes()); + public void testMultipartWithParamByteArrayPart() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestMultipartForm.class.getMethod("withParamByteArrayBinaryPart", String.class, byte[].class); + GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, + "name", "goo".getBytes()); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" - + // - "Content-Disposition: form-data; name=\"name\"\r\n" - + // - "\r\n" - + // - "name\r\n" - + // / - "----JCLOUDS--\r\n" - + // - "Content-Disposition: form-data; name=\"file\"; filename=\"name.tar.gz\"\r\n" - + // - "Content-Type: application/octet-stream\r\n" + // - "\r\n" + // - "goo\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"; filename=\"name.tar.gz\"\r\n" + // + "Content-Type: application/octet-stream\r\n" + // + "\r\n" + // + "goo\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); }; - public void testMultipartWithParamFileBinaryPart() throws SecurityException, - NoSuchMethodException, IOException { - Method method = TestMultipartForm.class.getMethod("withParamFileBinaryPart", String.class, - File.class); + public void testMultipartWithParamFileBinaryPart() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestMultipartForm.class.getMethod("withParamFileBinaryPart", String.class, File.class); File file = File.createTempFile("foo", "bar"); Files.write(new byte[] { 17, 26, 39, 40, 50 }, file); file.deleteOnExit(); - GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class) - .createRequest(method, "name", file); + GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, + "name", file); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" - + // - "Content-Disposition: form-data; name=\"name\"\r\n" - + // - "\r\n" - + // - "name\r\n" - + // / - "----JCLOUDS--\r\n" - + // - "Content-Disposition: form-data; name=\"file\"; filename=\"" - + file.getName() + "\"\r\n" + // - "Content-Type: application/octet-stream\r\n" + // - "\r\n" + // - "'(2\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // + "Content-Type: application/octet-stream\r\n" + // + "\r\n" + // + "'(2\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } - public class TestPut { + public interface TestPut { @PUT @Path("{foo}") @MapBinder(BindToJsonPayload.class) - public void putWithMethodBinder(@PathParam("foo") @MapPayloadParam("fooble") String path) { - } + void putWithMethodBinder(@PathParam("foo") @MapPayloadParam("fooble") String path); @PUT @Path("{foo}") @Produces(MediaType.TEXT_PLAIN) - public void putWithMethodBinderProduces( - @PathParam("foo") @BinderParam(BindToStringPayload.class) String path) { - } + void putWithMethodBinderProduces(@PathParam("foo") @BinderParam(BindToStringPayload.class) String path); @PUT @Path("{foo}") @MapBinder(BindToJsonPayload.class) @Consumes(MediaType.APPLICATION_JSON) - public void putWithMethodBinderConsumes( - @PathParam("foo") @MapPayloadParam("fooble") String path) { - } + Wrapper putWithMethodBinderConsumes(@PathParam("foo") @MapPayloadParam("fooble") String path); + + @GET + @Consumes(MediaType.APPLICATION_JSON) + Map testGeneric(); + + @GET + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture> testGeneric2(); + + @GET + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture> testGeneric3(); + + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + String testUnwrap(); + + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture testUnwrap2(); + + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture> testUnwrap3(); + + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture> testUnwrap4(); } - public void testCreatePutWithMethodBinder() throws SecurityException, NoSuchMethodException, - IOException { + static class Wrapper { + String foo; + } + + public void testCreatePutWithMethodBinder() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("putWithMethodBinder", String.class); HttpRequest request = factory(TestPut.class).createRequest(method, "data"); @@ -800,8 +778,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "{\"fooble\":\"data\"}", "application/json", false); } - public void testCreatePutWithMethodProduces() throws SecurityException, NoSuchMethodException, - IOException { + public void testCreatePutWithMethodProduces() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("putWithMethodBinderProduces", String.class); HttpRequest request = factory(TestPut.class).createRequest(method, "data"); @@ -810,14 +787,131 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "data", "text/plain", false); } - public void testCreatePutWithMethodConsumes() throws SecurityException, NoSuchMethodException, - IOException { + @SuppressWarnings("unchecked") + public void testCreatePutWithMethodConsumes() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("putWithMethodBinderConsumes", String.class); HttpRequest request = factory(TestPut.class).createRequest(method, "data"); assertRequestLineEquals(request, "PUT http://localhost:9999/data HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals(request, "{\"fooble\":\"data\"}", "application/json", false); + + assertResponseParserClassEquals(method, request, ParseJson.class); + // now test that it works! + + Function parser = (Function) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads.newStringPayload("{ foo:\"bar\"}"))).foo, "bar"); + + } + + @SuppressWarnings("unchecked") + public void testGeneric1() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testGeneric"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, ParseJson.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads.newStringPayload("{ foo:\"bar\"}"))), ImmutableMap + .of("foo", "bar")); + + } + + @SuppressWarnings("unchecked") + public void testGeneric2() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testGeneric2"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, ParseJson.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads.newStringPayload("{ foo:\"bar\"}"))), ImmutableMap + .of("foo", "bar")); + + } + + @SuppressWarnings("unchecked") + public void testGeneric3() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testGeneric3"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, ParseJson.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads.newStringPayload("{ foo:\"bar\"}"))), ImmutableMap + .of("foo", "bar")); + + } + + @SuppressWarnings("unchecked") + public void testUnwrap1() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testUnwrap"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads.newStringPayload("{ foo:\"bar\"}"))), "bar"); + + } + + @SuppressWarnings("unchecked") + public void testUnwrap2() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testUnwrap2"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads.newStringPayload("{ foo:\"bar\"}"))), "bar"); + + } + + @SuppressWarnings("unchecked") + public void testUnwrap3() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testUnwrap3"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads + .newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))), ImmutableSet.of("0.7.0", "0.7.1")); + } + + @SuppressWarnings("unchecked") + public void testUnwrap4() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPut.class.getMethod("testUnwrap4"); + HttpRequest request = factory(TestPut.class).createRequest(method); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + // now test that it works! + + Function> parser = (Function>) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + assertEquals(parser.apply(new HttpResponse(200, "ok", Payloads + .newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))), ImmutableSet.of("0.7.0", "0.7.1")); } static class TestRequestFilter1 implements HttpRequestFilter { @@ -871,8 +965,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testSkipEncoding() throws SecurityException, NoSuchMethodException { Method method = TestEncoding.class.getMethod("twoPaths", String.class, String.class); - HttpRequest request = factory(TestEncoding.class).createRequest(method, - new Object[] { "1", "localhost" }); + HttpRequest request = factory(TestEncoding.class).createRequest(method, new Object[] { "1", "localhost" }); assertEquals(request.getEndpoint().getPath(), "/1/localhost"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); @@ -881,8 +974,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testEncodingPath() throws SecurityException, NoSuchMethodException { Method method = TestEncoding.class.getMethod("twoPaths", String.class, String.class); - HttpRequest request = factory(TestEncoding.class).createRequest(method, - new Object[] { "/", "localhost" }); + HttpRequest request = factory(TestEncoding.class).createRequest(method, new Object[] { "/", "localhost" }); assertEquals(request.getEndpoint().getPath(), "///localhost"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); @@ -904,7 +996,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testConstantPathParam() throws SecurityException, NoSuchMethodException, IOException { Method method = TestConstantPathParam.class.getMethod("twoPaths", String.class, String.class); HttpRequest request = factory(TestConstantPathParam.class).createRequest(method, - new Object[] { "1", "localhost" }); + new Object[] { "1", "localhost" }); assertRequestLineEquals(request, "GET http://localhost:9999/v1/ralphie/1/localhost HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); @@ -923,32 +1015,27 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @Path("{path2}/{path1}") - public void twoPathsOutOfOrder(@PathParam("path1") String path, - @PathParam("path2") String path2) { + public void twoPathsOutOfOrder(@PathParam("path1") String path, @PathParam("path2") String path2) { } @GET @Path("{path}") - public void onePathParamExtractor( - @PathParam("path") @ParamParser(FirstCharacter.class) String path) { + public void onePathParamExtractor(@PathParam("path") @ParamParser(FirstCharacter.class) String path) { } @GET @Path("/") - public void oneQueryParamExtractor( - @QueryParam("one") @ParamParser(FirstCharacter.class) String one) { + public void oneQueryParamExtractor(@QueryParam("one") @ParamParser(FirstCharacter.class) String one) { } @POST @Path("/") - public void oneFormParamExtractor( - @FormParam("one") @ParamParser(FirstCharacter.class) String one) { + public void oneFormParamExtractor(@FormParam("one") @ParamParser(FirstCharacter.class) String one) { } @GET @Path("/") - public void oneMatrixParamExtractor( - @MatrixParam("one") @ParamParser(FirstCharacter.class) String one) { + public void oneMatrixParamExtractor(@MatrixParam("one") @ParamParser(FirstCharacter.class) String one) { } @GET @@ -960,19 +1047,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testPathParamExtractor() throws SecurityException, NoSuchMethodException, - IOException { + public void testPathParamExtractor() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPath.class.getMethod("onePathParamExtractor", String.class); - HttpRequest request = factory(TestPath.class).createRequest(method, - new Object[] { "localhost" }); + HttpRequest request = factory(TestPath.class).createRequest(method, new Object[] { "localhost" }); assertRequestLineEquals(request, "GET http://localhost:9999/l HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); } @Test - public void testQueryParamExtractor() throws SecurityException, NoSuchMethodException, - IOException { + public void testQueryParamExtractor() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPath.class.getMethod("oneQueryParamExtractor", String.class); HttpRequest request = factory(TestPath.class).createRequest(method, "localhost"); assertRequestLineEquals(request, "GET http://localhost:9999/?one=l HTTP/1.1"); @@ -981,22 +1065,18 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testMatrixParamExtractor() throws SecurityException, NoSuchMethodException, - IOException { + public void testMatrixParamExtractor() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPath.class.getMethod("oneMatrixParamExtractor", String.class); - HttpRequest request = factory(TestPath.class).createRequest(method, - new Object[] { "localhost" }); + HttpRequest request = factory(TestPath.class).createRequest(method, new Object[] { "localhost" }); assertRequestLineEquals(request, "GET http://localhost:9999/;one=l HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); } @Test - public void testFormParamExtractor() throws SecurityException, NoSuchMethodException, - IOException { + public void testFormParamExtractor() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPath.class.getMethod("oneFormParamExtractor", String.class); - HttpRequest request = factory(TestPath.class).createRequest(method, - new Object[] { "localhost" }); + HttpRequest request = factory(TestPath.class).createRequest(method, new Object[] { "localhost" }); assertRequestLineEquals(request, "POST http://localhost:9999/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "one=l", "application/x-www-form-urlencoded", false); @@ -1005,8 +1085,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testParamExtractorMethod() throws SecurityException, NoSuchMethodException { Method method = TestPath.class.getMethod("onePathParamExtractorMethod", String.class); - HttpRequest request = factory(TestPath.class).createRequest(method, - new Object[] { "localhost" }); + HttpRequest request = factory(TestPath.class).createRequest(method, new Object[] { "localhost" }); assertEquals(request.getEndpoint().getPath(), "/l"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); @@ -1042,17 +1121,15 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @Headers(keys = "x-amz-copy-source", values = "/{bucket}/{key}") - public void twoHeadersOutOfOrder(@PathParam("key") String path, - @PathParam("bucket") String path2) { + public void twoHeadersOutOfOrder(@PathParam("key") String path, @PathParam("bucket") String path2) { } } @Test - public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneHeader = TestHeader.class.getMethod("twoHeader", String.class); - Multimap headers = factory(TestHeader.class).createRequest(oneHeader, - new Object[] { "robot" }).getHeaders(); + Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) + .getHeaders(); assertEquals(headers.size(), 2); assertEquals(headers.get("slash"), Collections.singletonList("/robot")); assertEquals(headers.get("hyphen"), Collections.singletonList("-robot")); @@ -1066,42 +1143,38 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneHeader = TestClassHeader.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestClassHeader.class).createRequest(oneHeader, - new Object[] { "robot" }).getHeaders(); + new Object[] { "robot" }).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); } @Test - public void testBuildOneHeader() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneHeader = TestHeader.class.getMethod("oneHeader", String.class); - Multimap headers = factory(TestHeader.class).createRequest(oneHeader, - new Object[] { "robot" }).getHeaders(); + Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) + .getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); } @Test - public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoHeaders = TestHeader.class.getMethod("twoHeaders", String.class, String.class); Multimap headers = factory(TestHeader.class).createRequest(twoHeaders, - new Object[] { "robot", "eggs" }).getHeaders(); + new Object[] { "robot", "eggs" }).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot/eggs")); } @Test public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method twoHeadersOutOfOrder = TestHeader.class.getMethod("twoHeadersOutOfOrder", - String.class, String.class); - Multimap headers = factory(TestHeader.class).createRequest( - twoHeadersOutOfOrder, new Object[] { "robot", "eggs" }).getHeaders(); + UnsupportedEncodingException { + Method twoHeadersOutOfOrder = TestHeader.class.getMethod("twoHeadersOutOfOrder", String.class, String.class); + Multimap headers = factory(TestHeader.class).createRequest(twoHeadersOutOfOrder, + new Object[] { "robot", "eggs" }).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/eggs/robot")); } @@ -1113,31 +1186,25 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testQueryInOptions() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method oneQuery = TestQueryReplace.class.getMethod("queryInOptions", String.class, - TestReplaceQueryOptions.class); + public void testQueryInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + Method oneQuery = TestQueryReplace.class.getMethod("queryInOptions", String.class, TestReplaceQueryOptions.class); String query = factory(TestQueryReplace.class).createRequest(oneQuery, - new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); + new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); } private interface TestMapMatrixParams { @POST @Path("objects/{id}/action/{action}") - ListenableFuture action(@PathParam("id") String id, - @PathParam("action") String action, - @BinderParam(BindMapToMatrixParams.class) Map options); + ListenableFuture action(@PathParam("id") String id, @PathParam("action") String action, + @BinderParam(BindMapToMatrixParams.class) Map options); } - public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method method = TestMapMatrixParams.class.getMethod("action", String.class, String.class, - Map.class); + public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + Method method = TestMapMatrixParams.class.getMethod("action", String.class, String.class, Map.class); HttpRequest request = factory(TestMapMatrixParams.class).createRequest(method, - new Object[] { "robot", "kill", ImmutableMap.of("death", "slow") }); - assertRequestLineEquals(request, - "POST http://localhost:9999/objects/robot/action/kill;death=slow HTTP/1.1"); + new Object[] { "robot", "kill", ImmutableMap.of("death", "slow") }); + assertRequestLineEquals(request, "POST http://localhost:9999/objects/robot/action/kill;death=slow HTTP/1.1"); assertEquals(request.getHeaders().size(), 0); } @@ -1165,17 +1232,15 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @QueryParams(keys = "x-amz-copy-source", values = "/{bucket}/{key}") - public void twoQuerysOutOfOrder(@PathParam("key") String path, - @PathParam("bucket") String path2) { + public void twoQuerysOutOfOrder(@PathParam("key") String path, @PathParam("bucket") String path2) { } } @Test - public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestQueryReplace.class.getMethod("twoQuery", String.class); - String query = factory(TestQueryReplace.class).createRequest(oneQuery, - new Object[] { "robot" }).getEndpoint().getQuery(); + String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() + .getQuery(); assertEquals(query, "slash=/robot&hyphen=-robot"); } @@ -1187,39 +1252,35 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestClassQuery.class.getMethod("oneQuery", String.class); - String query = factory(TestClassQuery.class) - .createRequest(oneQuery, new Object[] { "robot" }).getEndpoint().getQuery(); + String query = factory(TestClassQuery.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() + .getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); } @Test - public void testBuildOneQuery() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestQueryReplace.class.getMethod("oneQuery", String.class); - String query = factory(TestQueryReplace.class).createRequest(oneQuery, - new Object[] { "robot" }).getEndpoint().getQuery(); + String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() + .getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); } @Test - public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoQuerys = TestQueryReplace.class.getMethod("twoQuerys", String.class, String.class); - String query = factory(TestQueryReplace.class).createRequest(twoQuerys, - new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); + String query = factory(TestQueryReplace.class).createRequest(twoQuerys, new Object[] { "robot", "eggs" }) + .getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot/eggs"); } @Test public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method twoQuerysOutOfOrder = TestQueryReplace.class.getMethod("twoQuerysOutOfOrder", - String.class, String.class); + UnsupportedEncodingException { + Method twoQuerysOutOfOrder = TestQueryReplace.class.getMethod("twoQuerysOutOfOrder", String.class, String.class); String query = factory(TestQueryReplace.class).createRequest(twoQuerysOutOfOrder, - new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); + new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/eggs/robot"); } @@ -1230,12 +1291,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testMatrixInOptions() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testMatrixInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestMatrixReplace.class.getMethod("matrixInOptions", String.class, - TestReplaceMatrixOptions.class); + TestReplaceMatrixOptions.class); String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, - new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath(); + new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath(); assertEquals(path, "/;x-amz-copy-source=/robot"); } @@ -1263,17 +1323,15 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @MatrixParams(keys = "x-amz-copy-source", values = "/{bucket}/{key}") - public void twoMatrixsOutOfOrder(@PathParam("key") String path, - @PathParam("bucket") String path2) { + public void twoMatrixsOutOfOrder(@PathParam("key") String path, @PathParam("bucket") String path2) { } } @Test - public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestMatrixReplace.class.getMethod("twoMatrix", String.class); - String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, - new Object[] { "robot" }).getEndpoint().getPath(); + String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() + .getPath(); assertEquals(path, "/;slash=/robot;hyphen=-robot"); } @@ -1286,40 +1344,36 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestClassMatrix.class.getMethod("oneMatrix", String.class); - String path = factory(TestClassMatrix.class).createRequest(oneMatrix, - new Object[] { "robot" }).getEndpoint().getPath(); + String path = factory(TestClassMatrix.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() + .getPath(); assertEquals(path, "/;x-amz-copy-source=/robot"); } @Test - public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestMatrixReplace.class.getMethod("oneMatrix", String.class); - String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, - new Object[] { "robot" }).getEndpoint().getPath(); + String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() + .getPath(); assertEquals(path, "/;x-amz-copy-source=/robot"); } @Test - public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method twoMatrixs = TestMatrixReplace.class.getMethod("twoMatrixs", String.class, - String.class); - String path = factory(TestMatrixReplace.class).createRequest(twoMatrixs, - new Object[] { "robot", "eggs" }).getEndpoint().getPath(); + public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + Method twoMatrixs = TestMatrixReplace.class.getMethod("twoMatrixs", String.class, String.class); + String path = factory(TestMatrixReplace.class).createRequest(twoMatrixs, new Object[] { "robot", "eggs" }) + .getEndpoint().getPath(); assertEquals(path, "/;x-amz-copy-source=/robot/eggs"); } @Test public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method twoMatrixsOutOfOrder = TestMatrixReplace.class.getMethod("twoMatrixsOutOfOrder", - String.class, String.class); + UnsupportedEncodingException { + Method twoMatrixsOutOfOrder = TestMatrixReplace.class.getMethod("twoMatrixsOutOfOrder", String.class, + String.class); String path = factory(TestMatrixReplace.class).createRequest(twoMatrixsOutOfOrder, - new Object[] { "robot", "eggs" }).getEndpoint().getPath(); + new Object[] { "robot", "eggs" }).getEndpoint().getPath(); assertEquals(path, "/;x-amz-copy-source=/eggs/robot"); } @@ -1358,18 +1412,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { ListenableFuture put(PayloadEnclosing payload); } - public void testPutPayloadEnclosing() throws SecurityException, NoSuchMethodException, - IOException { + public void testPutPayloadEnclosing() throws SecurityException, NoSuchMethodException, IOException { Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); HttpRequest request = factory(TestQuery.class).createRequest(method, - new PayloadEnclosingImpl(newStringPayload("whoops"))); + new PayloadEnclosingImpl(newStringPayload("whoops"))); assertRequestLineEquals(request, "PUT http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "whoops", "application/unknown", false); } - public void testPutPayloadEnclosingGenerateMD5() throws SecurityException, - NoSuchMethodException, IOException { + public void testPutPayloadEnclosingGenerateMD5() throws SecurityException, NoSuchMethodException, IOException { Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(newStringPayload("whoops")); @@ -1381,11 +1433,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "whoops", "application/unknown", true); } - public void testPutInputStreamPayloadEnclosingGenerateMD5() throws SecurityException, - NoSuchMethodException, IOException { + public void testPutInputStreamPayloadEnclosingGenerateMD5() throws SecurityException, NoSuchMethodException, + IOException { Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); - PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl( - newInputStreamPayload(toInputStream("whoops"))); + PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(newInputStreamPayload(toInputStream("whoops"))); encryptionService.generateMD5BufferingIfNotRepeatable(payloadEnclosing); HttpRequest request = factory(TestQuery.class).createRequest(method, payloadEnclosing); @@ -1395,11 +1446,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "whoops", "application/unknown", true); } - public void testPutPayloadChunkedNoContentLength() throws SecurityException, - NoSuchMethodException, IOException { + public void testPutPayloadChunkedNoContentLength() throws SecurityException, NoSuchMethodException, IOException { Method method = TestTransformers.class.getMethod("putXfer", Payload.class); - HttpRequest request = factory(TestQuery.class).createRequest(method, - newStringPayload("whoops")); + HttpRequest request = factory(TestQuery.class).createRequest(method, newStringPayload("whoops")); assertRequestLineEquals(request, "PUT http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Transfer-Encoding: chunked\n"); assertPayloadEquals(request, "whoops", "application/unknown", false); @@ -1407,15 +1456,14 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testPutPayload() throws SecurityException, NoSuchMethodException, IOException { Method method = TestTransformers.class.getMethod("put", Payload.class); - HttpRequest request = factory(TestQuery.class).createRequest(method, - newStringPayload("whoops")); + HttpRequest request = factory(TestQuery.class).createRequest(method, newStringPayload("whoops")); assertRequestLineEquals(request, "PUT http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "whoops", "application/unknown", false); } - public void testPutPayloadWithGeneratedMD5AndNoContentType() throws SecurityException, - NoSuchMethodException, IOException { + public void testPutPayloadWithGeneratedMD5AndNoContentType() throws SecurityException, NoSuchMethodException, + IOException { Payload payload = newStringPayload("whoops"); payload = encryptionService.generateMD5BufferingIfNotRepeatable(payload); Method method = TestTransformers.class.getMethod("put", Payload.class); @@ -1426,16 +1474,15 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test(expectedExceptions = IllegalArgumentException.class) - public void testPutInputStreamPayloadWithNoLengthThrowsException() throws SecurityException, - NoSuchMethodException, IOException { + public void testPutInputStreamPayloadWithNoLengthThrowsException() throws SecurityException, NoSuchMethodException, + IOException { Payload payload = newInputStreamPayload(toInputStream("whoops")); encryptionService.generateMD5BufferingIfNotRepeatable(payload); Method method = TestTransformers.class.getMethod("put", Payload.class); factory(TestQuery.class).createRequest(method, payload); } - public void testPutInputStreamPayload() throws SecurityException, NoSuchMethodException, - IOException { + public void testPutInputStreamPayload() throws SecurityException, NoSuchMethodException, IOException { Payload payload = newInputStreamPayload(toInputStream("whoops")); payload.setContentLength((long) "whoops".length()); Method method = TestTransformers.class.getMethod("put", Payload.class); @@ -1445,8 +1492,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "whoops", "application/unknown", false); } - public void testPutInputStreamPayloadWithMD5() throws SecurityException, NoSuchMethodException, - IOException { + public void testPutInputStreamPayloadWithMD5() throws SecurityException, NoSuchMethodException, IOException { Payload payload = newStringPayload("whoops"); payload.setContentLength((long) "whoops".length()); payload.setContentMD5(encryptionService.md5(toInputStream("whoops"))); @@ -1457,40 +1503,38 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertPayloadEquals(request, "whoops", "application/unknown", true); } - @SuppressWarnings("static-access") public void testInputStream() throws SecurityException, NoSuchMethodException { Method method = TestTransformers.class.getMethod("inputStream"); - Class> transformer = factory(TestTransformers.class) - .getParserOrThrowException(method); + Class> transformer = unwrap(factory(TestTransformers.class), method); assertEquals(transformer, ReturnInputStream.class); } - @SuppressWarnings("static-access") public void testInputStreamListenableFuture() throws SecurityException, NoSuchMethodException { Method method = TestTransformers.class.getMethod("futureInputStream"); - Class> transformer = factory(TestTransformers.class) - .getParserOrThrowException(method); + Class> transformer = unwrap(factory(TestTransformers.class), method); assertEquals(transformer, ReturnInputStream.class); } - @SuppressWarnings("static-access") + @SuppressWarnings("unchecked") + public static Class> unwrap(RestAnnotationProcessor processor, + Method method) { + return (Class>) RestAnnotationProcessor.getParserOrThrowException(method) + .getTypeLiteral().getRawType(); + } + public void testURI() throws SecurityException, NoSuchMethodException { Method method = TestTransformers.class.getMethod("uri"); - Class> transformer = factory(TestTransformers.class) - .getParserOrThrowException(method); + Class> transformer = unwrap(factory(TestTransformers.class), method); assertEquals(transformer, ParseURIFromListOrLocationHeaderIf20x.class); } - @SuppressWarnings("static-access") public void testURIListenableFuture() throws SecurityException, NoSuchMethodException { Method method = TestTransformers.class.getMethod("futureUri"); - Class> transformer = factory(TestTransformers.class) - .getParserOrThrowException(method); + Class> transformer = unwrap(factory(TestTransformers.class), method); assertEquals(transformer, ParseURIFromListOrLocationHeaderIf20x.class); } - public static class ReturnStringIf200Context extends ReturnStringIf2xx implements - InvocationContext { + public static class ReturnStringIf200Context extends ReturnStringIf2xx implements InvocationContext { public HttpRequest request; @@ -1511,18 +1555,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void oneTransformerWithContext() throws SecurityException, NoSuchMethodException { RestAnnotationProcessor processor = factory(TestTransformers.class); Method method = TestTransformers.class.getMethod("oneTransformerWithContext"); - GeneratedHttpRequest request = new GeneratedHttpRequest( - "GET", URI.create("http://localhost"), TestTransformers.class, method); + GeneratedHttpRequest request = new GeneratedHttpRequest("GET", URI + .create("http://localhost"), TestTransformers.class, method); Function transformer = processor.createResponseParser(method, request); assertEquals(transformer.getClass(), ReturnStringIf200Context.class); assertEquals(((ReturnStringIf200Context) transformer).request, request); } - @SuppressWarnings("static-access") public void testOneTransformer() throws SecurityException, NoSuchMethodException { Method method = TestTransformers.class.getMethod("oneTransformer"); - Class> transformer = factory(TestTransformers.class) - .getParserOrThrowException(method); + Class> transformer = unwrap(factory(TestTransformers.class), method); assertEquals(transformer, ReturnStringIf2xx.class); } @@ -1540,8 +1582,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @Path("/{id}") @ResponseParser(ReturnStringIf2xx.class) - ListenableFuture get(@PathParam("id") String id, - @HeaderParam(HttpHeaders.HOST) String host); + ListenableFuture get(@PathParam("id") String id, @HeaderParam(HttpHeaders.HOST) String host); @GET @Path("/{id}") @@ -1556,7 +1597,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @PUT @Path("/{id}") ListenableFuture put(@PathParam("id") @ParamParser(FirstCharacter.class) String id, - @BinderParam(BindToStringPayload.class) String payload); + @BinderParam(BindToStringPayload.class) String payload); @PUT @Path("/{id}") @@ -1568,42 +1609,36 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Headers(keys = "foo", values = "--{id}--") @ResponseParser(ReturnTrueIf2xx.class) ListenableFuture putHeader(@PathParam("id") String id, - @BinderParam(BindToStringPayload.class) String payload); + @BinderParam(BindToStringPayload.class) String payload); } - public void testCreateGetVarArgOptionsThatProducesHeaders() throws SecurityException, - NoSuchMethodException { + public void testCreateGetVarArgOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { Date date = new Date(); GetOptions options = GetOptions.Builder.ifModifiedSince(date); HttpRequestOptions[] optionsHolder = new HttpRequestOptions[] {}; Method method = TestRequest.class.getMethod("get", String.class, optionsHolder.getClass()); - HttpRequest request = factory(TestRequest.class).createRequest(method, - new Object[] { "1", options }); + HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { "1", options }); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 2); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections - .singletonList("localhost")); - assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections - .singletonList(dateService.rfc822DateFormat(date))); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); + assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService + .rfc822DateFormat(date))); } - public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, - NoSuchMethodException { + public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { Date date = new Date(); GetOptions options = GetOptions.Builder.ifModifiedSince(date); Method method = TestRequest.class.getMethod("get", String.class, HttpRequestOptions.class); - HttpRequest request = factory(TestRequest.class).createRequest(method, - new Object[] { "1", options }); + HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { "1", options }); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 2); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections - .singletonList("localhost")); - assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections - .singletonList(dateService.rfc822DateFormat(date))); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); + assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService + .rfc822DateFormat(date))); } public class PrefixOptions extends BaseHttpRequestOptions { @@ -1613,12 +1648,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } } - public void testCreateGetOptionsThatProducesQuery() throws SecurityException, - NoSuchMethodException, IOException { + public void testCreateGetOptionsThatProducesQuery() throws SecurityException, NoSuchMethodException, IOException { PrefixOptions options = new PrefixOptions().withPrefix("1"); Method method = TestRequest.class.getMethod("get", String.class, HttpRequestOptions.class); - HttpRequest request = factory(TestRequest.class).createRequest(method, - new Object[] { "1", options }); + HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { "1", options }); assertRequestLineEquals(request, "GET http://localhost:9999/1?prefix=1 HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: localhost\n"); assertPayloadEquals(request, null, null, false); @@ -1651,11 +1684,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } } - public void testCreateGetOptionsThatProducesPayload() throws SecurityException, - NoSuchMethodException, IOException { + public void testCreateGetOptionsThatProducesPayload() throws SecurityException, NoSuchMethodException, IOException { PayloadOptions options = new PayloadOptions(); - Method method = TestRequest.class.getMethod("putOptions", String.class, - HttpRequestOptions.class); + Method method = TestRequest.class.getMethod("putOptions", String.class, HttpRequestOptions.class); HttpRequest request = factory(TestRequest.class).createRequest(method, "1", options); assertRequestLineEquals(request, "PUT http://localhost:9999/1 HTTP/1.1"); @@ -1670,18 +1701,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test(dataProvider = "strings") public void testCreateGetRequest(String key) throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + UnsupportedEncodingException { Method method = TestRequest.class.getMethod("get", String.class, String.class); - HttpRequest request = factory(TestRequest.class).createRequest(method, - new Object[] { key, "localhost" }); + HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { key, "localhost" }); assertEquals(request.getEndpoint().getHost(), "localhost"); String expectedPath = "/" + URLEncoder.encode(key, "UTF-8").replaceAll("\\+", "%20"); assertEquals(request.getEndpoint().getRawPath(), expectedPath); assertEquals(request.getEndpoint().getPath(), "/" + key); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections - .singletonList("localhost")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); } public void testCreatePutRequest() throws SecurityException, NoSuchMethodException, IOException { @@ -1715,13 +1744,12 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testVirtualHostMethod() throws SecurityException, NoSuchMethodException { Method method = TestVirtualHostMethod.class.getMethod("get", String.class, String.class); HttpRequest request = factory(TestVirtualHostMethod.class).createRequest(method, - new Object[] { "1", "localhost" }); + new Object[] { "1", "localhost" }); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections - .singletonList("localhost")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); } public interface TestVirtualHost { @@ -1732,29 +1760,25 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @Path("/{id}") - ListenableFuture getPrefix(@PathParam("id") String id, - @BinderParam(BindAsHostPrefix.class) String foo); + ListenableFuture getPrefix(@PathParam("id") String id, @BinderParam(BindAsHostPrefix.class) String foo); } @Test public void testVirtualHost() throws SecurityException, NoSuchMethodException { Method method = TestVirtualHost.class.getMethod("get", String.class, String.class); - HttpRequest request = factory(TestVirtualHost.class).createRequest(method, - new Object[] { "1", "localhost" }); + HttpRequest request = factory(TestVirtualHost.class).createRequest(method, new Object[] { "1", "localhost" }); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections - .singletonList("localhost")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); } @Test public void testHostPrefix() throws SecurityException, NoSuchMethodException { Method method = TestVirtualHost.class.getMethod("getPrefix", String.class, String.class); - HttpRequest request = factory(TestVirtualHost.class).createRequest(method, - new Object[] { "1", "holy" }); + HttpRequest request = factory(TestVirtualHost.class).createRequest(method, new Object[] { "1", "holy" }); assertEquals(request.getEndpoint().getHost(), "holy.localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); @@ -1777,13 +1801,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @GET - public void twoDifferentHeaders(@HeaderParam("header1") String header1, - @HeaderParam("header2") String header2) { + public void twoDifferentHeaders(@HeaderParam("header1") String header1, @HeaderParam("header2") String header2) { } @GET - public void twoSameHeaders(@HeaderParam("header") String header1, - @HeaderParam("header") String header2) { + public void twoSameHeaders(@HeaderParam("header") String header1, @HeaderParam("header") String header2) { } } @@ -1791,7 +1813,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneHeader() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, "robot"); + ImmutableMultimap. of().entries(), method, "robot"); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), Collections.singletonList("robot")); } @@ -1800,17 +1822,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneIntHeader() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("oneIntHeader", int.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, 1); + ImmutableMultimap. of().entries(), method, 1); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), Collections.singletonList("1")); } @Test public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException { - Method method = TestHeaders.class - .getMethod("twoDifferentHeaders", String.class, String.class); + Method method = TestHeaders.class.getMethod("twoDifferentHeaders", String.class, String.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, "robot", "egg"); + ImmutableMultimap. of().entries(), method, "robot", "egg"); assertEquals(headers.size(), 2); assertEquals(headers.get("header1"), Collections.singletonList("robot")); assertEquals(headers.get("header2"), Collections.singletonList("egg")); @@ -1820,7 +1841,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("twoSameHeaders", String.class, String.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, "robot", "egg"); + ImmutableMultimap. of().entries(), method, "robot", "egg"); assertEquals(headers.size(), 2); Collection values = headers.get("header"); assert values.contains("robot"); @@ -1834,11 +1855,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @PUT @Path("{foo}") public ListenableFuture putWithPath(@PathParam("foo") String path, - @BinderParam(BindToStringPayload.class) String content); + @BinderParam(BindToStringPayload.class) String content); @PUT public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1, - @BinderParam(BindToStringPayload.class) String payload2); + @BinderParam(BindToStringPayload.class) String payload2); } @Test @@ -1893,17 +1914,14 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST @FormParams(keys = "x-amz-copy-source", values = "/{bucket}/{key}") - public void twoFormsOutOfOrder(@PathParam("key") String path, - @PathParam("bucket") String path2) { + public void twoFormsOutOfOrder(@PathParam("key") String path, @PathParam("bucket") String path2) { } } @Test - public void testBuildTwoForm() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoForm() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneForm = TestFormReplace.class.getMethod("twoForm", String.class); - Object form = factory(TestFormReplace.class).createRequest(oneForm, "robot").getPayload() - .getRawContent(); + Object form = factory(TestFormReplace.class).createRequest(oneForm, "robot").getPayload().getRawContent(); assertEquals(form, "slash=/robot&hyphen=-robot"); } @@ -1916,67 +1934,58 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneForm = TestClassForm.class.getMethod("oneForm", String.class); - Object form = factory(TestClassForm.class).createRequest(oneForm, "robot").getPayload() - .getRawContent(); + Object form = factory(TestClassForm.class).createRequest(oneForm, "robot").getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); } @Test - public void testBuildOneForm() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildOneForm() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneForm = TestFormReplace.class.getMethod("oneForm", String.class); - Object form = factory(TestFormReplace.class).createRequest(oneForm, "robot").getPayload() - .getRawContent(); + Object form = factory(TestFormReplace.class).createRequest(oneForm, "robot").getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); } @Test - public void testBuildTwoForms() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoForms() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoForms = TestFormReplace.class.getMethod("twoForms", String.class, String.class); - Object form = factory(TestFormReplace.class).createRequest(twoForms, "robot", "eggs") - .getPayload().getRawContent(); + Object form = factory(TestFormReplace.class).createRequest(twoForms, "robot", "eggs").getPayload() + .getRawContent(); assertEquals(form, "x-amz-copy-source=/robot/eggs"); } @Test public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { - Method twoFormsOutOfOrder = TestFormReplace.class.getMethod("twoFormsOutOfOrder", - String.class, String.class); - Object form = factory(TestFormReplace.class).createRequest(twoFormsOutOfOrder, "robot", - "eggs").getPayload().getRawContent(); + UnsupportedEncodingException { + Method twoFormsOutOfOrder = TestFormReplace.class.getMethod("twoFormsOutOfOrder", String.class, String.class); + Object form = factory(TestFormReplace.class).createRequest(twoFormsOutOfOrder, "robot", "eggs").getPayload() + .getRawContent(); assertEquals(form, "x-amz-copy-source=/eggs/robot"); } @SuppressWarnings("unchecked") private RestAnnotationProcessor factory(Class clazz) { return ((RestAnnotationProcessor) injector.getInstance(Key.get(newParameterizedType( - RestAnnotationProcessor.class, clazz)))); + RestAnnotationProcessor.class, clazz)))); } DateService dateService = new SimpleDateFormatDateService(); @BeforeClass void setupFactory() { - ContextSpec contextSpec = contextSpec("test", "http://localhost:9999", "1", - "userfoo", null, String.class, Integer.class); + ContextSpec contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, + String.class, Integer.class); - injector = createContextBuilder( - contextSpec, - ImmutableSet. of(new MockModule(), new NullLoggingModule(), - new AbstractModule() { + injector = createContextBuilder(contextSpec, + ImmutableSet. of(new MockModule(), new NullLoggingModule(), new AbstractModule() { - @Override - protected void configure() { - bind(URI.class).annotatedWith(Localhost2.class).toInstance( - URI.create("http://localhost:1111")); - } + @Override + protected void configure() { + bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111")); + } - })).buildInjector(); + })).buildInjector(); parserFactory = injector.getInstance(ParseSax.Factory.class); encryptionService = injector.getInstance(EncryptionService.class); } diff --git a/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/config/JschSshClientModule.java b/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/config/JschSshClientModule.java index aa6f9f0ead..3128d9c749 100755 --- a/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/config/JschSshClientModule.java +++ b/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/config/JschSshClientModule.java @@ -51,7 +51,8 @@ public class JschSshClientModule extends AbstractModule { protected void configure() { bind(SshClient.Factory.class).to(Factory.class).in(Scopes.SINGLETON); - bind(SocketOpen.class).to(InetSocketAddressConnect.class).in(Scopes.SINGLETON); + bind(SocketOpen.class).to(InetSocketAddressConnect.class).in( + Scopes.SINGLETON); } private static class Factory implements SshClient.Factory { @@ -64,27 +65,30 @@ public class JschSshClientModule extends AbstractModule { @SuppressWarnings("unused") @Inject - public Factory(BackoffLimitedRetryHandler backoffLimitedRetryHandler, Injector injector) { + public Factory(BackoffLimitedRetryHandler backoffLimitedRetryHandler, + Injector injector) { this.backoffLimitedRetryHandler = backoffLimitedRetryHandler; this.injector = injector; } public SshClient create(IPSocket socket, String username, String password) { - SshClient client = new JschSshClient(backoffLimitedRetryHandler, socket, timeout, - username, password, null); + SshClient client = new JschSshClient(backoffLimitedRetryHandler, + socket, timeout, username, password, null); injector.injectMembers(client);// add logger return client; } - public SshClient create(IPSocket socket, String username, byte[] privateKey) { - SshClient client = new JschSshClient(backoffLimitedRetryHandler, socket, timeout, - username, null, privateKey); + public SshClient create(IPSocket socket, String username, + byte[] privateKey) { + SshClient client = new JschSshClient(backoffLimitedRetryHandler, + socket, timeout, username, null, privateKey); injector.injectMembers(client);// add logger return client; } @Override - public Map generateRSAKeyPair(String comment, String passphrase) { + public Map generateRSAKeyPair(String comment, + String passphrase) { KeyPair pair = null; try { pair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA); @@ -97,9 +101,9 @@ public class JschSshClientModule extends AbstractModule { pair.writePrivateKey(privateKey); ByteArrayOutputStream publicKey = new ByteArrayOutputStream(); pair.writePublicKey(publicKey, comment); - return ImmutableMap.of("comment", comment, "passphrase", passphrase, "private", - new String(privateKey.toByteArray()), "public", new String(publicKey - .toByteArray())); + return ImmutableMap.of("comment", comment, "passphrase", passphrase, + "private", new String(privateKey.toByteArray()), "public", + new String(publicKey.toByteArray())); } } } \ No newline at end of file diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseErrorFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseErrorFromJsonResponse.java index 3615936755..e5167b6746 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseErrorFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseErrorFromJsonResponse.java @@ -23,19 +23,15 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.SortedSet; import javax.inject.Inject; import org.jclouds.gogrid.domain.internal.ErrorResponse; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; import com.google.inject.Singleton; /** @@ -47,24 +43,20 @@ import com.google.inject.Singleton; * @author Oleksiy Yarmula */ @Singleton -public class ParseErrorFromJsonResponse extends - ParseJson> { +public class ParseErrorFromJsonResponse implements + Function> { + + private final ParseJson> json; @Inject - ParseErrorFromJsonResponse(Gson gson) { - super(gson); + ParseErrorFromJsonResponse( + ParseJson> json) { + this.json = json; } - public SortedSet apply(InputStream stream) { - Type setType = new TypeToken>() { - }.getType(); - GenericResponseContainer response; - try { - response = gson.fromJson(new InputStreamReader(stream, "UTF-8"), - setType); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - return response.getList(); + @Override + public SortedSet apply(HttpResponse arg0) { + return json.apply(arg0).getList(); } + } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageFromJsonResponse.java index 4cc6b7168a..9db591896e 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageFromJsonResponse.java @@ -18,32 +18,31 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.util.SortedSet; - import javax.inject.Inject; import org.jclouds.gogrid.domain.ServerImage; -import org.jclouds.http.functions.ParseJson; +import org.jclouds.http.HttpResponse; +import com.google.common.base.Function; import com.google.common.collect.Iterables; -import com.google.gson.Gson; import com.google.inject.Singleton; /** * @author Oleksiy Yarmula */ @Singleton -public class ParseImageFromJsonResponse extends ParseJson { +public class ParseImageFromJsonResponse implements + Function { + private final ParseImageListFromJsonResponse parser; @Inject - ParseImageFromJsonResponse(Gson gson) { - super(gson); + ParseImageFromJsonResponse(ParseImageListFromJsonResponse parser) { + this.parser = parser; } - public ServerImage apply(InputStream stream) { - SortedSet allImages = new ParseImageListFromJsonResponse( - gson).apply(stream); - return Iterables.getOnlyElement(allImages); + @Override + public ServerImage apply(HttpResponse arg0) { + return Iterables.getOnlyElement(parser.apply(arg0)); } + } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageListFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageListFromJsonResponse.java index 1e90f31cc0..d57468112a 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageListFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageListFromJsonResponse.java @@ -18,43 +18,35 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.SortedSet; import javax.inject.Inject; import org.jclouds.gogrid.domain.ServerImage; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; import com.google.inject.Singleton; /** * @author Oleksiy Yarmula */ @Singleton -public class ParseImageListFromJsonResponse extends - ParseJson> { +public class ParseImageListFromJsonResponse implements + Function> { + + private final ParseJson> json; @Inject - ParseImageListFromJsonResponse(Gson gson) { - super(gson); + ParseImageListFromJsonResponse( + ParseJson> json) { + this.json = json; } - public SortedSet apply(InputStream stream) { - Type setType = new TypeToken>() { - }.getType(); - GenericResponseContainer response; - try { - response = gson.fromJson(new InputStreamReader(stream, "UTF-8"), - setType); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - return response.getList(); + @Override + public SortedSet apply(HttpResponse arg0) { + return json.apply(arg0).getList(); } -} + +} \ No newline at end of file diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseIpListFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseIpListFromJsonResponse.java index a0ea0f76e3..77f90ff58d 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseIpListFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseIpListFromJsonResponse.java @@ -18,19 +18,15 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.SortedSet; import javax.inject.Inject; import org.jclouds.gogrid.domain.Ip; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; import com.google.inject.Singleton; /** @@ -39,23 +35,19 @@ import com.google.inject.Singleton; * @author Oleksiy Yarmula */ @Singleton -public class ParseIpListFromJsonResponse extends ParseJson> { +public class ParseIpListFromJsonResponse implements + Function> { + + private final ParseJson> json; @Inject - ParseIpListFromJsonResponse(Gson gson) { - super(gson); + ParseIpListFromJsonResponse(ParseJson> json) { + this.json = json; } - public SortedSet apply(InputStream stream) { - Type setType = new TypeToken>() { - }.getType(); - GenericResponseContainer response; - try { - response = gson.fromJson(new InputStreamReader(stream, "UTF-8"), - setType); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - return response.getList(); + @Override + public SortedSet apply(HttpResponse arg0) { + return json.apply(arg0).getList(); } + } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseJobListFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseJobListFromJsonResponse.java index 447cf0618e..fed1ff75af 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseJobListFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseJobListFromJsonResponse.java @@ -18,19 +18,15 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.SortedSet; import javax.inject.Inject; import org.jclouds.gogrid.domain.Job; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; import com.google.inject.Singleton; /** @@ -39,23 +35,19 @@ import com.google.inject.Singleton; * @author Oleksiy Yarmula */ @Singleton -public class ParseJobListFromJsonResponse extends ParseJson> { +public class ParseJobListFromJsonResponse implements + Function> { + + private final ParseJson> json; @Inject - ParseJobListFromJsonResponse(Gson gson) { - super(gson); + ParseJobListFromJsonResponse(ParseJson> json) { + this.json = json; } - public SortedSet apply(InputStream stream) { - Type setType = new TypeToken>() { - }.getType(); - GenericResponseContainer response; - try { - response = gson.fromJson(new InputStreamReader(stream, "UTF-8"), - setType); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - return response.getList(); + @Override + public SortedSet apply(HttpResponse arg0) { + return json.apply(arg0).getList(); } + } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerFromJsonResponse.java index 0ed46a6c33..bf67e8b1dc 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerFromJsonResponse.java @@ -18,16 +18,14 @@ */ package org.jclouds.gogrid.functions; -import com.google.common.collect.Iterables; -import com.google.gson.Gson; -import com.google.inject.Singleton; +import javax.inject.Inject; import org.jclouds.gogrid.domain.LoadBalancer; -import org.jclouds.http.functions.ParseJson; +import org.jclouds.http.HttpResponse; -import javax.inject.Inject; -import java.io.InputStream; -import java.util.SortedSet; +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import com.google.inject.Singleton; /** * Parses the single load balancer out of the response. @@ -38,17 +36,19 @@ import java.util.SortedSet; * @author Oleksiy Yarmula */ @Singleton -public class ParseLoadBalancerFromJsonResponse extends ParseJson { +public class ParseLoadBalancerFromJsonResponse implements + Function { + private final ParseLoadBalancerListFromJsonResponse parser; @Inject - ParseLoadBalancerFromJsonResponse(Gson gson) { - super(gson); + ParseLoadBalancerFromJsonResponse( + ParseLoadBalancerListFromJsonResponse parser) { + this.parser = parser; } - public LoadBalancer apply(InputStream stream) { - SortedSet allLoadBalancers = new ParseLoadBalancerListFromJsonResponse( - gson).apply(stream); - return Iterables.getOnlyElement(allLoadBalancers); + @Override + public LoadBalancer apply(HttpResponse arg0) { + return Iterables.getOnlyElement(parser.apply(arg0)); } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerListFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerListFromJsonResponse.java index 85c631aedc..80362be9dc 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerListFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerListFromJsonResponse.java @@ -18,19 +18,15 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.SortedSet; import javax.inject.Inject; import org.jclouds.gogrid.domain.LoadBalancer; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; import com.google.inject.Singleton; /** @@ -40,24 +36,20 @@ import com.google.inject.Singleton; * @author Oleksiy Yarmula */ @Singleton -public class ParseLoadBalancerListFromJsonResponse extends - ParseJson> { +public class ParseLoadBalancerListFromJsonResponse implements + Function> { + + private final ParseJson> json; @Inject - ParseLoadBalancerListFromJsonResponse(Gson gson) { - super(gson); + ParseLoadBalancerListFromJsonResponse( + ParseJson> json) { + this.json = json; } - public SortedSet apply(InputStream stream) { - Type setType = new TypeToken>() { - }.getType(); - GenericResponseContainer response; - try { - response = gson.fromJson(new InputStreamReader(stream, "UTF-8"), - setType); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("jclouds requires UTF-8 encoding", e); - } - return response.getList(); + @Override + public SortedSet apply(HttpResponse arg0) { + return json.apply(arg0).getList(); } -} + +} \ No newline at end of file diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseOptionsFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseOptionsFromJsonResponse.java index 922f81a6a8..028c7423ea 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseOptionsFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseOptionsFromJsonResponse.java @@ -18,46 +18,38 @@ */ package org.jclouds.gogrid.functions; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; import java.util.SortedSet; import javax.inject.Inject; import org.jclouds.gogrid.domain.Option; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseJson; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.base.Function; import com.google.inject.Singleton; /** * Parses the list of generic options. * - * GoGrid uses options as containers for id/name/description objects. + * GoGrid uses options as containers for id/name/descrOptiontion objects. * * @author Oleksiy Yarmula */ @Singleton -public class ParseOptionsFromJsonResponse extends ParseJson> { +public class ParseOptionsFromJsonResponse implements + Function> { + + private final ParseJson> json; @Inject - ParseOptionsFromJsonResponse(Gson gson) { - super(gson); + ParseOptionsFromJsonResponse(ParseJson> json) { + this.json = json; } - public SortedSet