From 60b6b68556889d7f14f876410c6c52ab65859f0f Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Thu, 30 Dec 2010 23:40:23 +0100 Subject: [PATCH] code cleanup: http request immutability (except payload), builders, test backfill --- .../saas/AtmosStorageAsyncClient.java | 1 - .../saas/AtmosStorageResponseException.java | 4 +- .../saas/binders/BindMetadataToHeaders.java | 20 +- .../binders/BindUserMetadataToHeaders.java | 35 +- .../strategy/FindMD5InUserMetadata.java | 17 +- .../saas/config/AtmosObjectModule.java | 28 - .../atmosonline/saas/domain/AtmosObject.java | 11 +- .../atmosonline/saas/domain/BoundedSet.java | 7 +- .../atmosonline/saas/domain/UserMetadata.java | 76 ++- .../saas/domain/internal/AtmosObjectImpl.java | 30 +- .../domain/internal/BoundedLinkedHashSet.java | 83 +++ .../DelegatingMutableContentMetadata.java | 7 + .../atmosonline/saas/filters/SignRequest.java | 57 +- .../saas/functions/AtmosObjectName.java | 14 +- ...rseDirectoryListFromContentAndHeaders.java | 19 +- .../ParseObjectFromHeadersAndHttpContent.java | 16 +- .../ParseSystemMetadataFromHeaders.java | 17 +- .../ParseUserMetadataFromHeaders.java | 63 +- .../ReturnEndpointIfAlreadyExists.java | 18 +- .../AtmosStorageClientErrorRetryHandler.java | 2 +- .../ParseAtmosStorageErrorFromXmlContent.java | 14 +- .../saas/util/AtmosStorageUtils.java | 6 +- .../xml/ListDirectoryResponseHandler.java | 9 +- .../saas/AtmosStorageAsyncClientTest.java | 5 +- .../saas/AtmosStorageClientLiveTest.java | 15 +- .../saas/ProvidersInPropertiesTest.java | 4 +- .../binders/BindMetadataToHeadersTest.java | 89 +++ .../BindUserMetadataToHeadersTest.java | 62 +- .../blobstore/AtmosBlobRequestSignerTest.java | 8 +- .../config/AtmosBlobStoreModuleTest.java | 2 +- .../functions/ObjectToBlobMetadataTest.java | 2 +- ...ourceMetadataListToDirectoryEntryList.java | 4 +- .../integration/AtmosBlobSignerLiveTest.java | 2 +- ...osStorageContainerIntegrationLiveTest.java | 2 +- .../AtmosStorageContainerLiveTest.java | 2 +- ...rageInputStreamMapIntegrationLiveTest.java | 2 +- .../AtmosStorageIntegrationLiveTest.java | 2 +- .../integration/AtmosStorageLiveTest.java | 2 +- .../AtmosStorageMapIntegrationLiveTest.java | 2 +- ...tmosStorageServiceIntegrationLiveTest.java | 2 +- .../saas/filters/SignRequestTest.java | 95 +-- .../saas/functions/AtmosObjectNameTest.java | 69 +++ ...irectoryListFromContentAndHeadersTest.java | 79 +++ ...seObjectFromHeadersAndHttpContentTest.java | 66 +++ .../ParseSystemMetadataFromHeadersTest.java | 41 +- .../ParseUserMetadataFromHeadersTest.java | 48 ++ .../ReturnEndpointIfAlreadyExistsTest.java | 38 ++ .../saas/options/ListOptionsTest.java | 2 +- .../saas/xml/ErrorHandlerTest.java | 3 +- .../xml/ListDirectoryResponseHandlerTest.java | 15 +- .../org/jclouds/aws/AWSResponseException.java | 4 +- ...BlockDeviceMappingToIndexedFormParams.java | 35 +- .../BindBundleIdsToIndexedFormParams.java | 6 +- ...=> BindGroupNamesToIndexedFormParams.java} | 8 +- .../BindInstanceIdsToIndexedFormParams.java | 6 +- ...a => BindKeyNamesToIndexedFormParams.java} | 8 +- .../BindProductCodesToIndexedFormParams.java | 8 +- .../BindPublicIpsToIndexedFormParams.java | 10 +- .../BindS3UploadPolicyAndSignature.java | 16 +- .../BindUserGroupsToIndexedFormParams.java | 12 +- ...upPairToSourceSecurityGroupFormParams.java | 18 +- .../BindUserIdsToIndexedFormParams.java | 7 +- .../BindVolumeIdsToIndexedFormParams.java | 6 +- ...otNullBindAvailabilityZoneToFormParam.java | 8 +- .../aws/ec2/compute/EC2ComputeService.java | 6 +- .../RunningInstanceToNodeMetadata.java | 8 +- .../compute/options/EC2TemplateOptions.java | 10 +- .../ReturnVoidOnVolumeAvailable.java | 2 +- .../aws/ec2/services/KeyPairAsyncClient.java | 4 +- .../services/PlacementGroupAsyncClient.java | 4 +- .../services/SecurityGroupAsyncClient.java | 4 +- .../org/jclouds/aws/ec2/util/EC2Utils.java | 93 ++- ...dAvailabilityZonesToIndexedFormParams.java | 6 +- ...BindELBInstanceIdsToIndexedFormParams.java | 6 +- .../DescribeLoadBalancersResponseHandler.java | 1 - .../org/jclouds/aws/filters/FormSigner.java | 34 +- .../handlers/AWSClientErrorRetryHandler.java | 2 +- .../handlers/AWSRedirectionRetryHandler.java | 20 +- .../handlers/ParseAWSErrorFromXmlContent.java | 9 +- .../org/jclouds/aws/s3/S3AsyncClient.java | 4 +- .../aws/s3/binders/BindACLToXMLPayload.java | 21 +- .../binders/BindAsHostPrefixIfConfigured.java | 25 +- .../BindBucketLoggingToXmlPayload.java | 25 +- .../BindNoBucketLoggingToXmlPayload.java | 6 +- .../aws/s3/binders/BindPayerToXmlPayload.java | 14 +- ...ava => BindS3ObjectMetadataToRequest.java} | 30 +- .../jclouds/aws/s3/blobstore/S3BlobStore.java | 4 +- .../ScaleUpCloudBlobStoreContextModule.java | 4 +- .../s3/filters/RequestAuthorizeSignature.java | 77 ++- .../s3/functions/BindRegionToXmlPayload.java | 16 +- .../ParseObjectFromHeadersAndHttpContent.java | 5 +- .../ParseObjectMetadataFromHeaders.java | 5 +- .../ReturnFalseIfBucketAlreadyOwnedByYou.java | 2 +- ...urnTrueOn404OrNotFoundFalseIfNotEmpty.java | 2 +- .../jclouds/aws/s3/xml/ListBucketHandler.java | 4 +- ...teAndBlobStoreTogetherHappilyLiveTest.java | 2 +- .../aws/CredentialsStoredInBlobStoreTest.java | 4 +- .../aws/ProvidersInPropertiesTest.java | 4 +- .../cloudwatch/CloudWatchAsyncClientTest.java | 3 +- .../cloudwatch/CloudWatchClientLiveTest.java | 2 +- ...etMetricStatisticsResponseHandlerTest.java | 3 +- .../aws/config/AWSRestClientModuleTest.java | 2 +- ...icationArchitecturesEC2ClientLiveTest.java | 83 +-- .../aws/ec2/EBSBootEC2ClientLiveTest.java | 152 +++-- .../jclouds/aws/ec2/EC2AsyncClientTest.java | 5 +- ...kDeviceMappingToIndexedFormParamsTest.java | 75 +++ .../BindBundleIdsToIndexedFormParamsTest.java | 63 ++ ...BindGroupNamesToIndexedFormParamsTest.java | 63 ++ ...indInstanceIdsToIndexedFormParamsTest.java | 63 ++ .../BindKeyNamesToIndexedFormParamsTest.java | 63 ++ ...ndProductCodesToIndexedFormParamsTest.java | 64 ++ .../BindPublicIpsToIndexedFormParamsTest.java | 63 ++ .../BindS3UploadPolicyAndSignatureTest.java | 64 ++ ...BindUserGroupsToIndexedFormParamsTest.java | 69 +++ ...irToSourceSecurityGroupFormParamsTest.java | 66 +++ .../BindUserIdsToIndexedFormParamsTest.java | 64 ++ .../BindVolumeIdsToIndexedFormParamsTest.java | 63 ++ ...llBindAvailabilityZoneToFormParamTest.java | 65 ++ .../BlobStoreAndComputeServiceLiveTest.java | 3 +- .../compute/EC2ComputeServiceLiveTest.java | 2 +- .../EC2LoadBalancerServiceLiveTest.java | 2 +- .../compute/EC2TemplateBuilderLiveTest.java | 2 +- ...alyptusComputeServiceLiveTestDisabled.java | 2 +- .../NovaComputeServiceLiveTestDisabled.java | 2 +- .../NovaTemplateBuilderLiveTestDisabled.java | 2 +- .../functions/CreateUniqueKeyPairTest.java | 2 +- .../functions/CredentialsForInstanceTest.java | 48 +- .../compute/functions/ImageParserTest.java | 2 +- .../functions/RegionAndIdToImageTest.java | 8 +- .../RunningInstanceToNodeMetadataTest.java | 2 +- ...GroupsAsNeededAndReturnRunOptionsTest.java | 2 +- .../EC2RunNodesAndAddToSetStrategyTest.java | 25 +- ...encodedBytesToBase64EncodedStringTest.java | 2 +- .../aws/ec2/services/AMIAsyncClientTest.java | 3 +- .../aws/ec2/services/AMIClientLiveTest.java | 2 +- ...ilabilityZoneAndRegionAsyncClientTest.java | 3 +- ...ailabilityZoneAndRegionClientLiveTest.java | 2 +- .../ec2/services/BaseEC2AsyncClientTest.java | 8 +- .../ElasticBlockStoreAsyncClientTest.java | 3 +- .../ElasticBlockStoreClientLiveTest.java | 2 +- .../ElasticIPAddressAsyncClientTest.java | 3 +- .../ElasticIPAddressClientLiveTest.java | 2 +- .../ec2/services/InstanceAsyncClientTest.java | 3 +- .../ec2/services/InstanceClientLiveTest.java | 2 +- .../ec2/services/KeyPairAsyncClientTest.java | 3 +- .../ec2/services/KeyPairClientLiveTest.java | 2 +- .../services/MonitoringAsyncClientTest.java | 3 +- .../services/MonitoringClientLiveTest.java | 2 +- .../PlacementGroupAsyncClientTest.java | 3 +- .../PlacementGroupClientLiveTest.java | 2 +- .../SecurityGroupAsyncClientTest.java | 3 +- .../services/SecurityGroupClientLiveTest.java | 2 +- .../ec2/services/WindowsAsyncClientTest.java | 3 +- .../ec2/services/WindowsClientLiveTest.java | 2 +- .../jclouds/aws/ec2/utils/EC2UtilsTest.java | 2 +- .../AllocateAddressResponseHandlerTest.java | 3 +- .../aws/ec2/xml/AttachmentHandlerTest.java | 10 +- .../aws/ec2/xml/BaseEC2HandlerTest.java | 9 +- .../xml/BlockDeviceMappingHandlerTest.java | 3 +- .../aws/ec2/xml/BundleTaskHandlerTest.java | 7 +- .../xml/CreateVolumeResponseHandlerTest.java | 7 +- .../DescribeAddressesResponseHandlerTest.java | 5 +- ...eAvailabilityZonesResponseHandlerTest.java | 3 +- ...escribeBundleTasksResponseHandlerTest.java | 6 +- .../DescribeImagesResponseHandlerTest.java | 2 +- .../xml/DescribeInstanceAttributeTest.java | 5 +- .../DescribeInstancesResponseHandlerTest.java | 4 +- .../DescribeKeyPairsResponseHandlerTest.java | 8 +- ...ibePlacementGroupsResponseHandlerTest.java | 6 +- .../DescribeRegionsResponseHandlerTest.java | 11 +- ...dInstancesOfferingResponseHandlerTest.java | 6 +- ...ribeSecurityGroupsResponseHandlerTest.java | 8 +- .../DescribeSnapshotsResponseHandlerTest.java | 6 +- .../DescribeVolumesResponseHandlerTest.java | 6 +- .../xml/InstanceStateChangeHandlerTest.java | 6 +- .../ec2/xml/KeyPairResponseHandlerTest.java | 7 +- .../ec2/xml/MonitoringStateHandlerTest.java | 3 +- .../aws/ec2/xml/PermissionHandlerTest.java | 3 +- .../aws/ec2/xml/ProductCodesHandlerTest.java | 3 +- .../xml/RunInstancesResponseHandlerTest.java | 6 +- .../aws/ec2/xml/SnapshotHandlerTest.java | 7 +- .../jclouds/aws/elb/ELBAsyncClientTest.java | 3 +- .../jclouds/aws/elb/ELBClientLiveTest.java | 2 +- ...scribeLoadBalancerResponseHandlerTest.java | 8 +- ...esWithLoadBalancerResponseHandlerTest.java | 5 +- .../jclouds/aws/filters/FormSignerTest.java | 19 +- .../AWSClientErrorRetryHandlerTest.java | 2 +- .../ParseAWSErrorFromXmlContentTest.java | 6 +- .../jclouds/aws/s3/BaseS3AsyncClientTest.java | 6 + .../org/jclouds/aws/s3/S3AsyncClientTest.java | 106 ++-- .../org/jclouds/aws/s3/S3ClientLiveTest.java | 10 +- .../BindAsHostPrefixIfConfiguredTest.java | 21 +- .../BindBucketLoggingToXmlPayloadTest.java | 7 +- .../BindNoBucketLoggingToXmlPayloadTest.java | 10 +- .../BindS3ObjectMetadataToRequestTest.java | 131 ++++ .../s3/binders/BindS3ObjectToPayloadTest.java | 186 ------ .../s3/blobstore/S3BlobRequestSignerTest.java | 8 +- .../functions/BlobToHttpGetOptionsTest.java | 2 +- .../S3BlobIntegrationLiveTest.java | 2 +- .../blobstore/integration/S3BlobLiveTest.java | 2 +- .../S3BlobMapIntegrationLiveTest.java | 2 +- .../integration/S3BlobSignerLiveTest.java | 2 +- .../S3ContainerIntegrationLiveTest.java | 2 +- .../integration/S3ContainerLiveTest.java | 2 +- .../S3InputStreamMapIntegrationLiveTest.java | 2 +- .../S3ServiceIntegrationLiveTest.java | 2 +- .../aws/s3/config/S3RestClientModuleTest.java | 2 +- .../RequestAuthorizeSignatureTest.java | 8 +- .../ParseObjectMetadataFromHeadersTest.java | 17 +- .../aws/s3/options/CopyObjectOptionsTest.java | 2 +- .../aws/s3/options/PutBucketOptionsTest.java | 2 +- .../aws/s3/options/PutObjectOptionsTest.java | 2 +- .../aws/s3/services/BucketsLiveTest.java | 6 +- .../s3/xml/AccessControlListHandlerTest.java | 14 +- .../aws/s3/xml/BucketLoggingHandlerTest.java | 10 +- .../aws/s3/xml/CopyObjectHandlerTest.java | 3 +- .../aws/s3/xml/ListBucketHandlerTest.java | 96 ++- .../jclouds/aws/s3/xml/PayerHandlerTest.java | 14 +- .../org/jclouds/aws/s3/xml/S3ParserTest.java | 11 +- .../aws/simpledb/SimpleDBAsyncClientTest.java | 3 +- .../aws/simpledb/SimpleDBClientLiveTest.java | 2 +- .../config/SimpleDBRestClientModuleTest.java | 2 +- .../xml/ListDomainsResponseHandlerTest.java | 3 +- .../jclouds/aws/sqs/SQSAsyncClientTest.java | 3 +- .../jclouds/aws/sqs/SQSClientLiveTest.java | 2 +- .../sqs/config/SQSRestClientModuleTest.java | 2 +- .../xml/ListQueuesResponseHandlerTest.java | 3 +- .../org/jclouds/aws/util/AWSUtilsTest.java | 18 +- .../org/jclouds/aws/xml/ErrorHandlerTest.java | 14 +- .../functest/GoogleAppEngineLiveTest.java | 10 +- .../aws/s3/AmazonPerformanceLiveTest.java | 2 +- .../JCloudsApacheHCPerformanceLiveTest.java | 2 +- .../aws/s3/JCloudsGaePerformanceLiveTest.java | 2 +- .../aws/s3/JCloudsPerformanceLiveTest.java | 2 +- .../aws/s3/Jets3tPerformanceLiveTest.java | 2 +- .../AzureStoragePropertiesBuilder.java | 4 +- .../storage/blob/AzureBlobAsyncClient.java | 5 +- .../BindAzureBlobMetadataToRequest.java | 80 +++ .../blob/binders/BindAzureBlobToPayload.java | 66 --- .../blobstore/functions/AzureBlobToBlob.java | 4 +- .../BlobPropertiesToBlobMetadata.java | 4 +- .../ParseBlobFromHeadersAndHttpContent.java | 4 +- .../ParseBlobPropertiesFromHeaders.java | 5 +- .../ParseContainerPropertiesFromHeaders.java | 26 +- .../ReturnFalseIfContainerAlreadyExists.java | 2 +- .../filters/SharedKeyLiteAuthentication.java | 56 +- .../ParseAzureStorageErrorFromXmlContent.java | 12 +- .../queue/binders/BindToXmlStringPayload.java | 7 +- .../azure/storage/util/AzureStorageUtils.java | 2 +- .../storage/ProvidersInPropertiesTest.java | 4 +- .../blob/AzureBlobAsyncClientTest.java | 3 +- .../storage/blob/AzureBlobClientLiveTest.java | 6 +- .../BindAzureBlobMetadataToRequestTest.java | 154 +++++ .../binders/BindAzureBlobToPayloadTest.java | 200 ------- .../blobstore/AzureBlobRequestSignerTest.java | 8 +- .../config/AzureBlobStoreModuleTest.java | 2 +- ...AzureBlobContainerIntegrationLiveTest.java | 2 +- .../AzureBlobContainerLiveTest.java | 2 +- ...BlobInputStreamMapIntegrationLiveTest.java | 2 +- .../AzureBlobIntegrationLiveTest.java | 2 +- .../integration/AzureBlobLiveTest.java | 2 +- .../AzureBlobMapIntegrationLiveTest.java | 2 +- .../AzureBlobServiceIntegrationLiveTest.java | 2 +- .../integration/AzureBlobSignerLiveTest.java | 2 +- .../options/CreateContainerOptionsTest.java | 2 +- .../blob/options/ListBlobsOptionsTest.java | 2 +- ...ountNameEnumerationResultsHandlerTest.java | 5 +- ...inerNameEnumerationResultsHandlerTest.java | 51 +- .../AzureStorageRestClientModuleTest.java | 3 +- .../SharedKeyLiteAuthenticationTest.java | 40 +- .../ParseAzureErrorFromXmlContentTest.java | 6 +- .../storage/options/CreateOptionsTest.java | 2 +- .../storage/options/ListOptionsTest.java | 2 +- .../queue/AzureQueueAsyncClientTest.java | 3 +- .../queue/AzureQueueClientLiveTest.java | 2 +- .../storage/queue/options/GetOptionsTest.java | 2 +- ...ountNameEnumerationResultsHandlerTest.java | 5 +- .../xml/QueueMessagesListHandlerTest.java | 3 +- .../azure/storage/xml/ErrorHandlerTest.java | 3 +- .../blobstore/BlobStoreContextFactory.java | 2 +- .../blobstore/TransientAsyncBlobStore.java | 102 ++-- .../blobstore/TransientBlobRequestSigner.java | 19 +- .../binders/BindBlobToMultipartForm.java | 13 +- .../binders/BindMapToHeadersWithPrefix.java | 48 +- .../BindUserMetadataToHeadersWithPrefix.java | 23 +- .../domain/internal/StorageMetadataImpl.java | 2 - .../jclouds/blobstore/functions/BlobName.java | 10 +- .../functions/BlobToHttpGetOptions.java | 51 +- .../functions/ClearAndDeleteIfNotEmpty.java | 78 --- .../HttpGetOptionsListToGetOptions.java | 39 +- .../blobstore/functions/ObjectMD5.java | 33 +- .../ParseBlobFromHeadersAndHttpContent.java | 19 +- ...ParseSystemAndUserMetadataFromHeaders.java | 37 +- .../functions/PrefixToResourceMetadata.java | 3 + ...etadataToRelativePathResourceMetadata.java | 10 +- .../ReturnFalseOnContainerNotFound.java | 5 +- .../functions/ReturnFalseOnKeyNotFound.java | 2 +- .../ReturnNullOnContainerNotFound.java | 2 +- .../functions/ReturnNullOnKeyNotFound.java | 2 +- .../ThrowContainerNotFoundOn404.java | 2 +- .../functions/ThrowKeyNotFoundOn404.java | 2 +- .../internal/BaseAsyncBlobStore.java | 4 +- .../blobstore/internal/BaseBlobStore.java | 4 +- .../internal/BlobStoreContextImpl.java | 2 +- .../jclouds/blobstore/options/GetOptions.java | 80 ++- .../MarkersIfDirectoryReturnNameStrategy.java | 32 +- .../blobstore/util/BlobStoreUtils.java | 67 ++- .../clojure/org/jclouds/blobstore_test.clj | 4 +- .../TransientBlobRequestSignerTest.java | 8 +- .../binders/BindBlobToMultipartFormTest.java | 23 +- .../BindMapToHeadersWithPrefixTest.java | 68 +++ ...ndUserMetadataToHeadersWithPrefixTest.java | 76 +++ .../blobstore/functions/BlobNameTest.java | 59 ++ .../functions/BlobToHttpGetOptionsTest.java | 112 ++++ .../blobstore/functions/ObjectMD5Test.java | 75 +++ ...arseBlobFromHeadersAndHttpContentTest.java | 21 +- ...eSystemAndUserMetadataFromHeadersTest.java | 44 +- .../PrefixToResourceMetadataTest.java | 49 ++ ...taToRelativePathResourceMetadataTest.java} | 7 +- .../ReturnFalseOnContainerNotFoundTest.java | 49 ++ .../ReturnFalseOnKeyNotFoundTest.java | 49 ++ .../ReturnNullOnContainerNotFoundTest.java | 49 ++ .../ReturnNullOnKeyNotFoundTest.java | 49 ++ .../ThrowContainerNotFoundOn404Test.java | 58 ++ .../functions/ThrowKeyNotFoundOn404Test.java | 58 ++ .../TransientBlobIntegrationTest.java | 2 +- .../TransientBlobMapIntegrationTest.java | 2 +- .../TransientContainerIntegrationTest.java | 2 +- ...ransientInputStreamMapIntegrationTest.java | 2 +- .../TransientServiceIntegrationTest.java | 2 +- .../internal/BaseBlobIntegrationTest.java | 4 +- .../internal/BaseBlobLiveTest.java | 2 +- .../internal/BaseBlobMapIntegrationTest.java | 6 +- .../internal/BaseBlobSignerLiveTest.java | 8 +- .../BaseInputStreamMapIntegrationTest.java | 18 +- .../internal/BaseMapIntegrationTest.java | 4 +- .../blobstore/internal/BaseBlobMapTest.java | 10 +- .../blobstore/options/GetOptionsTest.java | 2 +- .../internal/BiggerThanPageSizeTest.java | 75 +++ .../blobstore/util/BlobStoreUtilsTest.java | 33 +- ...indCloneDriveOptionsToPlainTextString.java | 6 +- .../BindDriveDataToPlainTextString.java | 5 +- .../binders/BindDriveToPlainTextString.java | 5 +- .../binders/BindServerToPlainTextString.java | 5 +- ...CloudSigmaComputeServiceContextModule.java | 2 +- .../cloudsigma/functions/DriveDataToMap.java | 2 +- .../handlers/CloudSigmaErrorHandler.java | 10 +- .../cloudsigma/CloudSigmaAsyncClientTest.java | 56 +- .../cloudsigma/CloudSigmaClientLiveTest.java | 2 +- .../cloudsigma/ProvidersInPropertiesTest.java | 4 +- ...loneDriveOptionsToPlainTextStringTest.java | 10 +- .../BindDriveDataToPlainTextStringTest.java | 4 +- .../BindDriveToPlainTextStringTest.java | 4 +- .../BindServerToPlainTextStringTest.java | 4 +- .../functions/MapToDriveInfoTest.java | 4 +- .../functions/MapToServerInfoTest.java | 6 +- ...OsFamilyVersion64BitFromImageNameTest.java | 4 +- .../handlers/CloudSigmaErrorHandlerTest.java | 6 +- .../compute/ComputeServiceContextFactory.java | 2 +- ...iveComputeServiceAdapterContextModule.java | 16 +- .../domain/internal/TemplateBuilderImpl.java | 4 +- .../compute/internal/BaseComputeService.java | 4 +- .../internal/BaseLoadBalancerService.java | 3 - .../internal/ComputeServiceContextImpl.java | 3 +- .../compute/options/TemplateOptions.java | 8 +- .../compute/predicates/NodePredicates.java | 6 +- .../compute/util/ComputeServiceUtils.java | 4 +- .../compute/BaseComputeServiceLiveTest.java | 2 +- .../BaseLoadBalancerServiceLiveTest.java | 2 +- .../compute/BaseTemplateBuilderLiveTest.java | 2 +- .../org/jclouds/compute/ComputeTestUtils.java | 4 +- .../StubComputeServiceIntegrationTest.java | 12 +- .../StubTemplateBuilderIntegrationTest.java | 2 +- .../RetryOnTimeOutExceptionSupplier.java | 5 +- .../concurrent/internal/SyncProxy.java | 8 +- .../java/org/jclouds/domain/Credentials.java | 10 +- .../ExceptionToValueOrPropagate.java | 9 +- .../jclouds/functions/IdentityFunction.java | 27 +- .../java/org/jclouds/http/HttpCommand.java | 7 +- .../jclouds/http/HttpCommandRendezvous.java | 12 +- .../org/jclouds/http/HttpErrorHandler.java | 5 +- .../java/org/jclouds/http/HttpMessage.java | 55 +- .../java/org/jclouds/http/HttpRequest.java | 120 +++- .../org/jclouds/http/HttpRequestFilter.java | 18 +- .../java/org/jclouds/http/HttpResponse.java | 48 +- .../jclouds/http/HttpResponseException.java | 22 +- .../org/jclouds/http/HttpRetryHandler.java | 10 + .../main/java/org/jclouds/http/HttpUtils.java | 347 +++-------- .../jclouds/http/IOExceptionRetryHandler.java | 10 + ...ransformingHttpCommandExecutorService.java | 3 +- ...formingHttpCommandExecutorServiceImpl.java | 5 +- .../http/TransformingHttpCommandImpl.java | 72 ++- .../http/filters/BasicAuthentication.java | 15 +- .../functions/ParseContentMD5FromHeaders.java | 3 +- .../org/jclouds/http/functions/ParseJson.java | 4 +- .../org/jclouds/http/functions/ParseSax.java | 9 +- ...ParseURIFromListOrLocationHeaderIf20x.java | 9 +- .../http/functions/ReturnFalseOn404.java | 3 +- .../http/functions/ReturnStringIf2xx.java | 4 +- .../http/functions/ReturnTrueOn404.java | 3 +- .../handlers/BackoffLimitedRetryHandler.java | 2 +- ...oseContentAndSetExceptionErrorHandler.java | 5 +- .../handlers/RedirectionRetryHandler.java | 27 +- .../BaseHttpCommandExecutorService.java | 24 +- .../JavaUrlHttpCommandExecutorService.java | 24 +- .../http/options/BaseHttpRequestOptions.java | 8 +- .../org/jclouds/http/options/GetOptions.java | 72 ++- .../org/jclouds/http/utils/ModifyRequest.java | 194 ++++++ .../java/org/jclouds/io/ContentMetadata.java | 9 + .../jclouds/io/MutableContentMetadata.java | 8 + .../payloads/BaseMutableContentMetadata.java | 39 +- .../io/payloads/UrlEncodedFormPayload.java | 9 +- .../main/java/org/jclouds/rest/Binder.java | 2 +- .../org/jclouds/rest/HttpAsyncClient.java | 29 +- .../java/org/jclouds/rest/HttpClient.java | 22 +- .../org/jclouds/rest/InputParamValidator.java | 2 +- .../org/jclouds/rest/InvocationContext.java | 4 +- .../main/java/org/jclouds/rest/MapBinder.java | 3 +- .../main/java/org/jclouds/rest/Providers.java | 152 +++++ .../org/jclouds/rest/RestContextBuilder.java | 7 +- .../org/jclouds/rest/RestContextFactory.java | 21 +- .../org/jclouds/rest/RestContextSpec.java | 2 +- .../rest/binders/BindAsHostPrefix.java | 12 +- .../rest/binders/BindMapToMatrixParams.java | 9 +- .../rest/binders/BindToJsonPayload.java | 11 +- .../rest/binders/BindToStringPayload.java | 4 +- .../rest/config/CredentialStoreModule.java | 7 +- .../jclouds/rest/config/RestClientModule.java | 2 +- .../org/jclouds/rest/config/RestModule.java | 14 +- .../MapHttp4xxCodesToExceptions.java | 2 +- .../ReturnEmptyListOnNotFoundOr404.java | 2 +- .../ReturnEmptyMapOnNotFoundOr404.java | 2 +- .../ReturnEmptyMultimapOnNotFoundOr404.java | 2 +- .../ReturnEmptySetOnNotFoundOr404.java | 2 +- .../functions/ReturnNullOnNotFoundOr404.java | 2 +- .../functions/ReturnVoidOnNotFoundOr404.java | 2 +- .../rest/internal/AsyncRestClientProxy.java | 63 +- .../rest/internal/GeneratedHttpRequest.java | 119 +++- .../internal/RestAnnotationProcessor.java | 269 +++++---- .../rest/internal/RestContextImpl.java | 3 +- .../java/org/jclouds/util/Assertions.java | 45 ++ .../org/jclouds/util/CredentialUtils.java | 58 ++ .../org/jclouds/util/InputStreamChain.java | 2 +- .../main/java/org/jclouds/util/Lists2.java | 56 ++ .../src/main/java/org/jclouds/util/Maps2.java | 115 ++++ .../main/java/org/jclouds/util/Modules2.java | 75 +++ .../org/jclouds/util/NullSafeCollections.java | 39 ++ .../java/org/jclouds/util/Preconditions2.java | 55 ++ .../main/java/org/jclouds/util/SaxUtils.java | 46 ++ .../main/java/org/jclouds/util/Strings2.java | 203 +++++++ .../java/org/jclouds/util/Suppliers2.java | 49 ++ .../java/org/jclouds/util/Throwables2.java | 107 ++++ .../src/main/java/org/jclouds/util/Utils.java | 559 ------------------ .../java/org/jclouds/PerformanceTest.java | 6 +- .../concurrent/FutureExceptionParserTest.java | 6 +- .../concurrent/FutureIterablesTest.java | 2 +- .../FuturesComposePerformanceTest.java | 2 +- .../RetryOnTimeOutExceptionSupplierTest.java | 2 +- .../concurrent/internal/SyncProxyTest.java | 2 +- .../org/jclouds/crypto/CryptoStreamsTest.java | 2 +- .../java/org/jclouds/crypto/PemsTest.java | 2 +- .../org/jclouds/date/DateServiceTest.java | 38 +- .../org/jclouds/domain/CredentialsTest.java | 2 +- .../java/org/jclouds/domain/JsonBallTest.java | 2 +- .../org/jclouds/domain/JsonObjectTest.java | 2 +- ...CommandExecutorServiceIntegrationTest.java | 43 +- .../http/BaseHttpErrorHandlerTest.java | 2 +- .../java/org/jclouds/http/BaseJettyTest.java | 11 +- .../http/HttpPropertiesBuilderTest.java | 2 +- .../http/IntegrationTestAsyncClient.java | 23 +- .../jclouds/http/IntegrationTestClient.java | 32 +- .../http/filters/BasicAuthenticationTest.java | 4 +- .../http/functions/BaseHandlerTest.java | 6 + .../jclouds/http/functions/ParseSaxTest.java | 7 + ...eURIFromListOrLocationHeaderIf20xTest.java | 4 +- .../http/functions/ReturnStringIf200Test.java | 4 +- .../BackoffLimitedRetryHandlerTest.java | 2 +- .../handlers/DelegatingErrorHandlerTest.java | 2 +- .../handlers/RedirectionRetryHandlerTest.java | 7 +- .../jclouds/http/internal/WireLiveTest.java | 43 +- .../org/jclouds/http/internal/WireTest.java | 10 +- .../jclouds/http/options/GetOptionsTest.java | 2 +- .../jclouds/http/utils/ModifyRequestTest.java | 134 +++++ .../test/java/org/jclouds/io/CryptoTest.java | 3 +- .../io/payloads/MultipartFormTest.java | 8 +- .../predicates/RetryablePredicateTest.java | 2 +- .../org/jclouds/rest/BaseRestClientTest.java | 31 +- .../rest/CredentialStoreModuleTest.java | 6 +- .../jclouds/rest/InputParamValidatorTest.java | 9 +- .../java/org/jclouds/rest/RestClientTest.java | 10 +- .../jclouds/rest/RestContextBuilderTest.java | 2 +- .../jclouds/rest/RestContextFactoryTest.java | 7 +- .../binders/BindMapToMatrixParamsTest.java | 23 +- .../internal/RestAnnotationProcessorTest.java | 140 ++--- .../org/jclouds/util/CredentialUtilsTest.java | 61 ++ .../java/org/jclouds/util/HttpUtilsTest.java | 72 +-- .../java/org/jclouds/util/Lists2Test.java | 45 ++ .../test/java/org/jclouds/util/Maps2Test.java | 58 ++ .../java/org/jclouds/util/PatternsTest.java | 2 +- .../java/org/jclouds/util/ProvidersTest.java | 42 ++ .../java/org/jclouds/util/Strings2Test.java | 51 ++ .../{UtilsTest.java => Throwables2Test.java} | 247 +++----- .../functions/KeyToStoredTweetStatus.java | 2 +- .../controller/AddTweetsControllerTest.java | 2 +- .../controller/StoreTweetsControllerTest.java | 4 +- .../functions/KeyToStoredTweetStatusTest.java | 2 +- .../ServiceToStoredTweetStatusesTest.java | 2 +- .../integration/TweetStoreLiveTest.java | 12 +- .../functions/KeyToStoredTweetStatus.java | 2 +- .../controller/AddTweetsControllerTest.java | 2 +- .../controller/StoreTweetsControllerTest.java | 4 +- .../functions/KeyToStoredTweetStatusTest.java | 2 +- .../ServiceToStoredTweetStatusesTest.java | 2 +- .../integration/TweetStoreLiveTest.java | 12 +- .../BindDriveDataToPlainTextString.java | 5 +- .../binders/BindDriveToPlainTextString.java | 5 +- .../binders/BindServerToPlainTextString.java | 5 +- ...asticStackComputeServiceContextModule.java | 6 +- .../handlers/ElasticStackErrorHandler.java | 10 +- .../ElasticStackAsyncClientTest.java | 58 +- .../ElasticStackClientLiveTest.java | 8 +- .../ProvidersInPropertiesTest.java | 4 +- .../BindDriveDataToPlainTextStringTest.java | 4 +- .../BindDriveToPlainTextStringTest.java | 4 +- .../BindServerToPlainTextStringTest.java | 4 +- .../functions/MapToDriveInfoTest.java | 4 +- .../functions/MapToServerInfoTest.java | 6 +- .../ElasticStackErrorHandlerTest.java | 6 +- .../ApacheHCHttpCommandExecutorService.java | 17 +- .../jclouds/http/apachehc/ApacheHCUtils.java | 2 +- .../bouncycastle/BouncyCastleCryptoTest.java | 3 +- .../AsyncGaeHttpCommandExecutorService.java | 23 +- .../org/jclouds/gae/ConvertToGaeRequest.java | 7 +- .../jclouds/gae/ConvertToJcloudsResponse.java | 21 +- ...CommandExecutorServiceIntegrationTest.java | 46 +- .../jclouds/gae/ConvertToGaeRequestTest.java | 11 +- .../gae/ConvertToJcloudsResponseTest.java | 7 +- .../date/joda/JodaDateServiceTest.java | 3 +- .../org/jclouds/ssh/jsch/JschSshClient.java | 4 +- .../ssh/jsch/config/JschSshClientModule.java | 5 +- .../ssh/jsch/JschSshClientLiveTest.java | 10 +- .../filesystem/FilesystemAsyncBlobStore.java | 14 +- .../gogrid/binders/BindIdsToQueryParams.java | 10 +- .../binders/BindNamesToQueryParams.java | 6 +- ...ObjectNameToGetJobsRequestQueryParams.java | 8 +- .../BindRealIpPortPairsToQueryParams.java | 9 +- .../BindVirtualIpPortPairToQueryParams.java | 8 +- .../filters/SharedKeyLiteAuthentication.java | 14 +- .../jclouds/gogrid/mock/HttpCommandMock.java | 7 +- .../jclouds/gogrid/GoGridAsyncClientTest.java | 5 +- .../gogrid/GoGridLiveTestDisabled.java | 2 +- .../gogrid/ProvidersInPropertiesTest.java | 4 +- .../binders/BindIdsToQueryParamsTest.java | 4 +- .../binders/BindNamesToQueryParamsTest.java | 2 +- .../compute/GoGridComputeServiceLiveTest.java | 2 +- .../GoGridTemplateBuilderLiveTest.java | 2 +- ...GoGridComputeServiceContextModuleTest.java | 2 +- .../functions/ServerToNodeMetadataTest.java | 2 +- .../ParseCredentialsFromJsonResponseTest.java | 2 +- .../ParseJobsFromJsonResponseTest.java | 2 +- ...arseLoadBalancersFromJsonResponseTest.java | 2 +- ...eToCredentialsMapFromJsonResponseTest.java | 2 +- .../ParseServersFromJsonResponseTest.java | 4 +- .../services/BaseGoGridAsyncClientTest.java | 2 + .../services/GridImageAsyncClientTest.java | 28 +- .../services/GridIpAsyncClientTest.java | 14 +- .../services/GridJobAsyncClientTest.java | 20 +- .../GridLoadBalancerAsyncClientTest.java | 30 +- .../services/GridServerAsyncClientTest.java | 46 +- .../rackspace/RackspaceAuthAsyncClient.java | 1 - .../cloudfiles/CloudFilesAsyncClient.java | 4 +- ...ava => BindCFObjectMetadataToRequest.java} | 23 +- .../ParseContainerCDNMetadataFromHeaders.java | 2 +- .../ParseObjectFromHeadersAndHttpContent.java | 2 +- .../functions/ParseObjectInfoFromHeaders.java | 2 +- .../ParseObjectInfoListFromJsonResponse.java | 8 +- .../functions/ReturnTrueOn404FalseOn409.java | 3 +- .../ParseCloudFilesErrorFromHttpResponse.java | 8 +- .../binders/BindAdminPassToJsonPayload.java | 8 +- .../BindBackupScheduleToJsonPayload.java | 6 +- .../BindConfirmResizeToJsonPayload.java | 5 +- .../binders/BindCreateImageToJsonPayload.java | 6 +- .../binders/BindRebootTypeToJsonPayload.java | 6 +- .../BindResizeFlavorToJsonPayload.java | 6 +- .../BindRevertResizeToJsonPayload.java | 5 +- .../binders/BindServerNameToJsonPayload.java | 6 +- .../BindSharedIpGroupToJsonPayload.java | 6 +- ...arseCloudServersErrorFromHttpResponse.java | 8 +- .../options/CreateServerOptions.java | 4 +- .../options/CreateSharedIpGroupOptions.java | 6 +- .../options/RebuildServerOptions.java | 6 +- .../rackspace/filters/AddTimestampQuery.java | 8 +- .../filters/AuthenticateRequest.java | 9 +- ...arseAuthenticationResponseFromHeaders.java | 4 +- .../rackspace/ProvidersInPropertiesTest.java | 4 +- .../RackspaceAuthAsyncClientTest.java | 5 +- .../cloudfiles/CloudFilesClientLiveTest.java | 8 +- .../BindCFObjectMetadataToRequestTest.java | 155 +++++ .../binders/BindCFObjectToPayloadTest.java | 186 ------ .../CloudFilesBlobRequestSignerTest.java | 8 +- .../CloudFilesBlobIntegrationLiveTest.java | 2 +- .../integration/CloudFilesBlobLiveTest.java | 2 +- .../CloudFilesBlobMapIntegrationLiveTest.java | 2 +- .../CloudFilesBlobSignerLiveTest.java | 2 +- ...loudFilesContainerIntegrationLiveTest.java | 2 +- .../CloudFilesContainerLiveTest.java | 2 +- ...ilesInputStreamMapIntegrationLiveTest.java | 2 +- .../CloudFilesServiceIntegrationLiveTest.java | 2 +- ...rseObjectInfoListFromJsonResponseTest.java | 9 +- ...AuthenticationResponseFromHeadersTest.java | 9 +- ...erCDNMetadataListFromJsonResponseTest.java | 2 +- ...arseContainerListFromJsonResponseTest.java | 6 +- .../ParseObjectInfoFromHeadersTest.java | 15 +- ...seCloudFilesErrorFromHttpResponseTest.java | 6 +- .../CloudServersAsyncClientTest.java | 5 +- .../CloudServersClientLiveTest.java | 6 +- .../BindAdminPassToJsonPayloadTest.java | 2 +- .../BindCreateImageToJsonPayloadTest.java | 2 +- .../BindRebootTypeToJsonPayloadTest.java | 2 +- .../BindServerNameToJsonPayloadTest.java | 2 +- .../CloudServersComputeServiceLiveTest.java | 2 +- .../CloudServersTemplateBuilderLiveTest.java | 2 +- ...erversComputeServiceContextModuleTest.java | 2 +- .../CloudServersImageToImageTest.java | 2 +- .../functions/FlavorToHardwareTest.java | 2 +- .../functions/ServerToNodeMetadataTest.java | 2 +- .../cloudservers/domain/ServerTest.java | 2 +- .../ParseAddressesFromJsonResponseTest.java | 2 +- ...rseBackupScheduleFromJsonResponseTest.java | 2 +- .../ParseFlavorFromJsonResponseTest.java | 2 +- .../ParseFlavorListFromJsonResponseTest.java | 4 +- .../ParseImageFromJsonResponseTest.java | 2 +- .../ParseImageListFromJsonResponseTest.java | 4 +- ...seInetAddressListFromJsonResponseTest.java | 2 +- .../ParseServerFromJsonResponseTest.java | 4 +- .../ParseServerListFromJsonResponseTest.java | 4 +- ...arseSharedIpGroupFromJsonResponseTest.java | 2 +- ...SharedIpGroupListFromJsonResponseTest.java | 4 +- .../options/CreateServerOptionsTest.java | 2 +- .../CreateSharedIpGroupOptionsTest.java | 2 +- .../cloudservers/options/ListOptionsTest.java | 2 +- .../options/RebuildServerOptionsTest.java | 2 +- .../filters/AddTimestampQueryTest.java | 7 +- .../options/BaseListOptionsTest.java | 2 +- .../miro/binder/CreateServerOptions.java | 22 +- .../miro/binder/RimuHostingJsonBinder.java | 10 +- .../binder/RimuHostingRebootJsonBinder.java | 18 +- .../filters/RimuHostingAuthentication.java | 13 +- .../functions/ParseRimuHostingException.java | 2 +- .../miro/ProvidersInPropertiesTest.java | 4 +- .../miro/RimuHostingAsyncClientTest.java | 5 +- .../miro/RimuHostingClientLiveTest.java | 2 +- .../RimuHostingComputeServiceLiveTest.java | 2 +- .../RimuHostingTemplateBuilderLiveTest.java | 2 +- ...ostingComputeServiceContextModuleTest.java | 2 +- .../handlers/BoxDotNetErrorHandler.java | 28 +- .../boxdotnet/BoxDotNetAsyncClientTest.java | 11 +- .../boxdotnet/BoxDotNetClientLiveTest.java | 2 +- .../IBMDeveloperCloudTemplateOptions.java | 4 +- .../config/IBMDeveloperCloudParserModule.java | 3 - .../IBMDeveloperCloudErrorHandler.java | 8 +- .../IBMDeveloperCloudAsyncClientTest.java | 71 ++- .../ibmdev/ProvidersInPropertiesTest.java | 4 +- ...DeveloperCloudTemplateBuilderLiveTest.java | 2 +- .../LibvirtComputeServiceLiveTest.java | 2 +- .../compute/LibvirtExperimentLiveTest.java | 2 +- .../jclouds/mezeo/pcs2/PCSAsyncClient.java | 20 +- .../BindContainerNameToXmlPayload.java | 7 +- .../binders/BindFileInfoToXmlPayload.java | 22 +- .../binders/BindPCSFileToMultipartForm.java | 13 +- .../blobstore/functions/BlobToFileInfo.java | 7 +- .../functions/FileInfoToBlobMetadata.java | 9 +- .../jclouds/mezeo/pcs2/domain/PCSFile.java | 3 +- .../functions/AddMetadataItemIntoMap.java | 9 +- .../ReturnFalseIfContainerNotFound.java | 3 +- .../ReturnTrueIfContainerAlreadyExists.java | 4 +- .../mezeo/pcs2/xml/ContainerHandler.java | 4 +- .../jclouds/mezeo/pcs2/xml/FileHandler.java | 6 +- .../mezeo/pcs2/PCSAsyncClientTest.java | 4 +- .../jclouds/mezeo/pcs2/PCSClientLiveTest.java | 10 +- .../org/jclouds/mezeo/pcs2/PCSCloudTest.java | 4 +- .../mezeo/pcs2/ProvidersInPropertiesTest.java | 4 +- .../BindContainerNameToXmlPayloadTest.java | 4 +- .../binders/BindFileInfoToXmlPayloadTest.java | 37 +- .../ning/NingHttpCommandExecutorService.java | 100 ++-- .../NingHttpCommandExecutorServiceTest.java | 7 - .../binders/BindMetadataToQueryParams.java | 9 +- .../sdn/filters/AddSessionTokenToRequest.java | 11 +- .../filters/InsertUserContextIntoPath.java | 12 +- .../sdn/ProvidersInPropertiesTest.java | 4 +- .../nirvanix/sdn/SDNAsyncClientTest.java | 4 +- .../nirvanix/sdn/SDNAuthAsyncClientTest.java | 4 +- .../sdn/SDNAuthenticationLiveTest.java | 4 +- .../nirvanix/sdn/SDNClientLiveTest.java | 2 +- .../BindMetadataToQueryParamsTest.java | 8 +- .../filters/AddSessionTokenToRequestTest.java | 52 +- .../InsertUserContextIntoPathTest.java | 52 +- .../handlers/SymphonyVPDCErrorHandler.java | 8 +- .../savvis/SymphonyVPDCAsyncClientTest.java | 12 +- .../SymphonyVPDCErrorHandlerTest.java | 6 +- .../twitter/TwitterAsyncClientTest.java | 7 +- .../vi/compute/ViComputeServiceLiveTest.java | 2 +- .../scriptbuilder/domain/AppendFileTest.java | 2 +- .../domain/AuthorizeRSAPublicKeyTest.java | 2 +- .../scriptbuilder/domain/CallTest.java | 2 +- .../domain/CreateRunScriptTest.java | 2 +- .../domain/InstallRSAPrivateKeyTest.java | 2 +- .../domain/PipeHttpResponseToTest.java | 2 +- .../scriptbuilder/domain/ShellTokenTest.java | 2 +- .../domain/StatementListTest.java | 2 +- .../scriptbuilder/domain/SwitchArgTest.java | 2 +- .../UnzipHttpResponseIntoDirectoryToTest.java | 2 +- .../jclouds/scriptbuilder/util/UtilsTest.java | 2 +- .../ServerManagerComputeServiceLiveTest.java | 2 +- .../ServerManagerExperimentLiveTest.java | 2 +- .../binders/BindCreateBackupToXmlPayload.java | 8 +- .../binders/BindCreateSliceToXmlPayload.java | 9 +- .../slicehost/filters/SlicehostBasic.java | 10 +- .../ParseSlicehostErrorFromHttpResponse.java | 4 +- .../slicehost/ProvidersInPropertiesTest.java | 4 +- .../slicehost/SlicehostAsyncClientTest.java | 5 +- .../slicehost/SlicehostClientLiveTest.java | 2 +- .../SlicehostComputeServiceLiveTest.java | 2 +- .../SlicehostTemplateBuilderLiveTest.java | 2 +- ...cehostComputeServiceContextModuleTest.java | 2 +- .../functions/FlavorToHardwareTest.java | 2 +- .../functions/SliceToNodeMetadataTest.java | 2 +- .../functions/SlicehostImageToImageTest.java | 2 +- .../slicehost/xml/FlavorHandlerTest.java | 2 +- .../slicehost/xml/FlavorsHandlerTest.java | 3 +- .../slicehost/xml/ImageHandlerTest.java | 2 +- .../slicehost/xml/ImagesHandlerTest.java | 3 +- .../slicehost/xml/SliceHandlerTest.java | 3 +- .../slicehost/xml/SlicesHandlerTest.java | 3 +- .../ant/taskdefs/compute/ComputeTask.java | 4 +- .../ant/taskdefs/sshjava/SSHJavaTest.java | 2 +- .../jclouds/blobstore/GetPathLiveTest.java | 6 +- .../BlueLockVCloudDirectorClientLiveTest.java | 2 +- ...oudDirectorGuestCustomizationLiveTest.java | 2 +- .../bluelock/ProvidersInPropertiesTest.java | 4 +- .../VCloudSessionRefreshLiveTest.java | 2 +- ...kVCloudDirectorComputeServiceLiveTest.java | 2 +- .../domain/VCloudExpressLoginAsyncClient.java | 2 - .../java/domain/VCloudLoginAsyncClient.java | 2 - .../vcloud/CommonVCloudAsyncClient.java | 13 - .../org/jclouds/vcloud/VCloudAsyncClient.java | 7 - .../vcloud/VCloudExpressAsyncClient.java | 7 - .../vcloud/VCloudResponseException.java | 4 +- .../BindCaptureVAppParamsToXmlPayload.java | 21 +- .../BindCloneVAppParamsToXmlPayload.java | 29 +- ...GuestCustomizationSectionToXmlPayload.java | 8 +- ...antiateVAppTemplateParamsToXmlPayload.java | 12 +- ...ExpressVAppTemplateParamsToXmlPayload.java | 12 +- .../binders/BindParamsToXmlPayload.java | 8 +- .../options/VCloudTemplateOptions.java | 4 +- .../vcloud/filters/SetVCloudTokenCookie.java | 10 +- .../VAppTemplatesForCatalogItems.java | 2 +- .../ParseVCloudErrorFromHttpResponse.java | 10 +- .../jclouds/vcloud/CaptureVAppLiveTest.java | 2 +- .../vcloud/CommonVCloudClientLiveTest.java | 2 +- .../vcloud/ProvidersInPropertiesTest.java | 4 +- .../jclouds/vcloud/VCloudAsyncClientTest.java | 17 +- .../jclouds/vcloud/VCloudClientLiveTest.java | 2 +- .../vcloud/VCloudExpressAsyncClientTest.java | 13 +- .../vcloud/VCloudExpressClientLiveTest.java | 2 +- .../VCloudGuestCustomizationLiveTest.java | 4 +- .../vcloud/VCloudLoginAsyncClientTest.java | 5 +- .../vcloud/VCloudVersionsAsyncClientTest.java | 5 +- .../BindCloneVAppParamsToXmlPayloadTest.java | 13 +- .../BindDeployVAppParamsToXmlPayloadTest.java | 2 +- ...ateVAppTemplateParamsToXmlPayloadTest.java | 25 +- ...essVAppTemplateParamsToXmlPayloadTest.java | 17 +- ...indUndeployVAppParamsToXmlPayloadTest.java | 2 +- ...ssBindCloneVAppParamsToXmlPayloadTest.java | 13 +- .../compute/VCloudComputeServiceLiveTest.java | 2 +- ...VCloudComputeServiceContextModuleTest.java | 2 +- ...xpressComputeServiceContextModuleTest.java | 2 +- .../VCloudExpressOrgNetworkAdapterTest.java | 2 +- .../filters/SetVCloudTokenCookieTest.java | 2 +- .../ParseLoginResponseFromHeadersTest.java | 12 +- .../InstantiateVAppTemplateOptionsTest.java | 2 +- .../vcloud/xml/CatalogHandlerTest.java | 2 +- .../vcloud/xml/CatalogItemHandlerTest.java | 2 +- .../GuestCustomizationSectionHandlerTest.java | 3 +- .../xml/NetworkConnectionHandlerTest.java | 5 +- .../NetworkConnectionSectionHandlerTest.java | 2 +- .../jclouds/vcloud/xml/OrgHandlerTest.java | 2 +- .../vcloud/xml/OrgListHandlerTest.java | 3 +- .../vcloud/xml/OrgNetworkHandlerTest.java | 2 +- .../xml/SupportedVersionsHandlerTest.java | 2 +- .../jclouds/vcloud/xml/TaskHandlerTest.java | 3 +- .../vcloud/xml/TasksListHandlerTest.java | 3 +- .../jclouds/vcloud/xml/VAppHandlerTest.java | 2 +- .../vcloud/xml/VAppTemplateHandlerTest.java | 2 +- .../xml/VCloudExpressNetworkHandlerTest.java | 2 +- .../VCloudExpressVAppTemplateHandlerTest.java | 2 +- .../jclouds/vcloud/xml/VDCHandlerTest.java | 2 +- .../org/jclouds/vcloud/xml/VmHandlerTest.java | 2 +- .../xml/ovf/OvfEnvelopeHandlerTest.java | 2 +- .../ovf/ResourceAllocationHandlerTest.java | 3 +- .../vcloud/xml/ovf/SystemHandlerTest.java | 3 +- .../xml/ovf/VCloudExpressVAppHandlerTest.java | 3 +- ...loudOperatingSystemSectionHandlerTest.java | 5 +- ...loudVirtualHardwareSectionHandlerTest.java | 5 +- .../xml/ovf/VirtualSystemHandlerTest.java | 2 +- .../terremark/TerremarkECloudAsyncClient.java | 13 - .../terremark/TerremarkVCloudAsyncClient.java | 18 - .../TerremarkVCloudExpressAsyncClient.java | 8 - .../BindAddInternetServiceToXmlPayload.java | 21 +- .../BindAddNodeServiceToXmlPayload.java | 24 +- .../binders/BindCreateKeyToXmlPayload.java | 22 +- .../BindNodeConfigurationToXmlPayload.java | 7 +- .../BindVAppConfigurationToXmlPayload.java | 12 +- .../functions/CreateUniqueKeyPair.java | 4 +- .../TerremarkVCloudTemplateOptions.java | 4 +- .../config/TerremarkRestClientModule.java | 8 +- .../terremark/domain/VAppConfiguration.java | 5 +- .../ReturnVoidOnDeleteDefaultIp.java | 2 +- ...eTerremarkVCloudErrorFromHttpResponse.java | 6 +- .../options/AddInternetServiceOptions.java | 6 +- .../terremark/options/AddNodeOptions.java | 6 +- .../terremark/xml/KeyPairByNameHandler.java | 4 +- .../terremark/InternetServiceLiveTest.java | 2 +- .../terremark/ProvidersInPropertiesTest.java | 4 +- .../TerremarkECloudAsyncClientTest.java | 17 +- ...TerremarkECloudClientLiveTestDisabled.java | 5 +- ...TerremarkVCloudExpressAsyncClientTest.java | 21 +- .../TerremarkVCloudExpressClientLiveTest.java | 5 +- ...indAddInternetServiceToXmlPayloadTest.java | 8 +- .../BindAddNodeServiceToXmlPayloadTest.java | 8 +- ...BindNodeConfigurationToXmlPayloadTest.java | 2 +- ...BindVAppConfigurationToXmlPayloadTest.java | 89 +-- ...ateVAppTemplateParamsToXmlPayloadTest.java | 21 +- ...TerremarkECloudComputeServiceLiveTest.java | 2 +- ...erremarkECloudTemplateBuilderLiveTest.java | 2 +- .../TerremarkVCloudComputeClientTest.java | 2 +- ...rkVCloudExpressComputeServiceLiveTest.java | 2 +- ...kVCloudExpressTemplateBuilderLiveTest.java | 2 +- .../strategy/CleanupOrphanKeysTest.java | 3 +- ...yPairUnlessUserSpecifiedOtherwiseTest.java | 2 +- .../compute/strategy/DeleteKeyPairTest.java | 2 +- ...ltLoginCredentialsForVAppTemplateTest.java | 2 +- .../VAppTemplatesInOrgsLiveTest.java | 2 +- .../AddInternetServiceOptionsTest.java | 2 +- .../terremark/options/AddNodeOptionsTest.java | 2 +- ...arkInstantiateVAppTemplateOptionsTest.java | 2 +- .../CustomizationParametersHandlerTest.java | 3 +- .../xml/InternetServiceHandlerTest.java | 3 +- .../xml/InternetServicesHandlerTest.java | 3 +- .../terremark/xml/IpAddressesHandlerTest.java | 3 +- .../vcloud/terremark/xml/KeyHandlerTest.java | 3 +- .../xml/KeyPairByNameHandlerTest.java | 13 +- .../vcloud/terremark/xml/KeysHandlerTest.java | 3 +- .../vcloud/terremark/xml/NodeHandlerTest.java | 5 +- .../terremark/xml/NodesHandlerTest.java | 3 +- .../xml/PublicIpAddressHandlerTest.java | 3 +- .../xml/PublicIpAddressesHandlerTest.java | 3 +- .../xml/ResourceAllocationHandlerTest.java | 3 +- .../xml/TerremarkCatalogItemHandlerTest.java | 3 +- .../xml/TerremarkNetworkHandlerTest.java | 3 +- .../xml/TerremarkOrgHandlerTest.java | 3 +- ...remarkVCloudExpressNetworkHandlerTest.java | 2 +- .../xml/TerremarkVDCHandlerTest.java | 2 +- .../vcloud/terremark/xml/VAppHandlerTest.java | 3 +- .../terremark/xml/ovf/SystemHandlerTest.java | 5 +- 865 files changed, 8904 insertions(+), 5432 deletions(-) create mode 100644 atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedLinkedHashSet.java create mode 100644 atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeadersTest.java create mode 100644 atmos/src/test/java/org/jclouds/atmosonline/saas/functions/AtmosObjectNameTest.java create mode 100644 atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeadersTest.java create mode 100644 atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContentTest.java create mode 100644 atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeadersTest.java create mode 100644 atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExistsTest.java rename aws/core/src/main/java/org/jclouds/aws/ec2/binders/{BindGroupNameToIndexedFormParams.java => BindGroupNamesToIndexedFormParams.java} (82%) rename aws/core/src/main/java/org/jclouds/aws/ec2/binders/{BindKeyNameToIndexedFormParams.java => BindKeyNamesToIndexedFormParams.java} (82%) rename aws/core/src/main/java/org/jclouds/aws/s3/binders/{BindS3ObjectToPayload.java => BindS3ObjectMetadataToRequest.java} (58%) create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignatureTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParamsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParamTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequestTest.java delete mode 100644 aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayloadTest.java create mode 100644 azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequest.java delete mode 100644 azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayload.java create mode 100644 azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequestTest.java delete mode 100644 azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayloadTest.java delete mode 100644 blobstore/src/main/java/org/jclouds/blobstore/functions/ClearAndDeleteIfNotEmpty.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefixTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefixTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/BlobNameTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/BlobToHttpGetOptionsTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ObjectMD5Test.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/PrefixToResourceMetadataTest.java rename blobstore/src/test/java/org/jclouds/blobstore/functions/{BlobMetadataToRelativePathResourceMetadataTest.java => ResourceMetadataToRelativePathResourceMetadataTest.java} (95%) create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFoundTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFoundTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFoundTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFoundTest.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404Test.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404Test.java create mode 100644 blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/BiggerThanPageSizeTest.java rename atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedHashSet.java => core/src/main/java/org/jclouds/functions/IdentityFunction.java (59%) create mode 100644 core/src/main/java/org/jclouds/http/utils/ModifyRequest.java create mode 100644 core/src/main/java/org/jclouds/rest/Providers.java create mode 100644 core/src/main/java/org/jclouds/util/Assertions.java create mode 100644 core/src/main/java/org/jclouds/util/CredentialUtils.java create mode 100644 core/src/main/java/org/jclouds/util/Lists2.java create mode 100644 core/src/main/java/org/jclouds/util/Maps2.java create mode 100644 core/src/main/java/org/jclouds/util/Modules2.java create mode 100644 core/src/main/java/org/jclouds/util/NullSafeCollections.java create mode 100644 core/src/main/java/org/jclouds/util/Preconditions2.java create mode 100644 core/src/main/java/org/jclouds/util/SaxUtils.java create mode 100644 core/src/main/java/org/jclouds/util/Strings2.java create mode 100644 core/src/main/java/org/jclouds/util/Suppliers2.java create mode 100644 core/src/main/java/org/jclouds/util/Throwables2.java delete mode 100644 core/src/main/java/org/jclouds/util/Utils.java create mode 100644 core/src/test/java/org/jclouds/http/utils/ModifyRequestTest.java create mode 100644 core/src/test/java/org/jclouds/util/CredentialUtilsTest.java create mode 100644 core/src/test/java/org/jclouds/util/Lists2Test.java create mode 100644 core/src/test/java/org/jclouds/util/Maps2Test.java create mode 100644 core/src/test/java/org/jclouds/util/ProvidersTest.java create mode 100644 core/src/test/java/org/jclouds/util/Strings2Test.java rename core/src/test/java/org/jclouds/util/{UtilsTest.java => Throwables2Test.java} (51%) rename rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/{BindCFObjectToPayload.java => BindCFObjectMetadataToRequest.java} (68%) create mode 100644 rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequestTest.java delete mode 100644 rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayloadTest.java diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClient.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClient.java index ec9a939907..58a8018179 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClient.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClient.java @@ -82,7 +82,6 @@ public interface AtmosStorageAsyncClient { * @see AtmosStorageClient#listDirectories */ @GET - @Path("") @ResponseParser(ParseDirectoryListFromContentAndHeaders.class) @Consumes(MediaType.TEXT_XML) ListenableFuture> listDirectories(ListOptions... options); diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageResponseException.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageResponseException.java index 8cb402955e..730971e8c5 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageResponseException.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/AtmosStorageResponseException.java @@ -41,7 +41,7 @@ public class AtmosStorageResponseException extends HttpResponseException { public AtmosStorageResponseException(HttpCommand command, HttpResponse response, AtmosStorageError error) { - super(String.format("command %s failed with code %s, error: %s", command.getRequest() + super(String.format("command %s failed with code %s, error: %s", command.getCurrentRequest() .getRequestLine(), response.getStatusCode(), error.toString()), command, response); this.setError(error); @@ -49,7 +49,7 @@ public class AtmosStorageResponseException extends HttpResponseException { public AtmosStorageResponseException(HttpCommand command, HttpResponse response, AtmosStorageError error, Throwable cause) { - super(String.format("command %1$s failed with error: %2$s", command.getRequest() + super(String.format("command %1$s failed with error: %2$s", command.getCurrentRequest() .getRequestLine(), error.toString()), command, response, cause); this.setError(error); diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeaders.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeaders.java index 76e8a91238..e3295abcd2 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeaders.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeaders.java @@ -20,28 +20,36 @@ package org.jclouds.atmosonline.saas.binders; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.atmosonline.saas.domain.AtmosObject; -import org.jclouds.crypto.Crypto; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; +/** + * @author Adrian Cole + */ @Singleton public class BindMetadataToHeaders implements Binder { private final BindUserMetadataToHeaders metaBinder; @Inject - protected BindMetadataToHeaders(BindUserMetadataToHeaders metaBinder, Crypto crypto) { + protected BindMetadataToHeaders(BindUserMetadataToHeaders metaBinder) { this.metaBinder = metaBinder; } - public void bindToRequest(HttpRequest request, Object payload) { - AtmosObject object = (AtmosObject) payload; + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof AtmosObject, "this binder is only valid for AtmosObject!"); + checkNotNull(request, "request"); + + AtmosObject object = AtmosObject.class.cast(input); + checkNotNull(object.getPayload(), "object payload"); checkArgument(object.getPayload().getContentMetadata().getContentLength() != null, - "contentLength must be set, streaming not supported"); - metaBinder.bindToRequest(request, object.getUserMetadata()); + "contentLength must be set, streaming not supported"); + return metaBinder.bindToRequest(request, object.getUserMetadata()); } } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeaders.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeaders.java index 2f1afea3d4..a36a520f08 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeaders.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeaders.java @@ -19,36 +19,57 @@ package org.jclouds.atmosonline.saas.binders; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import java.util.Map; + import javax.inject.Singleton; import org.jclouds.atmosonline.saas.domain.UserMetadata; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; +import com.google.common.base.Function; import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Multimaps; +/** + * @author Adrian Cole + */ @Singleton -public class BindUserMetadataToHeaders implements Binder { +public class BindUserMetadataToHeaders implements Binder, Function> { + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof UserMetadata, + "this binder is only valid for UserMetadatas!"); + checkNotNull(request, "request"); - public void bindToRequest(HttpRequest request, Object payload) { - UserMetadata md = (UserMetadata) checkNotNull(payload, "payload"); + return ModifyRequest.putHeaders(request, Multimaps.forMap(apply(UserMetadata.class.cast(input)))); + } + + @Override + public Map apply(UserMetadata md) { + Builder headers = ImmutableMap. builder(); if (md.getMetadata().size() > 0) { String header = Joiner.on(',').withKeyValueSeparator("=").join(md.getMetadata()); - request.getHeaders().put("x-emc-meta", header); + headers.put("x-emc-meta", header); } if (md.getListableMetadata().size() > 0) { String header = Joiner.on(',').withKeyValueSeparator("=").join(md.getListableMetadata()); - request.getHeaders().put("x-emc-listable-meta", header); + headers.put("x-emc-listable-meta", header); } if (md.getTags().size() > 0) { String header = Joiner.on(',').join(md.getTags()); - request.getHeaders().put("x-emc-tags", header); + headers.put("x-emc-tags", header); } if (md.getListableTags().size() > 0) { String header = Joiner.on(',').join(md.getListableTags()); - request.getHeaders().put("x-emc-listable-tags", header); + headers.put("x-emc-listable-tags", header); } + return headers.build(); } } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/strategy/FindMD5InUserMetadata.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/strategy/FindMD5InUserMetadata.java index 14553b2202..618b89c927 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/strategy/FindMD5InUserMetadata.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/strategy/FindMD5InUserMetadata.java @@ -73,21 +73,22 @@ public class FindMD5InUserMetadata implements ContainsValueInListStrategy { protected Long maxTime; @Inject - private FindMD5InUserMetadata(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, - ObjectMD5 objectMD5, ListBlobsInContainer getAllBlobMetadata, AtmosStorageAsyncClient client) { + FindMD5InUserMetadata(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, ObjectMD5 objectMD5, + ListBlobsInContainer getAllBlobMetadata, AtmosStorageAsyncClient client) { this.objectMD5 = objectMD5; this.getAllBlobMetadata = getAllBlobMetadata; this.client = client; this.userExecutor = userExecutor; } + @Override public boolean execute(final String containerName, Object value, ListContainerOptions options) { final byte[] toSearch = objectMD5.apply(value); final BlockingQueue queue = new SynchronousQueue(); Map> responses = Maps.newHashMap(); for (BlobMetadata md : getAllBlobMetadata.execute(containerName, options)) { - final ListenableFuture future = Futures.makeListenable(client.headFile(containerName - + "/" + md.getName()), userExecutor); + final ListenableFuture future = Futures.makeListenable( + client.headFile(containerName + "/" + md.getName()), userExecutor); future.addListener(new Runnable() { public void run() { try { @@ -109,11 +110,11 @@ public class FindMD5InUserMetadata implements ContainsValueInListStrategy { }, userExecutor); responses.put(md.getName(), future); } - Map exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, String.format( - "searching for md5 in container %s", containerName)); + Map exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, + String.format("searching for md5 in container %s", containerName)); if (exceptions.size() > 0) throw new BlobRuntimeException(String.format("searching for md5 in container %s: %s", containerName, - exceptions)); + exceptions)); try { return queue.poll(1, TimeUnit.MICROSECONDS) != null; } catch (InterruptedException e) { @@ -122,7 +123,7 @@ public class FindMD5InUserMetadata implements ContainsValueInListStrategy { } catch (Exception e) { Throwables.propagateIfPossible(e, BlobRuntimeException.class); throw new BlobRuntimeException(String.format("Error searching for ETAG of value: [%s] in container:%s", value, - containerName), e); + containerName), e); } } } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/config/AtmosObjectModule.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/config/AtmosObjectModule.java index d8b8a5b01f..a56160c1dc 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/config/AtmosObjectModule.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/config/AtmosObjectModule.java @@ -19,19 +19,12 @@ package org.jclouds.atmosonline.saas.config; -import javax.inject.Inject; -import javax.inject.Provider; - import org.jclouds.atmosonline.saas.domain.AtmosObject; import org.jclouds.atmosonline.saas.domain.MutableContentMetadata; -import org.jclouds.atmosonline.saas.domain.SystemMetadata; -import org.jclouds.atmosonline.saas.domain.UserMetadata; -import org.jclouds.atmosonline.saas.domain.internal.AtmosObjectImpl; import org.jclouds.blobstore.config.BlobStoreObjectModule; import com.google.inject.AbstractModule; import com.google.inject.Provides; -import com.google.inject.Scopes; /** * Configures the domain object mappings needed for all Atmos implementations @@ -48,27 +41,6 @@ public class AtmosObjectModule extends AbstractModule { protected void configure() { // for converters install(new BlobStoreObjectModule()); - bind(AtmosObject.Factory.class).to(AtmosObjectFactory.class).in(Scopes.SINGLETON); - } - - private static class AtmosObjectFactory implements AtmosObject.Factory { - - @Inject - Provider metadataProvider; - - public AtmosObject create(MutableContentMetadata contentMetadata) { - return new AtmosObjectImpl(contentMetadata != null ? contentMetadata : metadataProvider - .get()); - } - - public AtmosObject create(SystemMetadata systemMetadata, UserMetadata userMetadata) { - return new AtmosObjectImpl(metadataProvider.get(), systemMetadata, userMetadata); - } - - public AtmosObject create(MutableContentMetadata contentMetadata, - SystemMetadata systemMetadata, UserMetadata userMetadata) { - return new AtmosObjectImpl(contentMetadata, systemMetadata, userMetadata); - } } @Provides diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java index 00e942bd77..ef87d68065 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java @@ -21,28 +21,25 @@ package org.jclouds.atmosonline.saas.domain; import javax.annotation.Nullable; +import org.jclouds.atmosonline.saas.domain.internal.AtmosObjectImpl.AtmosObjectFactory; import org.jclouds.io.PayloadEnclosing; import com.google.common.collect.Multimap; +import com.google.inject.ImplementedBy; /** - * Amazon Atmos is designed to store objects. Objects are stored in buckets and consist of a - * {@link ObjectMetadataAtmosObject#getInput() value}, a {@link ObjectMetadata#getKey key}, - * {@link ObjectMetadata#getUserMetadata() metadata}, and an access control policy. * * @author Adrian Cole - * @see */ public interface AtmosObject extends PayloadEnclosing, Comparable { + @ImplementedBy(AtmosObjectFactory.class) public interface Factory { AtmosObject create(@Nullable MutableContentMetadata contentMetadata); AtmosObject create(SystemMetadata systemMetadata, UserMetadata userMetadata); AtmosObject create(MutableContentMetadata contentMetadata, SystemMetadata systemMetadata, - UserMetadata userMetadata); + UserMetadata userMetadata); } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/BoundedSet.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/BoundedSet.java index db7b378fc8..d8e92a525f 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/BoundedSet.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/BoundedSet.java @@ -21,7 +21,9 @@ package org.jclouds.atmosonline.saas.domain; import java.util.Set; -import org.jclouds.atmosonline.saas.domain.internal.BoundedHashSet; +import javax.annotation.Nullable; + +import org.jclouds.atmosonline.saas.domain.internal.BoundedLinkedHashSet; import com.google.inject.ImplementedBy; @@ -30,9 +32,10 @@ import com.google.inject.ImplementedBy; * @author Adrian Cole * */ -@ImplementedBy(BoundedHashSet.class) +@ImplementedBy(BoundedLinkedHashSet.class) public interface BoundedSet extends Set { + @Nullable String getToken(); } \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/UserMetadata.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/UserMetadata.java index 29bfd5a3d0..9a617d1905 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/UserMetadata.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/UserMetadata.java @@ -19,10 +19,10 @@ package org.jclouds.atmosonline.saas.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Map; import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; @@ -33,10 +33,25 @@ import com.google.common.collect.Sets; * @author Adrian Cole */ public class UserMetadata { - private final SortedMap metadata = Maps.newTreeMap(); - private final SortedMap listableMetadata = Maps.newTreeMap(); - private final SortedSet tags = Sets.newTreeSet(); - private final SortedSet listableTags = Sets.newTreeSet(); + private final Map metadata; + private final Map listableMetadata; + private final Set tags; + private final Set listableTags; + + public UserMetadata(Map metadata, Map listableMetadata, Iterable tags, + Iterable listableTags) { + this.metadata = Maps.newLinkedHashMap(checkNotNull(metadata, "metadata")); + this.listableMetadata = Maps.newLinkedHashMap(checkNotNull(listableMetadata, "listableMetadata")); + this.tags = Sets.newLinkedHashSet(checkNotNull(tags, "tags")); + this.listableTags = Sets.newLinkedHashSet(checkNotNull(listableTags, "listableTags")); + } + + public UserMetadata() { + this.metadata = Maps.newLinkedHashMap(); + this.listableMetadata = Maps.newLinkedHashMap(); + this.tags = Sets.newLinkedHashSet(); + this.listableTags = Sets.newLinkedHashSet(); + } public Map getMetadata() { return metadata; @@ -54,4 +69,53 @@ public class UserMetadata { return listableTags; } + @Override + public String toString() { + return "[metadata=" + metadata + ", listableMetadata=" + listableMetadata + ", tags=" + tags + ", listableTags=" + + listableTags + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((listableMetadata == null) ? 0 : listableMetadata.hashCode()); + result = prime * result + ((listableTags == null) ? 0 : listableTags.hashCode()); + result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); + result = prime * result + ((tags == null) ? 0 : tags.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; + UserMetadata other = (UserMetadata) obj; + if (listableMetadata == null) { + if (other.listableMetadata != null) + return false; + } else if (!listableMetadata.equals(other.listableMetadata)) + return false; + if (listableTags == null) { + if (other.listableTags != null) + return false; + } else if (!listableTags.equals(other.listableTags)) + return false; + if (metadata == null) { + if (other.metadata != null) + return false; + } else if (!metadata.equals(other.metadata)) + return false; + if (tags == null) { + if (other.tags != null) + return false; + } else if (!tags.equals(other.tags)) + return false; + return true; + } + } \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/AtmosObjectImpl.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/AtmosObjectImpl.java index 9f53e2f481..eeb523a024 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/AtmosObjectImpl.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/AtmosObjectImpl.java @@ -22,6 +22,8 @@ package org.jclouds.atmosonline.saas.domain.internal; import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; +import javax.inject.Provider; +import javax.inject.Singleton; import org.jclouds.atmosonline.saas.domain.AtmosObject; import org.jclouds.atmosonline.saas.domain.MutableContentMetadata; @@ -39,6 +41,26 @@ import com.google.common.collect.Multimap; * @author Adrian Cole */ public class AtmosObjectImpl extends PayloadEnclosingImpl implements AtmosObject, Comparable { + @Singleton + public static class AtmosObjectFactory implements AtmosObject.Factory { + + @Inject + Provider metadataProvider; + + public AtmosObject create(MutableContentMetadata contentMetadata) { + return new AtmosObjectImpl(contentMetadata != null ? contentMetadata : metadataProvider.get()); + } + + public AtmosObject create(SystemMetadata systemMetadata, UserMetadata userMetadata) { + return new AtmosObjectImpl(metadataProvider.get(), systemMetadata, userMetadata); + } + + public AtmosObject create(MutableContentMetadata contentMetadata, SystemMetadata systemMetadata, + UserMetadata userMetadata) { + return new AtmosObjectImpl(contentMetadata, systemMetadata, userMetadata); + } + } + private final UserMetadata userMetadata; private final SystemMetadata systemMetadata; @@ -50,12 +72,11 @@ public class AtmosObjectImpl extends PayloadEnclosingImpl implements AtmosObject return userMetadata; } - private MutableContentMetadata contentMetadata; + private MutableContentMetadata contentMetadata; private Multimap allHeaders = LinkedHashMultimap.create(); public AtmosObjectImpl(MutableContentMetadata contentMetadata, SystemMetadata systemMetadata, - UserMetadata userMetadata) { - super(); + UserMetadata userMetadata) { this.contentMetadata = contentMetadata; this.systemMetadata = systemMetadata; this.userMetadata = userMetadata; @@ -145,6 +166,7 @@ public class AtmosObjectImpl extends PayloadEnclosingImpl implements AtmosObject @Override public void setPayload(Payload data) { this.payload = data; - this.contentMetadata = new DelegatingMutableContentMetadata(contentMetadata.getName(), payload.getContentMetadata()); + this.contentMetadata = new DelegatingMutableContentMetadata(contentMetadata.getName(), + payload.getContentMetadata()); } } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedLinkedHashSet.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedLinkedHashSet.java new file mode 100644 index 0000000000..2a8c4b782d --- /dev/null +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedLinkedHashSet.java @@ -0,0 +1,83 @@ +/** + * + * 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.atmosonline.saas.domain.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.LinkedHashSet; + +import javax.annotation.Nullable; + +import org.jclouds.atmosonline.saas.domain.BoundedSet; + +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + * + */ +public class BoundedLinkedHashSet extends LinkedHashSet implements BoundedSet { + + /** The serialVersionUID */ + private static final long serialVersionUID = -7133632087734650835L; + protected final String token; + + public BoundedLinkedHashSet(Iterable contents, @Nullable String token) { + Iterables.addAll(this, checkNotNull(contents, "contents")); + this.token = token; + } + + @Nullable + public String getToken() { + return token; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((token == null) ? 0 : token.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + BoundedLinkedHashSet other = (BoundedLinkedHashSet) obj; + if (token == null) { + if (other.token != null) + return false; + } else if (!token.equals(other.token)) + return false; + return true; + } + + @Override + public String toString() { + return "[token=" + token + ", contents=" + super.toString() + "]"; + } + +} \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/DelegatingMutableContentMetadata.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/DelegatingMutableContentMetadata.java index d27744fe22..b752d20fc2 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/DelegatingMutableContentMetadata.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/DelegatingMutableContentMetadata.java @@ -22,6 +22,8 @@ package org.jclouds.atmosonline.saas.domain.internal; import org.jclouds.atmosonline.saas.domain.MutableContentMetadata; import org.jclouds.io.payloads.BaseMutableContentMetadata; +import com.google.common.collect.Multimap; + /** * * @author Adrian Cole @@ -150,4 +152,9 @@ public class DelegatingMutableContentMetadata implements MutableContentMetadata return delegate.getContentLanguage(); } + @Override + public void setPropertiesFromHttpHeaders(Multimap headers) { + delegate.setPropertiesFromHttpHeaders(headers); + } + } \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/filters/SignRequest.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/filters/SignRequest.java index 23a5ef0c3e..c929512182 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/filters/SignRequest.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/filters/SignRequest.java @@ -25,7 +25,6 @@ import static org.jclouds.Constants.PROPERTY_IDENTITY; import static org.jclouds.util.Patterns.NEWLINE_PATTERN; import static org.jclouds.util.Patterns.TWO_SPACE_PATTERN; -import java.util.Collections; import java.util.Set; import java.util.TreeSet; @@ -45,11 +44,15 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpUtils; import org.jclouds.http.internal.SignatureWire; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.io.InputSuppliers; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Multimaps; /** * Signs the EMC Atmos Online Storage request. @@ -77,8 +80,8 @@ public class SignRequest implements HttpRequestFilter { @Inject public SignRequest(SignatureWire signatureWire, @Named(PROPERTY_IDENTITY) String uid, - @Named(PROPERTY_CREDENTIAL) String encodedKey, @TimeStamp Provider timeStampProvider, - Crypto crypto, HttpUtils utils) { + @Named(PROPERTY_CREDENTIAL) String encodedKey, @TimeStamp Provider timeStampProvider, Crypto crypto, + HttpUtils utils) { this.signatureWire = signatureWire; this.uid = uid; this.key = CryptoStreams.base64(encodedKey); @@ -87,16 +90,19 @@ public class SignRequest implements HttpRequestFilter { this.utils = utils; } - public void filter(HttpRequest request) throws HttpException { - String toSign = replaceUIDHeader(request).removeOldSignature(request).replaceDateHeader(request) - .createStringToSign(request); - calculateAndReplaceAuthHeader(request, toSign); + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { + Builder builder = ImmutableMap.builder(); + builder.put(AtmosStorageHeaders.UID, uid); + String date = timeStampProvider.get(); + builder.put(HttpHeaders.DATE, date); + if (request.getHeaders().containsKey(AtmosStorageHeaders.DATE)) + builder.put(AtmosStorageHeaders.DATE, date); + request = ModifyRequest.replaceHeaders(request, Multimaps.forMap(builder.build())); + String signature = calculateSignature(createStringToSign(request)); + request = ModifyRequest.replaceHeader(request, AtmosStorageHeaders.SIGNATURE, signature); utils.logRequest(signatureLog, request, "<<"); - } - - private SignRequest removeOldSignature(HttpRequest request) { - request.getHeaders().removeAll(AtmosStorageHeaders.SIGNATURE); - return this; + return request; } public String createStringToSign(HttpRequest request) { @@ -113,11 +119,11 @@ public class SignRequest implements HttpRequestFilter { return buffer.toString(); } - private void calculateAndReplaceAuthHeader(HttpRequest request, String toSign) throws HttpException { + private String calculateSignature(String toSign) { String signature = signString(toSign); if (signatureWire.enabled()) - signatureWire.input(Utils.toInputStream(signature)); - request.getHeaders().replaceValues(AtmosStorageHeaders.SIGNATURE, Collections.singletonList(signature)); + signatureWire.input(Strings2.toInputStream(signature)); + return signature; } public String signString(String toSign) { @@ -134,16 +140,6 @@ public class SignRequest implements HttpRequestFilter { toSign.append(request.getMethod()).append("\n"); } - SignRequest replaceUIDHeader(HttpRequest request) { - request.getHeaders().replaceValues(AtmosStorageHeaders.UID, Collections.singletonList(uid)); - return this; - } - - SignRequest replaceDateHeader(HttpRequest request) { - request.getHeaders().replaceValues(HttpHeaders.DATE, Collections.singletonList(timeStampProvider.get())); - return this; - } - private void appendCanonicalizedHeaders(HttpRequest request, StringBuilder toSign) { // TreeSet == Sort the headers alphabetically. Set headers = new TreeSet(request.getHeaders().keySet()); @@ -155,8 +151,8 @@ public class SignRequest implements HttpRequestFilter { // replacing any // newline characters and extra embedded white spaces in the value. for (String value : request.getHeaders().get(header)) { - value = Utils.replaceAll(value, TWO_SPACE_PATTERN, " "); - value = Utils.replaceAll(value, NEWLINE_PATTERN, ""); + value = Strings2.replaceAll(value, TWO_SPACE_PATTERN, " "); + value = Strings2.replaceAll(value, NEWLINE_PATTERN, ""); toSign.append(value).append(' '); } toSign.deleteCharAt(toSign.lastIndexOf(" ")); @@ -171,8 +167,9 @@ public class SignRequest implements HttpRequestFilter { } private void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) { - buffer.append(utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata().getContentType())) - .append("\n"); + buffer.append( + utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() + .getContentType())).append("\n"); } @VisibleForTesting diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/AtmosObjectName.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/AtmosObjectName.java index 09e61f2d88..6f9616af56 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/AtmosObjectName.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/AtmosObjectName.java @@ -19,6 +19,9 @@ package org.jclouds.atmosonline.saas.functions; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Singleton; import org.jclouds.atmosonline.saas.domain.AtmosObject; @@ -31,11 +34,14 @@ import com.google.common.base.Function; */ @Singleton public class AtmosObjectName implements Function { + @Override + public String apply(Object input) { + checkArgument(checkNotNull(input, "input") instanceof AtmosObject, + "this function is only valid for AtmosObjects!"); + AtmosObject object = AtmosObject.class.cast(input); - public String apply(Object in) { - AtmosObject from = (AtmosObject) in; - return from.getContentMetadata().getName() != null ? from.getContentMetadata().getName() - : from.getSystemMetadata().getObjectName(); + return checkNotNull(object.getContentMetadata().getName() != null ? object.getContentMetadata().getName() + : object.getSystemMetadata().getObjectName(), "objectName"); } } \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeaders.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeaders.java index 1f334b8092..2cfc37a3ba 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeaders.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeaders.java @@ -19,13 +19,15 @@ package org.jclouds.atmosonline.saas.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import org.jclouds.atmosonline.saas.domain.BoundedSet; import org.jclouds.atmosonline.saas.domain.DirectoryEntry; -import org.jclouds.atmosonline.saas.domain.internal.BoundedHashSet; +import org.jclouds.atmosonline.saas.domain.internal.BoundedLinkedHashSet; import org.jclouds.atmosonline.saas.reference.AtmosStorageHeaders; import org.jclouds.atmosonline.saas.xml.ListDirectoryResponseHandler; import org.jclouds.http.HttpResponse; @@ -40,25 +42,24 @@ import com.google.common.base.Function; * @author Adrian Cole */ @Singleton -public class ParseDirectoryListFromContentAndHeaders implements - Function> { +public class ParseDirectoryListFromContentAndHeaders implements Function> { private final ParseSax.Factory factory; private final Provider listHandlerProvider; @Inject - private ParseDirectoryListFromContentAndHeaders(Factory factory, - Provider orgHandlerProvider) { - this.factory = factory; - this.listHandlerProvider = orgHandlerProvider; + ParseDirectoryListFromContentAndHeaders(Factory factory, Provider listHandlerProvider) { + this.factory = checkNotNull(factory, "factory"); + this.listHandlerProvider = checkNotNull(listHandlerProvider, "listHandlerProvider"); } /** * parses the http response headers to create a new {@link BoundedSet} object. */ public BoundedSet apply(HttpResponse from) { + checkNotNull(from, "http response"); String token = from.getFirstHeaderOrNull(AtmosStorageHeaders.TOKEN); - return new BoundedHashSet(factory.create(listHandlerProvider.get()).parse( - from.getPayload().getInput()), token); + return new BoundedLinkedHashSet(factory.create(listHandlerProvider.get()).parse( + from.getPayload().getInput()), token); } } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContent.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContent.java index 8cbdd4d23f..f75bcad351 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContent.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContent.java @@ -19,6 +19,7 @@ package org.jclouds.atmosonline.saas.functions; +import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.http.HttpUtils.attemptToParseSizeAndRangeFromHeaders; import javax.inject.Inject; @@ -44,11 +45,11 @@ public class ParseObjectFromHeadersAndHttpContent implements Function metaMap = Maps.newHashMap(); String[] metas = meta.split(", "); @@ -59,12 +60,12 @@ public class ParseSystemMetadataFromHeaders implements Function= 12 : String.format("Should be 12 entries in %s", metaMap); byte[] md5 = metaMap.containsKey("content-md5") ? CryptoStreams.hex(metaMap.get("content-md5")) : null; return new SystemMetadata(md5, dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("atime"), "atime")), - dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("ctime"), "ctime")), checkNotNull(metaMap - .get("gid"), "gid"), dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("itime"), - "itime")), dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("mtime"), "mtime")), - Integer.parseInt(checkNotNull(metaMap.get("nlink"), "nlink")), checkNotNull(metaMap.get("objectid"), - "objectid"), checkNotNull(metaMap.get("objname"), "objname"), checkNotNull(metaMap - .get("policyname"), "policyname"), Long.parseLong(checkNotNull(metaMap.get("size"), "size")), - FileType.fromValue(checkNotNull(metaMap.get("type"), "type")), checkNotNull(metaMap.get("uid"), "uid")); + dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("ctime"), "ctime")), checkNotNull( + metaMap.get("gid"), "gid"), dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("itime"), + "itime")), dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get("mtime"), "mtime")), + Integer.parseInt(checkNotNull(metaMap.get("nlink"), "nlink")), checkNotNull(metaMap.get("objectid"), + "objectid"), checkNotNull(metaMap.get("objname"), "objname"), checkNotNull(metaMap.get("policyname"), + "policyname"), Long.parseLong(checkNotNull(metaMap.get("size"), "size")), + FileType.fromValue(checkNotNull(metaMap.get("type"), "type")), checkNotNull(metaMap.get("uid"), "uid")); } } \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeaders.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeaders.java index 9d64754c24..2d03f98dc2 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeaders.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeaders.java @@ -31,54 +31,55 @@ import org.jclouds.atmosonline.saas.reference.AtmosStorageHeaders; import org.jclouds.http.HttpResponse; import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; -import com.google.common.collect.Sets; /** * @author Adrian Cole */ @Singleton public class ParseUserMetadataFromHeaders implements Function { - private final Set sysKeys = ImmutableSet.of("atime", "ctime", "gid", "itime", "mtime", - "nlink", "policyname", "size", "uid"); + private static final Set sysKeys = ImmutableSet.of("atime", "ctime", "gid", "itime", "mtime", "nlink", + "policyname", "size", "uid", "content-md5", "objectid", "objname", "type"); + private static final Predicate filter = new Predicate() { + + @Override + public boolean apply(String arg0) { + return !sysKeys.contains(arg0); + } + + }; public UserMetadata apply(HttpResponse from) { - UserMetadata md = new UserMetadata(); - Map metaMap = getMetaMap(checkNotNull(from - .getFirstHeaderOrNull(AtmosStorageHeaders.META), AtmosStorageHeaders.META)); + checkNotNull(from, "http response"); - Set keys = Sets.difference(metaMap.keySet(), sysKeys); - for (String key : keys) { - md.getMetadata().put(key, metaMap.get(key)); - } - if (from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_META) != null) - md.getListableMetadata().putAll( - getMetaMap(from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_META))); + Map meta = Maps.filterKeys( + getMetaMap(checkNotNull(from.getFirstHeaderOrNull(AtmosStorageHeaders.META), AtmosStorageHeaders.META)), + filter); - if (from.getFirstHeaderOrNull(AtmosStorageHeaders.TAGS) != null) - md.getTags().addAll(getTags(from.getFirstHeaderOrNull(AtmosStorageHeaders.TAGS))); - if (from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_TAGS) != null) - md.getTags().addAll(getTags(from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_TAGS))); - return md; - } - - private Set getTags(String meta) { - Set tags = Sets.newTreeSet(); - String[] metas = meta.split(", "); - for (String entry : metas) { - tags.add(entry); - } - return tags; + Map listableMeta = (from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_META) != null) ? getMetaMap(from + .getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_META)) : ImmutableMap. of(); + + Iterable tags = (from.getFirstHeaderOrNull(AtmosStorageHeaders.TAGS) != null) ? Splitter.on(", ").split( + from.getFirstHeaderOrNull(AtmosStorageHeaders.TAGS)) : ImmutableSet. of(); + + Iterable listableTags = (from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_TAGS) != null) ? Splitter + .on(", ").split(from.getFirstHeaderOrNull(AtmosStorageHeaders.LISTABLE_TAGS)) : ImmutableSet. of(); + + return new UserMetadata(meta, listableMeta, tags, listableTags); } + // TODO: change to guava private Map getMetaMap(String meta) { - Map metaMap = Maps.newHashMap(); - String[] metas = meta.split(", "); - for (String entry : metas) { + Builder metaMap = ImmutableMap. builder(); + for (String entry : Splitter.on(", ").split(meta)) { String[] entrySplit = entry.split("="); metaMap.put(entrySplit[0], entrySplit[1]); } - return metaMap; + return metaMap.build(); } } \ No newline at end of file diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExists.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExists.java index d6bdcef487..ec124b21a2 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExists.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExists.java @@ -19,26 +19,31 @@ package org.jclouds.atmosonline.saas.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.net.URI; +import javax.annotation.Nullable; + import org.jclouds.blobstore.KeyAlreadyExistsException; import org.jclouds.http.HttpRequest; import org.jclouds.rest.InvocationContext; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; /** * * @author Adrian Cole */ -public class ReturnEndpointIfAlreadyExists implements Function, InvocationContext { +public class ReturnEndpointIfAlreadyExists implements Function, + InvocationContext { private URI endpoint; public URI apply(Exception from) { - if (from instanceof KeyAlreadyExistsException) { + if (checkNotNull(from, "exception") instanceof KeyAlreadyExistsException) { return endpoint; } return URI.class.cast(propagateOrNull(from)); @@ -46,7 +51,12 @@ public class ReturnEndpointIfAlreadyExists implements Function, @Override public ReturnEndpointIfAlreadyExists setContext(HttpRequest request) { - this.endpoint = request == null ? null : request.getEndpoint(); + return setEndpoint(request == null ? null : request.getEndpoint()); + } + + @VisibleForTesting + ReturnEndpointIfAlreadyExists setEndpoint(@Nullable URI endpoint) { + this.endpoint = endpoint; return this; } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/AtmosStorageClientErrorRetryHandler.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/AtmosStorageClientErrorRetryHandler.java index 0072ebaf94..00e38957e1 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/AtmosStorageClientErrorRetryHandler.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/AtmosStorageClientErrorRetryHandler.java @@ -60,7 +60,7 @@ public class AtmosStorageClientErrorRetryHandler implements HttpRetryHandler { public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (command.getFailureCount() > retryCountLimit) return false; - if (response.getStatusCode() == 404 && command.getRequest().getMethod().equals("DELETE")) { + if (response.getStatusCode() == 404 && command.getCurrentRequest().getMethod().equals("DELETE")) { command.incrementFailureCount(); return true; } else if (response.getStatusCode() == 409 || response.getStatusCode() == 400) { diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/ParseAtmosStorageErrorFromXmlContent.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/ParseAtmosStorageErrorFromXmlContent.java index 61abe7291c..da240b5688 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/ParseAtmosStorageErrorFromXmlContent.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/handlers/ParseAtmosStorageErrorFromXmlContent.java @@ -42,7 +42,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * This will parse and set an appropriate exception on the command object. @@ -72,9 +72,9 @@ public class ParseAtmosStorageErrorFromXmlContent implements HttpErrorHandler { AtmosStorageError error = null; if (response.getPayload() != null) { try { - String content = Utils.toStringAndClose(response.getPayload().getInput()); + String content = Strings2.toStringAndClose(response.getPayload().getInput()); if (content != null && content.indexOf('<') >= 0) { - error = utils.parseAtmosStorageErrorFromContent(command, response, Utils.toInputStream(content)); + error = utils.parseAtmosStorageErrorFromContent(command, response, Strings2.toInputStream(content)); } else { exception = content != null ? new HttpResponseException(command, response, content) : exception; } @@ -83,7 +83,7 @@ public class ParseAtmosStorageErrorFromXmlContent implements HttpErrorHandler { } } if (error != null && error.getCode() == 1016) { - File file = new File(command.getRequest().getEndpoint().getPath()); + File file = new File(command.getCurrentRequest().getEndpoint().getPath()); exception = new KeyAlreadyExistsException(file.getParentFile().getAbsolutePath(), file.getName()); } else { switch (response.getStatusCode()) { @@ -91,10 +91,10 @@ public class ParseAtmosStorageErrorFromXmlContent implements HttpErrorHandler { exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String message = error != null ? error.getMessage() : String.format("%s -> %s", command.getRequest() + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + String message = error != null ? error.getMessage() : String.format("%s -> %s", command.getCurrentRequest() .getRequestLine(), response.getStatusLine()); - String path = command.getRequest().getEndpoint().getPath(); + String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = DIRECTORY_PATH.matcher(path); if (matcher.find()) { exception = new ContainerNotFoundException(matcher.group(1), message); diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/util/AtmosStorageUtils.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/util/AtmosStorageUtils.java index c9c3c81bad..df1b973bdc 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/util/AtmosStorageUtils.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/util/AtmosStorageUtils.java @@ -36,7 +36,7 @@ import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpException; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseSax; -import org.jclouds.util.Utils; +import org.jclouds.util.Assertions; import com.google.common.base.Supplier; @@ -61,7 +61,7 @@ public class AtmosStorageUtils { InputStream content) throws HttpException { AtmosStorageError error = (AtmosStorageError) factory.create(errorHandlerProvider.get()).parse(content); if (error.getCode() == 1032) { - error.setStringSigned(signer.createStringToSign(command.getRequest())); + error.setStringSigned(signer.createStringToSign(command.getCurrentRequest())); } return error; @@ -77,7 +77,7 @@ public class AtmosStorageUtils { public static void deleteAndEnsureGone(final AtmosStorageClient sync, final String path) { try { - if (!Utils.eventuallyTrue(new Supplier() { + if (!Assertions.eventuallyTrue(new Supplier() { public Boolean get() { sync.deletePath(path); return !sync.pathExists(path); diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandler.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandler.java index cb619475fe..562613eff5 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandler.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandler.java @@ -19,7 +19,7 @@ package org.jclouds.atmosonline.saas.xml; -import java.util.SortedSet; +import java.util.Set; import org.jclouds.atmosonline.saas.domain.DirectoryEntry; import org.jclouds.atmosonline.saas.domain.FileType; @@ -34,17 +34,16 @@ import com.google.common.collect.Sets; * @see * @author Adrian Cole */ -public class ListDirectoryResponseHandler extends - ParseSax.HandlerWithResult> { +public class ListDirectoryResponseHandler extends ParseSax.HandlerWithResult> { - private SortedSet entries = Sets.newTreeSet(); + private Set entries = Sets.newLinkedHashSet(); private String currentObjectId; private FileType currentType; private String currentName; private StringBuilder currentText = new StringBuilder(); - public SortedSet getResult() { + public Set getResult() { return entries; } 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 14a229ef48..507d9f6011 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClientTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageAsyncClientTest.java @@ -61,11 +61,12 @@ import com.google.inject.Module; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code AtmosStorageClient} + * Tests behavior of {@code AtmosStorageAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "emcsaas.AtmosStorageClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AtmosStorageAsyncClientTest") public class AtmosStorageAsyncClientTest extends RestClientTest { private BlobToObject blobToObject; diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageClientLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageClientLiveTest.java index 3866944522..e6ff9bbe56 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageClientLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/AtmosStorageClientLiveTest.java @@ -40,7 +40,8 @@ import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payloads; import org.jclouds.io.payloads.InputStreamPayload; -import org.jclouds.util.Utils; +import org.jclouds.util.Assertions; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Supplier; @@ -53,7 +54,7 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "emcsaas.AtmosStorageClientLiveTest") +@Test(groups = "live", sequential = true) public class AtmosStorageClientLiveTest extends BaseBlobStoreIntegrationTest { public AtmosStorageClient getApi() { @@ -187,7 +188,7 @@ public class AtmosStorageClientLiveTest extends BaseBlobStoreIntegrationTest { } Object makeData(String in, boolean stream) { - return stream ? Utils.toInputStream(in) : in; + return stream ? Strings2.toInputStream(in) : in; } private void createOrReplaceObject(String name, Object data, String metadataValue) throws Exception { @@ -239,14 +240,14 @@ public class AtmosStorageClientLiveTest extends BaseBlobStoreIntegrationTest { private static void verifyHeadObject(AtmosStorageClient connection, String path, String metadataValue) throws InterruptedException, ExecutionException, TimeoutException, IOException { AtmosObject getBlob = connection.headFile(path); - assertEquals(Utils.toStringAndClose(getBlob.getPayload().getInput()), ""); + assertEquals(Strings2.toStringAndClose(getBlob.getPayload().getInput()), ""); verifyMetadata(metadataValue, getBlob); } private static void verifyObject(AtmosStorageClient connection, String path, String compare, String metadataValue) throws InterruptedException, ExecutionException, TimeoutException, IOException { AtmosObject getBlob = connection.readFile(path); - assertEquals(Utils.toStringAndClose(getBlob.getPayload().getInput()), compare); + assertEquals(Strings2.toStringAndClose(getBlob.getPayload().getInput()), compare); verifyMetadata(metadataValue, getBlob); } @@ -269,7 +270,7 @@ public class AtmosStorageClientLiveTest extends BaseBlobStoreIntegrationTest { assert md.getUserID() != null; try { - Utils.toStringAndClose(URI.create( + Strings2.toStringAndClose(URI.create( "http://accesspoint.emccis.com/rest/objects/" + getBlob.getSystemMetadata().getObjectID()).toURL() .openStream()); assert false : "shouldn't have worked, since it is private"; @@ -325,7 +326,7 @@ public class AtmosStorageClientLiveTest extends BaseBlobStoreIntegrationTest { getApi().deletePath(path); } catch (KeyNotFoundException ex) { } - assert Utils.eventuallyTrue(new Supplier() { + assert Assertions.eventuallyTrue(new Supplier() { public Boolean get() { return !getApi().pathExists(path); } diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/ProvidersInPropertiesTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/ProvidersInPropertiesTest.java index 4b39dd772e..819495b8b0 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/ProvidersInPropertiesTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.atmosonline.saas; import org.jclouds.blobstore.util.BlobStoreUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "atmosonline") : providers; assert Iterables.contains(providers, "synaptic") : providers; } diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeadersTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeadersTest.java new file mode 100644 index 0000000000..8fad07c325 --- /dev/null +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindMetadataToHeadersTest.java @@ -0,0 +1,89 @@ +/** + * + * 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.atmosonline.saas.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.atmosonline.saas.domain.AtmosObject; +import org.jclouds.http.HttpRequest; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindMetadataToHeaders} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindMetadataToHeadersTest { + Injector injector = Guice.createInjector(); + BindMetadataToHeaders binder = injector.getInstance(BindMetadataToHeaders.class); + + public void testGood() { + AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + object.setPayload(payload); + object.getUserMetadata().getListableMetadata().put("apple", "bear"); + object.getUserMetadata().getListableMetadata().put("sushi", "king"); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + request = binder.bindToRequest(request, object); + assertEquals(request.getFirstHeaderOrNull("x-emc-listable-meta"), "apple=bear,sushi=king"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeAtmosObject() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullPayloadIsBad() { + AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + binder.bindToRequest(request, object); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNullContentLengthIllegal() { + AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(null); + object.setPayload(payload); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + binder.bindToRequest(request, object); + } + + +} diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeadersTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeadersTest.java index 3446e07864..c2f26eba8c 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeadersTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/binders/BindUserMetadataToHeadersTest.java @@ -21,8 +21,11 @@ package org.jclouds.atmosonline.saas.binders; import static org.testng.Assert.assertEquals; +import java.io.File; import java.net.URI; +import javax.ws.rs.HttpMethod; + import org.jclouds.atmosonline.saas.domain.UserMetadata; import org.jclouds.http.HttpRequest; import org.testng.annotations.Test; @@ -35,59 +38,56 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "atmossaas.BindUserMetadataToHeadersTest") +@Test(groups = "unit") public class BindUserMetadataToHeadersTest { + Injector injector = Guice.createInjector(); + BindUserMetadataToHeaders binder = injector.getInstance(BindUserMetadataToHeaders.class); public void testMeta() { - Injector injector = Guice.createInjector(); - BindUserMetadataToHeaders binder = injector - .getInstance(BindUserMetadataToHeaders.class); - UserMetadata metadata = new UserMetadata(); - metadata.getMetadata().put("apple","bear"); - metadata.getMetadata().put("sushi","king"); - HttpRequest request = new HttpRequest("GET",URI.create("http://localhost")); - binder.bindToRequest(request, metadata); + metadata.getMetadata().put("apple", "bear"); + metadata.getMetadata().put("sushi", "king"); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + request = binder.bindToRequest(request, metadata); assertEquals(request.getFirstHeaderOrNull("x-emc-meta"), "apple=bear,sushi=king"); } public void testListableMeta() { - Injector injector = Guice.createInjector(); - BindUserMetadataToHeaders binder = injector - .getInstance(BindUserMetadataToHeaders.class); - UserMetadata metadata = new UserMetadata(); - metadata.getListableMetadata().put("apple","bear"); - metadata.getListableMetadata().put("sushi","king"); - HttpRequest request = new HttpRequest("GET",URI.create("http://localhost")); - binder.bindToRequest(request, metadata); + metadata.getListableMetadata().put("apple", "bear"); + metadata.getListableMetadata().put("sushi", "king"); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + request = binder.bindToRequest(request, metadata); assertEquals(request.getFirstHeaderOrNull("x-emc-listable-meta"), "apple=bear,sushi=king"); } - - + public void testTags() { - Injector injector = Guice.createInjector(); - BindUserMetadataToHeaders binder = injector - .getInstance(BindUserMetadataToHeaders.class); - UserMetadata tagsdata = new UserMetadata(); tagsdata.getTags().add("apple"); tagsdata.getTags().add("sushi"); - HttpRequest request = new HttpRequest("GET",URI.create("http://localhost")); - binder.bindToRequest(request, tagsdata); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + request = binder.bindToRequest(request, tagsdata); assertEquals(request.getFirstHeaderOrNull("x-emc-tags"), "apple,sushi"); } public void testListableTags() { - Injector injector = Guice.createInjector(); - BindUserMetadataToHeaders binder = injector - .getInstance(BindUserMetadataToHeaders.class); - UserMetadata tagsdata = new UserMetadata(); tagsdata.getListableTags().add("apple"); tagsdata.getListableTags().add("sushi"); - HttpRequest request = new HttpRequest("GET",URI.create("http://localhost")); - binder.bindToRequest(request, tagsdata); + HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); + request = binder.bindToRequest(request, tagsdata); assertEquals(request.getFirstHeaderOrNull("x-emc-listable-tags"), "apple,sushi"); } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeUserMetadata() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } } diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobRequestSignerTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobRequestSignerTest.java index 91fa367e17..59a2ec5c8a 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobRequestSignerTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobRequestSignerTest.java @@ -45,7 +45,13 @@ import com.google.common.base.Supplier; import com.google.inject.Module; import com.google.inject.TypeLiteral; -@Test(groups = "unit", testName = "emcsaas.AtmosBlobRequestSignerTest") +/** + * Tests behavior of {@code AtmosBlobRequestSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AtmosBlobRequestSignerTest") public class AtmosBlobRequestSignerTest extends RestClientTest { private BlobRequestSigner signer; diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreModuleTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreModuleTest.java index e565f631b7..1590e5bab6 100755 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreModuleTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreModuleTest.java @@ -37,7 +37,7 @@ import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "emcsaas.AtmosBlobStoreModuleTest") +@Test(groups = "unit") public class AtmosBlobStoreModuleTest { Injector createInjector() { diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ObjectToBlobMetadataTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ObjectToBlobMetadataTest.java index 1cc3e36381..30d1f8d3af 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ObjectToBlobMetadataTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ObjectToBlobMetadataTest.java @@ -31,7 +31,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "atmossaas.ObjectToBlobMetadataTest") +@Test(groups = "unit") public class ObjectToBlobMetadataTest { public void testFromWhenTypeIsDirectory() { diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ResourceMetadataListToDirectoryEntryList.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ResourceMetadataListToDirectoryEntryList.java index 71048e387e..7c72525337 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ResourceMetadataListToDirectoryEntryList.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/functions/ResourceMetadataListToDirectoryEntryList.java @@ -24,7 +24,7 @@ import javax.inject.Singleton; import org.jclouds.atmosonline.saas.domain.BoundedSet; import org.jclouds.atmosonline.saas.domain.DirectoryEntry; import org.jclouds.atmosonline.saas.domain.FileType; -import org.jclouds.atmosonline.saas.domain.internal.BoundedHashSet; +import org.jclouds.atmosonline.saas.domain.internal.BoundedLinkedHashSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; @@ -42,7 +42,7 @@ public class ResourceMetadataListToDirectoryEntryList public BoundedSet apply( org.jclouds.blobstore.domain.PageSet from) { - return new BoundedHashSet(Iterables.transform(from, + return new BoundedLinkedHashSet(Iterables.transform(from, new Function() { public DirectoryEntry apply(StorageMetadata from) { FileType type = (from.getType() == StorageType.FOLDER || from.getType() == StorageType.RELATIVE_PATH) ? FileType.DIRECTORY diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosBlobSignerLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosBlobSignerLiveTest.java index 44867392a4..c751c10d32 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosBlobSignerLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosBlobSignerLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "emcsaas.AtmosBlobSignerLiveTest") +@Test(groups = { "live" }) public class AtmosBlobSignerLiveTest extends BaseBlobSignerLiveTest { } \ No newline at end of file diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerIntegrationLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerIntegrationLiveTest.java index 61a25f0677..0049dc6488 100755 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerIntegrationLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerIntegrationLiveTest.java @@ -31,7 +31,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "emcsaas.AtmosStorageContainerIntegrationTest") +@Test(groups = "live") public class AtmosStorageContainerIntegrationLiveTest extends BaseContainerIntegrationTest { @Override diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerLiveTest.java index 7bcadd8faf..2ce2871281 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageContainerLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "emcsaas.AtmosStorageContainerLiveTest") +@Test(groups = { "live" }) public class AtmosStorageContainerLiveTest extends BaseContainerLiveTest { } \ No newline at end of file diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageInputStreamMapIntegrationLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageInputStreamMapIntegrationLiveTest.java index 49070d943f..25b539ca64 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageInputStreamMapIntegrationLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageInputStreamMapIntegrationLiveTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "emcsaas.AtmosStorageInputStreamMapIntegrationTest") +@Test(groups = "live") public class AtmosStorageInputStreamMapIntegrationLiveTest extends BaseInputStreamMapIntegrationTest { @Override diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageIntegrationLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageIntegrationLiveTest.java index 4a362a2b0f..f35c662bb7 100755 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageIntegrationLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageIntegrationLiveTest.java @@ -34,7 +34,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "emcsaas.AtmosStorageIntegrationTest") +@Test(groups = { "integration", "live" }) public class AtmosStorageIntegrationLiveTest extends BaseBlobIntegrationTest { @DataProvider(name = "delete") diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageLiveTest.java index cd05e05d3e..65c2c7d7a5 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageLiveTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "emcsaas.AtmosStorageLiveTest") +@Test(groups = { "live" }) public class AtmosStorageLiveTest extends BaseBlobLiveTest { protected void checkMD5(String container, String name, byte[] md5) { // atmos does not support content-md5 yet diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageMapIntegrationLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageMapIntegrationLiveTest.java index 73561b2ae0..825a762920 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageMapIntegrationLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageMapIntegrationLiveTest.java @@ -29,7 +29,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "emcsaas.AtmosStorageMapIntegrationTest") +@Test(groups = "live") public class AtmosStorageMapIntegrationLiveTest extends BaseBlobMapIntegrationTest { @Override diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageServiceIntegrationLiveTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageServiceIntegrationLiveTest.java index 0e74a3ef64..b9f11965d9 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageServiceIntegrationLiveTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/blobstore/integration/AtmosStorageServiceIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "emcsaas.AtmosStorageServiceIntegrationTest") +@Test(groups = "live") public class AtmosStorageServiceIntegrationLiveTest extends BaseServiceIntegrationTest { } \ No newline at end of file diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/filters/SignRequestTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/filters/SignRequestTest.java index c0b15d66d0..ecac9a17e4 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/filters/SignRequestTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/filters/SignRequestTest.java @@ -36,57 +36,75 @@ import org.jclouds.date.TimeStamp; import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; import org.jclouds.logging.config.NullLoggingModule; +import org.jclouds.rest.BaseRestClientTest.MockModule; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestContextFactory; -import org.jclouds.rest.BaseRestClientTest.MockModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multimap; import com.google.inject.Injector; import com.google.inject.Module; -@Test(groups = "unit", testName = "emcsaas.SignRequestTest") +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") public class SignRequestTest { + private static final String EXPECTED_SIGNATURE = "WHJo1MFevMnK4jCthJ974L3YHoo="; + private static final String UID = "6039ac182f194e15b9261d73ce044939/user1"; + private static final String DEFAULT_DATE = "Thu, 05 Jun 2008 16:38:19 GMT"; private static final String KEY = "LJLuryj6zs8ste6Y3jTGQp71xq0="; private SignRequest filter; @Test void testCreateStringToSign() throws IOException { - String expects = Utils.toStringAndClose(getClass().getResourceAsStream("/hashstring.txt")); - HttpRequest request = newRequest(); - String toSign = filter.replaceDateHeader(request).createStringToSign(request); + String expects = Strings2.toStringAndClose(getClass().getResourceAsStream("/hashstring.txt")); + HttpRequest request = newRequest(preconstructedHeaders().build()); + String toSign = filter.createStringToSign(request); assertEquals(toSign, expects); } @Test - void testUid() throws IOException, NoSuchAlgorithmException, InvalidKeyException { - HttpRequest request = newRequest(); - filter.replaceUIDHeader(request); - assertEquals(request.getFirstHeaderOrNull(AtmosStorageHeaders.UID), "user"); + void testSignString() throws IOException, NoSuchAlgorithmException, InvalidKeyException { + HttpRequest request = newRequest(preconstructedHeaders().build()); + String toSign = filter.createStringToSign(request); + String signature = filter.signString(toSign); + assertEquals(signature, EXPECTED_SIGNATURE); } @Test - void testSignString() throws IOException, NoSuchAlgorithmException, InvalidKeyException { - String expects = "WHJo1MFevMnK4jCthJ974L3YHoo="; + void testFilter() throws IOException, NoSuchAlgorithmException, InvalidKeyException { + HttpRequest request = newRequest(inputHeaders().build()); + request = filter.filter(request); + assertEquals(request.getFirstHeaderOrNull(AtmosStorageHeaders.SIGNATURE), EXPECTED_SIGNATURE); + } - HttpRequest request = newRequest(); - String toSign = filter.replaceDateHeader(request).createStringToSign(request); - String signature = filter.signString(toSign); - assertEquals(signature, expects); + @Test + void testFilterReplacesOldValues() throws IOException, NoSuchAlgorithmException, InvalidKeyException { + HttpRequest request = newRequest(inputHeaders().put(AtmosStorageHeaders.SIGNATURE, "foo") + .put(HttpHeaders.DATE, "foo").put(AtmosStorageHeaders.DATE, "foo").put(AtmosStorageHeaders.UID, "foo") + .build()); + request = filter.filter(request); + assertEquals(request.getFirstHeaderOrNull(AtmosStorageHeaders.SIGNATURE), EXPECTED_SIGNATURE); } @BeforeClass protected void createFilter() { - Injector injector = new RestContextFactory().createContextBuilder( - "atmosonline", - "user", - KEY, - ImmutableSet. of(new MockModule(), new TestAtmosStorageRestClientModule(), + Injector injector = new RestContextFactory() + .createContextBuilder( + "atmosonline", + UID, + KEY, + ImmutableSet. of(new MockModule(), new TestAtmosStorageRestClientModule(), new NullLoggingModule()), new Properties()).buildInjector(); filter = injector.getInstance(SignRequest.class); @@ -96,6 +114,7 @@ public class SignRequestTest { @RequiresHttp @ConfiguresRestClient private static final class TestAtmosStorageRestClientModule extends AtmosStorageRestClientModule { + @Override protected void configure() { super.configure(); @@ -103,24 +122,34 @@ public class SignRequestTest { @Override protected String provideTimeStamp(@TimeStamp Supplier cache) { - return "Thu, 05 Jun 2008 16:38:19 GMT"; + return DEFAULT_DATE; } } - public HttpRequest newRequest() { - HttpRequest request = new HttpRequest("POST", URI.create("http://localhost/rest/objects")); + public HttpRequest newRequest(Multimap headers) { + HttpRequest request = new HttpRequest("POST", URI.create("http://localhost/rest/objects"), headers); request.setPayload(""); request.getPayload().getContentMetadata().setContentLength(4286l); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM); - - request.getHeaders().put(AtmosStorageHeaders.LISTABLE_META, "part4/part7/part8=quick"); - request.getHeaders().put(AtmosStorageHeaders.META, "part1=buy"); - request.getHeaders().put(HttpHeaders.ACCEPT, "*/*"); - request.getHeaders().put(AtmosStorageHeaders.USER_ACL, "john=FULL_CONTROL,mary=WRITE"); - request.getHeaders().put(AtmosStorageHeaders.DATE, "Thu, 05 Jun 2008 16:38:19 GMT"); - request.getHeaders().put(AtmosStorageHeaders.GROUP_ACL, "other=NONE"); - request.getHeaders().put(HttpHeaders.HOST, "10.5.115.118"); - request.getHeaders().put(AtmosStorageHeaders.UID, "6039ac182f194e15b9261d73ce044939/user1"); return request; } + + protected Builder preconstructedHeaders() { + Builder builder = inputHeaders(); + builder.put(HttpHeaders.DATE, DEFAULT_DATE); + builder.put(AtmosStorageHeaders.UID, UID); + return builder; + } + + protected Builder inputHeaders() { + Builder builder = ImmutableMultimap.builder(); + builder.put(AtmosStorageHeaders.LISTABLE_META, "part4/part7/part8=quick"); + builder.put(AtmosStorageHeaders.META, "part1=buy"); + builder.put(HttpHeaders.ACCEPT, "*/*"); + builder.put(AtmosStorageHeaders.USER_ACL, "john=FULL_CONTROL,mary=WRITE"); + builder.put(AtmosStorageHeaders.GROUP_ACL, "other=NONE"); + builder.put(AtmosStorageHeaders.DATE, DEFAULT_DATE); + builder.put(HttpHeaders.HOST, "10.5.115.118"); + return builder; + } } \ No newline at end of file diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/AtmosObjectNameTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/AtmosObjectNameTest.java new file mode 100644 index 0000000000..a435289519 --- /dev/null +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/AtmosObjectNameTest.java @@ -0,0 +1,69 @@ +/** + * + * 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.atmosonline.saas.functions; + +import static org.testng.Assert.assertEquals; + +import java.io.File; + +import org.jclouds.atmosonline.saas.domain.AtmosObject; +import org.jclouds.atmosonline.saas.domain.AtmosObject.Factory; +import org.jclouds.atmosonline.saas.domain.SystemMetadata; +import org.jclouds.atmosonline.saas.domain.UserMetadata; +import org.testng.annotations.Test; + +import com.google.inject.Guice; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class AtmosObjectNameTest { + AtmosObjectName fn = new AtmosObjectName(); + private static final Factory BLOB_FACTORY = Guice.createInjector().getInstance(AtmosObject.Factory.class); + + @Test + public void testCorrectContentMetadataName() throws SecurityException, NoSuchMethodException { + + AtmosObject blob = BLOB_FACTORY.create(null); + blob.getContentMetadata().setName("foo"); + + assertEquals(fn.apply(blob), "foo"); + } + + @Test + public void testCorrectSystemMetadataObjectName() throws SecurityException, NoSuchMethodException { + + AtmosObject blob = BLOB_FACTORY.create(new SystemMetadata(null, null, null, null, null, null, 0, null, "foo", + null, 0, null, null), new UserMetadata()); + assertEquals(fn.apply(blob), "foo"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeAtmosObject() { + fn.apply(new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeadersTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeadersTest.java new file mode 100644 index 0000000000..f6fbc77b5d --- /dev/null +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseDirectoryListFromContentAndHeadersTest.java @@ -0,0 +1,79 @@ +/** + * + * 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.atmosonline.saas.functions; + +import static org.testng.Assert.assertEquals; + +import java.util.Set; + +import org.jclouds.atmosonline.saas.domain.BoundedSet; +import org.jclouds.atmosonline.saas.domain.DirectoryEntry; +import org.jclouds.atmosonline.saas.domain.FileType; +import org.jclouds.atmosonline.saas.domain.internal.BoundedLinkedHashSet; +import org.jclouds.atmosonline.saas.reference.AtmosStorageHeaders; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.BaseHandlerTest; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Sets; + +/** + * Tests behavior of {@code ParseDirectoryListFromContentAndHeaders} + * + * @author Adrian Cole + */ +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ParseDirectoryListFromContentAndHeadersTest") +public class ParseDirectoryListFromContentAndHeadersTest extends BaseHandlerTest { + + Function> createFn() { + return injector.getInstance(ParseDirectoryListFromContentAndHeaders.class); + } + + public void testWithToken() { + HttpResponse response = new HttpResponse(200, "ok", Payloads.newPayload(getClass().getResourceAsStream( + "/list_basic.xml")), ImmutableMultimap.of(AtmosStorageHeaders.TOKEN, "token")); + + BoundedSet result = createFn().apply(response); + assertEquals(result, new BoundedLinkedHashSet(values(), "token")); + assertEquals(result.getToken(), "token"); + } + + public void testWithoutToken() { + HttpResponse response = new HttpResponse(200, "ok", Payloads.newPayload(getClass().getResourceAsStream( + "/list_basic.xml"))); + BoundedSet result = createFn().apply(response); + + assertEquals(result, values()); + assertEquals(result.getToken(), null); + } + + protected Set values() { + Set expected = Sets.newLinkedHashSet(); + expected.add(new DirectoryEntry("4980cdb2a411106a04a4538c92a1b204ad92077de6e3", FileType.DIRECTORY, + "adriancole-blobstore-2096685753")); + expected.add(new DirectoryEntry("4980cdb2a410105404980d99e53a0504ad93939e7dc3", FileType.DIRECTORY, + "adriancole-blobstore247496608")); + return expected; + } +} diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContentTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContentTest.java new file mode 100644 index 0000000000..756e9b810a --- /dev/null +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseObjectFromHeadersAndHttpContentTest.java @@ -0,0 +1,66 @@ +/** + * + * 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.atmosonline.saas.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.atmosonline.saas.domain.AtmosObject; +import org.jclouds.atmosonline.saas.reference.AtmosStorageHeaders; +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMultimap; +import com.google.inject.Guice; + +/** + * Tests behavior of {@code ParseObjectFromHeadersAndHttpContent} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ParseObjectFromHeadersAndHttpContentTest { + + static final HttpResponse RESPONSE = new HttpResponse(200, "ok", Payloads.newStringPayload(""), + ImmutableMultimap.of(AtmosStorageHeaders.TAGS, "tag1, tag2", AtmosStorageHeaders.LISTABLE_TAGS, + "listabletag1, listabletag2", AtmosStorageHeaders.META, + "meta1=foo1, content-md5=1f3870be274f6c49b3e31a0c6728957f, atime=2009-10-12T16:09:42Z, mtime=2009-10-19T04:37:00Z," + + " ctime=2009-10-19T04:37:00Z, itime=2009-10-12T16:09:42Z, type=directory, uid=root, " + + "gid=rootr, objectid=4980cdb2b010109b04a44f7bb83f5f04ad354c638ae5, " + + "objname=e913e09366364e9ba384b8fead643d43, size=4096, nlink=1, policyname=default", + AtmosStorageHeaders.LISTABLE_META, "listablemeta1=listablefoo1, listablemeta2=listablefoo2")); + + public static final AtmosObject EXPECTED; + + static { + EXPECTED = Guice.createInjector().getInstance(AtmosObject.Factory.class) + .create(ParseSystemMetadataFromHeadersTest.EXPECTED, ParseUserMetadataFromHeadersTest.EXPECTED); + EXPECTED.getContentMetadata().setName("e913e09366364e9ba384b8fead643d43"); + EXPECTED.setPayload(RESPONSE.getPayload()); + } + + public void test() { + ParseObjectFromHeadersAndHttpContent parser = Guice.createInjector().getInstance( + ParseObjectFromHeadersAndHttpContent.class); + AtmosObject data = parser.apply(RESPONSE); + + assertEquals(data, EXPECTED); + } +} diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseSystemMetadataFromHeadersTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseSystemMetadataFromHeadersTest.java index 902c71c6bb..f1e4707a2e 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseSystemMetadataFromHeadersTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseSystemMetadataFromHeadersTest.java @@ -25,44 +25,35 @@ import org.jclouds.atmosonline.saas.domain.FileType; import org.jclouds.atmosonline.saas.domain.SystemMetadata; import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.DateService; -import org.jclouds.http.HttpResponse; -import org.jclouds.io.Payloads; +import org.jclouds.date.internal.SimpleDateFormatDateService; import org.testng.annotations.Test; import com.google.inject.Guice; -import com.google.inject.Injector; /** * Tests behavior of {@code ParseSystemMetadataFromHeaders} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "atmossaas.ParseSystemMetadataFromHeadersTest") +@Test(groups = "unit") public class ParseSystemMetadataFromHeadersTest { + static final DateService dateService = new SimpleDateFormatDateService(); + static final SystemMetadata EXPECTED = new SystemMetadata(CryptoStreams.hex("1f3870be274f6c49b3e31a0c6728957f"), + + dateService.iso8601SecondsDateParse("2009-10-12T16:09:42Z"), + dateService.iso8601SecondsDateParse("2009-10-19T04:37:00Z"), "rootr", + dateService.iso8601SecondsDateParse("2009-10-12T16:09:42Z"), + dateService.iso8601SecondsDateParse("2009-10-19T04:37:00Z"), 1, + "4980cdb2b010109b04a44f7bb83f5f04ad354c638ae5", "e913e09366364e9ba384b8fead643d43", "default", 4096l, + FileType.DIRECTORY, "root" + + ); public void test() { - Injector injector = Guice.createInjector(); - ParseSystemMetadataFromHeaders parser = injector.getInstance(ParseSystemMetadataFromHeaders.class); - DateService dateService = injector.getInstance(DateService.class); + ParseSystemMetadataFromHeaders parser = Guice.createInjector().getInstance(ParseSystemMetadataFromHeaders.class); - HttpResponse response = new HttpResponse(200, "ok", Payloads.newStringPayload("")); - response.getHeaders().put( - "x-emc-meta", - "content-md5=1f3870be274f6c49b3e31a0c6728957f, atime=2009-10-12T16:09:42Z, mtime=2009-10-19T04:37:00Z," - + " ctime=2009-10-19T04:37:00Z, itime=2009-10-12T16:09:42Z, type=directory, uid=root, " - + "gid=rootr, objectid=4980cdb2b010109b04a44f7bb83f5f04ad354c638ae5, " - + "objname=e913e09366364e9ba384b8fead643d43, size=4096, nlink=1, policyname=default"); - SystemMetadata expected = new SystemMetadata(CryptoStreams.hex("1f3870be274f6c49b3e31a0c6728957f"), + SystemMetadata data = parser.apply(ParseObjectFromHeadersAndHttpContentTest.RESPONSE); - dateService.iso8601SecondsDateParse("2009-10-12T16:09:42Z"), dateService - .iso8601SecondsDateParse("2009-10-19T04:37:00Z"), "rootr", dateService - .iso8601SecondsDateParse("2009-10-12T16:09:42Z"), dateService - .iso8601SecondsDateParse("2009-10-19T04:37:00Z"), 1, "4980cdb2b010109b04a44f7bb83f5f04ad354c638ae5", - "e913e09366364e9ba384b8fead643d43", "default", 4096l, FileType.DIRECTORY, "root" - - ); - SystemMetadata data = parser.apply(response); - - assertEquals(data, expected); + assertEquals(data, EXPECTED); } } diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeadersTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeadersTest.java new file mode 100644 index 0000000000..a6c04472b4 --- /dev/null +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ParseUserMetadataFromHeadersTest.java @@ -0,0 +1,48 @@ +/** + * + * 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.atmosonline.saas.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.atmosonline.saas.domain.UserMetadata; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Guice; + +/** + * Tests behavior of {@code ParseUserMetadataFromHeaders} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ParseUserMetadataFromHeadersTest { + static final UserMetadata EXPECTED = new UserMetadata(ImmutableMap. of("meta1", "foo1"), + ImmutableMap.of("listablemeta1", "listablefoo1", "listablemeta2", "listablefoo2"), ImmutableSet.of("tag1", + "tag2"), ImmutableSet.of("listabletag1", "listabletag2")); + + public void test() { + ParseUserMetadataFromHeaders parser = Guice.createInjector().getInstance(ParseUserMetadataFromHeaders.class); + UserMetadata data = parser.apply(ParseObjectFromHeadersAndHttpContentTest.RESPONSE); + + assertEquals(data, EXPECTED); + } +} diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExistsTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExistsTest.java new file mode 100644 index 0000000000..be2e93f32d --- /dev/null +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/functions/ReturnEndpointIfAlreadyExistsTest.java @@ -0,0 +1,38 @@ +package org.jclouds.atmosonline.saas.functions; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.blobstore.KeyAlreadyExistsException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ReturnEndpointIfAlreadyExistsTest { + + @Test + public void testFoundIsNullWhenEndpointNotSet() { + assertEquals(new ReturnEndpointIfAlreadyExists().apply(new KeyAlreadyExistsException()), null); + } + + @Test + public void testFoundIsEndpointWhenSet() { + assertEquals( + new ReturnEndpointIfAlreadyExists().setEndpoint(URI.create("foo")).apply(new KeyAlreadyExistsException()), + URI.create("foo")); + } + + @Test(expectedExceptions = RuntimeException.class) + public void testNotFoundPropagates() { + new ReturnEndpointIfAlreadyExists().apply(new RuntimeException()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + new ReturnEndpointIfAlreadyExists().apply(null); + } +} diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/options/ListOptionsTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/options/ListOptionsTest.java index 8c76d036d9..782ac6c3c4 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/options/ListOptionsTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/options/ListOptionsTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "emcsaas.ListOptionsTest") +@Test(groups = "unit") public class ListOptionsTest { public void testToken() { diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ErrorHandlerTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ErrorHandlerTest.java index e8098568f3..7939dae87e 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ErrorHandlerTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ErrorHandlerTest.java @@ -33,7 +33,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "atmossaas.ErrorHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ErrorHandlerTest") public class ErrorHandlerTest extends BaseHandlerTest { ParseSax createParser() { diff --git a/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandlerTest.java b/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandlerTest.java index 8ea68473d8..0a1ff56b07 100644 --- a/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandlerTest.java +++ b/atmos/src/test/java/org/jclouds/atmosonline/saas/xml/ListDirectoryResponseHandlerTest.java @@ -22,7 +22,7 @@ package org.jclouds.atmosonline.saas.xml; import static org.testng.Assert.assertEquals; import java.io.InputStream; -import java.util.SortedSet; +import java.util.Set; import org.jclouds.atmosonline.saas.domain.DirectoryEntry; import org.jclouds.atmosonline.saas.domain.FileType; @@ -37,24 +37,25 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "atmossaas.ListDirectoryResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ListDirectoryResponseHandlerTest") public class ListDirectoryResponseHandlerTest extends BaseHandlerTest { - ParseSax> createParser() { - ParseSax> parser = (ParseSax>) factory + ParseSax> createParser() { + ParseSax> parser = (ParseSax>) factory .create(injector.getInstance(ListDirectoryResponseHandler.class)); return parser; } public void testApplyInputStreamBase() { InputStream is = getClass().getResourceAsStream("/list_basic.xml"); - ParseSax> parser = createParser(); - SortedSet expected = Sets.newTreeSet(); + ParseSax> parser = createParser(); + Set expected = Sets.newTreeSet(); expected.add(new DirectoryEntry("4980cdb2a411106a04a4538c92a1b204ad92077de6e3", FileType.DIRECTORY, "adriancole-blobstore-2096685753")); expected.add(new DirectoryEntry("4980cdb2a410105404980d99e53a0504ad93939e7dc3", FileType.DIRECTORY, "adriancole-blobstore247496608")); - SortedSet result = parser.parse(is); + Set result = parser.parse(is); assertEquals(result, expected); } } diff --git a/aws/core/src/main/java/org/jclouds/aws/AWSResponseException.java b/aws/core/src/main/java/org/jclouds/aws/AWSResponseException.java index 9df80de290..ef52b2227f 100644 --- a/aws/core/src/main/java/org/jclouds/aws/AWSResponseException.java +++ b/aws/core/src/main/java/org/jclouds/aws/AWSResponseException.java @@ -40,7 +40,7 @@ public class AWSResponseException extends HttpResponseException { private AWSError error = new AWSError(); public AWSResponseException(HttpCommand command, HttpResponse response, AWSError error) { - super(String.format("request %s failed with code %s, error: %s", command.getRequest().getRequestLine(), response + super(String.format("request %s failed with code %s, error: %s", command.getCurrentRequest().getRequestLine(), response .getStatusCode(), error.toString()), command, response); this.setError(error); @@ -48,7 +48,7 @@ public class AWSResponseException extends HttpResponseException { public AWSResponseException(HttpCommand command, HttpResponse response, AWSError error, Throwable cause) { - super(String.format("request %1$s failed with error: %2$s", command.getRequest().getRequestLine(), error + super(String.format("request %1$s failed with error: %2$s", command.getCurrentRequest().getRequestLine(), error .toString()), command, response, cause); this.setError(error); diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParams.java index 737b788b02..25b5f0d33d 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParams.java @@ -22,47 +22,52 @@ package org.jclouds.aws.ec2.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; -import static org.jclouds.http.HttpUtils.addFormParamTo; import org.jclouds.aws.ec2.domain.BlockDeviceMapping; import org.jclouds.aws.ec2.domain.RunningInstance; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; + /** * @author Oleksiy Yarmula + * @author Adrian Cole */ public class BindBlockDeviceMappingToIndexedFormParams implements Binder { - private final String deviceNamePattern = "BlockDeviceMapping.%d.DeviceName"; - private final String volumeIdPattern = "BlockDeviceMapping.%d.Ebs.VolumeId"; - private final String deleteOnTerminationPattern = "BlockDeviceMapping.%d.Ebs.DeleteOnTermination"; + private static final String deviceNamePattern = "BlockDeviceMapping.%d.DeviceName"; + private static final String volumeIdPattern = "BlockDeviceMapping.%d.Ebs.VolumeId"; + private static final String deleteOnTerminationPattern = "BlockDeviceMapping.%d.Ebs.DeleteOnTermination"; - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof BlockDeviceMapping, - "this binder is only valid for BlockDeviceMapping"); + "this binder is only valid for BlockDeviceMapping"); BlockDeviceMapping blockDeviceMapping = (BlockDeviceMapping) input; + Builder builder = ImmutableMultimap. builder(); int amazonOneBasedIndex = 1; // according to docs, counters must start with 1 for (String ebsBlockDeviceName : blockDeviceMapping.getEbsBlockDevices().keySet()) { - for (RunningInstance.EbsBlockDevice ebsBlockDevice : blockDeviceMapping - .getEbsBlockDevices().get(ebsBlockDeviceName)) { + for (RunningInstance.EbsBlockDevice ebsBlockDevice : blockDeviceMapping.getEbsBlockDevices().get( + ebsBlockDeviceName)) { // not null by contract - addFormParamTo(request, format(volumeIdPattern, amazonOneBasedIndex), ebsBlockDevice - .getVolumeId()); + builder.put(format(volumeIdPattern, amazonOneBasedIndex), ebsBlockDevice.getVolumeId()); if (ebsBlockDeviceName != null) { - addFormParamTo(request, format(deviceNamePattern, amazonOneBasedIndex), - ebsBlockDeviceName); + builder.put(format(deviceNamePattern, amazonOneBasedIndex), ebsBlockDeviceName); } - addFormParamTo(request, format(deleteOnTerminationPattern, amazonOneBasedIndex), String - .valueOf(ebsBlockDevice.isDeleteOnTermination())); + builder.put(format(deleteOnTerminationPattern, amazonOneBasedIndex), + String.valueOf(ebsBlockDevice.isDeleteOnTermination())); amazonOneBasedIndex++; } } - + ImmutableMultimap forms = builder.build(); + return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms); } } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParams.java index 65e96496c9..87fe77b612 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParams.java @@ -33,9 +33,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindBundleIdsToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithPrefix(request, "BundleId", input); + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithPrefix(request, "BundleId", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindGroupNameToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParams.java similarity index 82% rename from aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindGroupNameToIndexedFormParams.java rename to aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParams.java index cb3b1e9c1c..732785c043 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindGroupNameToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParams.java @@ -32,10 +32,10 @@ import org.jclouds.rest.Binder; * @author Adrian Cole */ @Singleton -public class BindGroupNameToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithPrefix(request, "GroupName", input); +public class BindGroupNamesToIndexedFormParams implements Binder { + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithPrefix(request, "GroupName", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParams.java index 9595ee49fb..64e3b91241 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParams.java @@ -33,9 +33,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindInstanceIdsToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithPrefix(request, "InstanceId", input); + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithPrefix(request, "InstanceId", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindKeyNameToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParams.java similarity index 82% rename from aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindKeyNameToIndexedFormParams.java rename to aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParams.java index 7dddd3a2ef..ac9a6c2011 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindKeyNameToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParams.java @@ -32,10 +32,10 @@ import org.jclouds.rest.Binder; * @author Adrian Cole */ @Singleton -public class BindKeyNameToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithPrefix(request, "KeyName", input); +public class BindKeyNamesToIndexedFormParams implements Binder { + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithPrefix(request, "KeyName", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParams.java index 6d46109750..4495a0861e 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParams.java @@ -27,15 +27,15 @@ import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; /** - * Binds the String [] to form parameters named with ProductCode.index + * Binds the Iterable to form parameters named with ProductCode.index * * @author Adrian Cole */ @Singleton public class BindProductCodesToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexIterableToFormValuesWithPrefix(request, "ProductCode", input); + @Override + public R bindToRequest(R request, Object input) { + return indexIterableToFormValuesWithPrefix(request, "ProductCode", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParams.java index ab470f1a92..2cb6570687 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParams.java @@ -35,11 +35,11 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindPublicIpsToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - checkArgument(checkNotNull(input, "input") instanceof String[], - "this binder is only valid for String[] : " + input.getClass()); + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof String[], "this binder is only valid for String[] : " + + input.getClass()); String[] addressStrings = (String[]) input; - indexStringArrayToFormValuesWithPrefix(request, "PublicIp", addressStrings); + return indexStringArrayToFormValuesWithPrefix(request, "PublicIp", addressStrings); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignature.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignature.java index d6b25ad5e3..be6a4c5485 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignature.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignature.java @@ -20,18 +20,19 @@ package org.jclouds.aws.ec2.binders; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.http.HttpUtils.addFormParamTo; import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.aws.filters.FormSigner; -import org.jclouds.crypto.Crypto; import org.jclouds.crypto.CryptoStreams; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; /** * @@ -42,15 +43,18 @@ public class BindS3UploadPolicyAndSignature implements Binder { private final FormSigner signer; @Inject - BindS3UploadPolicyAndSignature(FormSigner signer, Crypto crypto) { + BindS3UploadPolicyAndSignature(FormSigner signer) { this.signer = signer; } - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { String encodedJson = CryptoStreams.base64(checkNotNull(input, "json").toString().getBytes(Charsets.UTF_8)); - addFormParamTo(request, "Storage.S3.UploadPolicy", encodedJson); + Builder builder = ImmutableMultimap. builder(); + builder.put("Storage.S3.UploadPolicy", encodedJson); String signature = signer.sign(encodedJson); - addFormParamTo(request, "Storage.S3.UploadPolicySignature", signature); + builder.put("Storage.S3.UploadPolicySignature", signature); + return ModifyRequest.putFormParams(request, builder.build()); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParams.java index a540c46610..a02af141f8 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParams.java @@ -37,19 +37,19 @@ import com.google.common.collect.Iterables; */ @Singleton public class BindUserGroupsToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - checkArgument(checkNotNull(input, "input") instanceof Iterable, - "this binder is only valid for Iterable: " + input.getClass()); + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof Iterable, "this binder is only valid for Iterable: " + + input.getClass()); checkValidUserGroup(input); - indexIterableToFormValuesWithPrefix(request, "UserGroup", input); + return indexIterableToFormValuesWithPrefix(request, "UserGroup", input); } private void checkValidUserGroup(Object input) { Iterable values = (Iterable) input; long size = Iterables.size(values); checkArgument(size == 0 || (size == 1 && Iterables.getOnlyElement(values).equals("all")), - "only supported UserGroup is 'all'"); + "only supported UserGroup is 'all'"); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParams.java index d751e5b36f..d80e0925d0 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParams.java @@ -21,14 +21,17 @@ package org.jclouds.aws.ec2.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.http.HttpUtils.addFormParamTo; import javax.inject.Singleton; import org.jclouds.aws.ec2.domain.UserIdGroupPair; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; + /** * Binds the String [] to query parameters named with GroupName.index * @@ -36,12 +39,15 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindUserIdGroupPairToSourceSecurityGroupFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof UserIdGroupPair, - "this binder is only valid for UserIdGroupPair!"); + "this binder is only valid for UserIdGroupPair!"); UserIdGroupPair pair = (UserIdGroupPair) input; - addFormParamTo(request, "SourceSecurityGroupOwnerId", pair.getUserId()); - addFormParamTo(request, "SourceSecurityGroupName", pair.getGroupName()); + Builder builder = ImmutableMultimap. builder(); + builder.put("SourceSecurityGroupOwnerId", pair.getUserId()); + builder.put("SourceSecurityGroupName", pair.getGroupName()); + return ModifyRequest.putFormParams(request, builder.build()); + } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParams.java index 7f47a8987b..e20283813d 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParams.java @@ -27,14 +27,15 @@ import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; /** - * Binds the String [] to form parameters named with UserId.index + * Binds the Iterable to form parameters named with UserId.index * * @author Adrian Cole */ @Singleton public class BindUserIdsToIndexedFormParams implements Binder { - public void bindToRequest(HttpRequest request, Object input) { - indexIterableToFormValuesWithPrefix(request, "UserId", input); + @Override + public R bindToRequest(R request, Object input) { + return indexIterableToFormValuesWithPrefix(request, "UserId", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParams.java index 28b6a70cdf..ac73d5b27e 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParams.java @@ -33,9 +33,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindVolumeIdsToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithPrefix(request, "VolumeId", input); + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithPrefix(request, "VolumeId", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParam.java b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParam.java index d60c979cbf..dd7fee8844 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParam.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParam.java @@ -20,11 +20,11 @@ package org.jclouds.aws.ec2.binders; import static com.google.common.base.Preconditions.checkArgument; -import static org.jclouds.http.HttpUtils.addFormParamTo; import javax.inject.Singleton; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; /** @@ -34,11 +34,13 @@ import org.jclouds.rest.Binder; */ @Singleton public class IfNotNullBindAvailabilityZoneToFormParam implements Binder { - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { if (input != null) { checkArgument(input instanceof String, "this binder is only valid for AvailabilityZone!"); - addFormParamTo(request, "Placement.AvailabilityZone", (String) input); + return ModifyRequest.addFormParam(request, "Placement.AvailabilityZone", (String) input); } + return request; } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java index 7a54ec7224..1fc4d5cb29 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java @@ -21,7 +21,6 @@ package org.jclouds.aws.ec2.compute; import static com.google.common.base.Preconditions.checkState; import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle; -import static org.jclouds.util.Utils.checkNotEmpty; import java.util.Map; import java.util.Map.Entry; @@ -62,6 +61,7 @@ import org.jclouds.compute.util.ComputeUtils; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.http.HttpResponseException; +import org.jclouds.util.Preconditions2; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; @@ -107,7 +107,7 @@ public class EC2ComputeService extends BaseComputeService { @VisibleForTesting void deletePlacementGroup(String region, String tag) { - checkNotEmpty(tag, "tag"); + Preconditions2.checkNotEmpty(tag, "tag"); String group = String.format("jclouds#%s#%s", tag, region); try { if (ec2Client.getPlacementGroupServices().describePlacementGroupsInRegion(region, group).size() > 0) { @@ -137,7 +137,7 @@ public class EC2ComputeService extends BaseComputeService { @VisibleForTesting void deleteSecurityGroup(String region, String tag) { - checkNotEmpty(tag, "tag"); + Preconditions2.checkNotEmpty(tag, "tag"); String group = String.format("jclouds#%s#%s", tag, region); if (ec2Client.getSecurityGroupServices().describeSecurityGroupsInRegion(region, group).size() > 0) { logger.debug(">> deleting securityGroup(%s)", group); diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java index c3a9daaf15..78b5d5c878 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java @@ -20,13 +20,12 @@ package org.jclouds.aws.ec2.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.nullSafeSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; -import java.util.Map.Entry; import javax.annotation.Resource; import javax.inject.Inject; @@ -49,6 +48,7 @@ import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; +import org.jclouds.util.NullSafeCollections; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; @@ -93,8 +93,8 @@ public class RunningInstanceToNodeMetadata implements Function groupIds) { checkArgument(Iterables.size(groupIds) > 0, "you must specify at least one security group"); for (String groupId : groupIds) - Utils.checkNotEmpty(groupId, "all security groups must be non-empty"); + Preconditions2.checkNotEmpty(groupId, "all security groups must be non-empty"); this.groupIds = ImmutableSet.copyOf(groupIds); return this; } @@ -112,7 +112,7 @@ public class EC2TemplateOptions extends TemplateOptions { public EC2TemplateOptions keyPair(String keyPair) { checkNotNull(keyPair, "use noKeyPair option to request boot without a keypair"); checkState(!noKeyPair, "you cannot specify both options keyPair and noKeyPair"); - Utils.checkNotEmpty(keyPair, "keypair must be non-empty"); + Preconditions2.checkNotEmpty(keyPair, "keypair must be non-empty"); this.keyPair = keyPair; return this; } @@ -132,7 +132,7 @@ public class EC2TemplateOptions extends TemplateOptions { public EC2TemplateOptions placementGroup(String placementGroup) { checkNotNull(placementGroup, "use noPlacementGroup option to request boot without a keypair"); checkState(!noPlacementGroup, "you cannot specify both options placementGroup and noPlacementGroup"); - Utils.checkNotEmpty(placementGroup, "placementGroup must be non-empty"); + Preconditions2.checkNotEmpty(placementGroup, "placementGroup must be non-empty"); this.placementGroup = placementGroup; return this; } @@ -151,7 +151,7 @@ public class EC2TemplateOptions extends TemplateOptions { */ public EC2TemplateOptions subnetId(String subnetId) { checkNotNull(subnetId, "subnetId cannot be null"); - Utils.checkNotEmpty(subnetId, "subnetId must be non-empty"); + Preconditions2.checkNotEmpty(subnetId, "subnetId must be non-empty"); this.subnetId = subnetId; return this; } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/functions/ReturnVoidOnVolumeAvailable.java b/aws/core/src/main/java/org/jclouds/aws/ec2/functions/ReturnVoidOnVolumeAvailable.java index 428da8452d..976d521b84 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/functions/ReturnVoidOnVolumeAvailable.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/functions/ReturnVoidOnVolumeAvailable.java @@ -19,7 +19,7 @@ package org.jclouds.aws.ec2.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/services/KeyPairAsyncClient.java b/aws/core/src/main/java/org/jclouds/aws/ec2/services/KeyPairAsyncClient.java index 5e30b71d28..c69c5baa45 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/services/KeyPairAsyncClient.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/services/KeyPairAsyncClient.java @@ -30,7 +30,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jclouds.aws.ec2.EC2AsyncClient; -import org.jclouds.aws.ec2.binders.BindKeyNameToIndexedFormParams; +import org.jclouds.aws.ec2.binders.BindKeyNamesToIndexedFormParams; import org.jclouds.aws.ec2.domain.KeyPair; import org.jclouds.aws.ec2.xml.DescribeKeyPairsResponseHandler; import org.jclouds.aws.ec2.xml.KeyPairResponseHandler; @@ -79,7 +79,7 @@ public interface KeyPairAsyncClient { @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) ListenableFuture> describeKeyPairsInRegion( @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, - @BinderParam(BindKeyNameToIndexedFormParams.class) String... keyPairNames); + @BinderParam(BindKeyNamesToIndexedFormParams.class) String... keyPairNames); /** * @see KeyPairClient#deleteKeyPairInRegion diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClient.java b/aws/core/src/main/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClient.java index 99e9243a28..5bd3df0fb4 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClient.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClient.java @@ -30,7 +30,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jclouds.aws.ec2.EC2AsyncClient; -import org.jclouds.aws.ec2.binders.BindGroupNameToIndexedFormParams; +import org.jclouds.aws.ec2.binders.BindGroupNamesToIndexedFormParams; import org.jclouds.aws.ec2.domain.PlacementGroup; import org.jclouds.aws.ec2.xml.DescribePlacementGroupsResponseHandler; import org.jclouds.aws.filters.FormSigner; @@ -97,6 +97,6 @@ public interface PlacementGroupAsyncClient { @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) ListenableFuture> describePlacementGroupsInRegion( @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, - @BinderParam(BindGroupNameToIndexedFormParams.class) String... placementGroupIds); + @BinderParam(BindGroupNamesToIndexedFormParams.class) String... placementGroupIds); } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClient.java b/aws/core/src/main/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClient.java index 7a264a09d7..81ee41bb82 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClient.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClient.java @@ -30,7 +30,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jclouds.aws.ec2.EC2AsyncClient; -import org.jclouds.aws.ec2.binders.BindGroupNameToIndexedFormParams; +import org.jclouds.aws.ec2.binders.BindGroupNamesToIndexedFormParams; import org.jclouds.aws.ec2.binders.BindUserIdGroupPairToSourceSecurityGroupFormParams; import org.jclouds.aws.ec2.domain.IpProtocol; import org.jclouds.aws.ec2.domain.SecurityGroup; @@ -91,7 +91,7 @@ public interface SecurityGroupAsyncClient { @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) ListenableFuture> describeSecurityGroupsInRegion( @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, - @BinderParam(BindGroupNameToIndexedFormParams.class) String... securityGroupNames); + @BinderParam(BindGroupNamesToIndexedFormParams.class) String... securityGroupNames); /** * @see SecurityGroupClient#authorizeSecurityGroupIngressInRegion(@Nullable Region, diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/util/EC2Utils.java b/aws/core/src/main/java/org/jclouds/aws/ec2/util/EC2Utils.java index bb33f4db1b..dcffbbbee0 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/util/EC2Utils.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/util/EC2Utils.java @@ -21,7 +21,6 @@ package org.jclouds.aws.ec2.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.http.HttpUtils.addFormParamTo; import java.util.HashSet; import java.util.Map; @@ -38,10 +37,13 @@ import org.jclouds.aws.ec2.services.InstanceClient; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.internal.GeneratedHttpRequest; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; import com.google.common.collect.Iterables; /** @@ -52,37 +54,35 @@ public class EC2Utils { @Singleton public static class GetRegionFromLocation implements Function { public String apply(Location location) { - String region = location.getScope() == LocationScope.REGION ? location.getId() : location - .getParent().getId(); + String region = location.getScope() == LocationScope.REGION ? location.getId() : location.getParent().getId(); return region; } } - - public static String[] getAvailabilityZonesForRegion(String region) - { - Set availabilityZones = new HashSet(); - for (String az : AvailabilityZone.zones) { - if (az.startsWith(region)) - availabilityZones.add(az); - } - - return (String[])availabilityZones.toArray(new String[availabilityZones.size()]); - } - public static void indexStringArrayToFormValuesWithPrefix(HttpRequest request, String prefix, - Object input) { - checkArgument(checkNotNull(input, "input") instanceof String[], - "this binder is only valid for String[] : " + input.getClass()); - String[] values = (String[]) input; - for (int i = 0; i < values.length; i++) { - addFormParamTo(request, prefix + "." + (i + 1), checkNotNull(values[i], prefix - .toLowerCase() - + "s[" + i + "]")); + public static String[] getAvailabilityZonesForRegion(String region) { + Set availabilityZones = new HashSet(); + for (String az : AvailabilityZone.zones) { + if (az.startsWith(region)) + availabilityZones.add(az); } + + return (String[]) availabilityZones.toArray(new String[availabilityZones.size()]); } - public static Iterable getAllRunningInstancesInRegion(InstanceClient client, - String region, String id) { + public static R indexStringArrayToFormValuesWithPrefix(R request, String prefix, Object input) { + checkArgument(checkNotNull(input, "input") instanceof String[], "this binder is only valid for String[] : " + + input.getClass()); + String[] values = (String[]) input; + Builder builder = ImmutableMultimap. builder(); + for (int i = 0; i < values.length; i++) { + builder.put(prefix + "." + (i + 1), checkNotNull(values[i], prefix.toLowerCase() + "s[" + i + "]")); + } + ImmutableMultimap forms = builder.build(); + return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms); + } + + public static Iterable getAllRunningInstancesInRegion(InstanceClient client, String region, + String id) { return Iterables.concat(client.describeInstancesInRegion(region, id)); } @@ -92,17 +92,17 @@ public class EC2Utils { return parts; } - public static void indexIterableToFormValuesWithPrefix(HttpRequest request, String prefix, - Object input) { - checkArgument(checkNotNull(input, "input") instanceof Iterable, - "this binder is only valid for Iterable: " + input.getClass()); + public static R indexIterableToFormValuesWithPrefix(R request, String prefix, Object input) { + checkArgument(checkNotNull(input, "input") instanceof Iterable, "this binder is only valid for Iterable: " + + input.getClass()); Iterable values = (Iterable) input; + Builder builder = ImmutableMultimap. builder(); int i = 0; for (Object o : values) { - addFormParamTo(request, prefix + "." + (i++ + 1), checkNotNull(o.toString(), prefix - .toLowerCase() - + "s[" + i + "]")); + builder.put(prefix + "." + (i++ + 1), checkNotNull(o.toString(), prefix.toLowerCase() + "s[" + i + "]")); } + ImmutableMultimap forms = builder.build(); + return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms); } public static String findRegionInArgsOrNull(GeneratedHttpRequest gRequest) { @@ -118,8 +118,8 @@ public class EC2Utils { public static boolean isRegion(String regionName) { return Region.EU_WEST_1.equals(regionName) || Region.US_WEST_1.equals(regionName) - || Region.US_EAST_1.equals(regionName) || Region.US_STANDARD.equals(regionName) - || Region.AP_SOUTHEAST_1.equals(regionName); + || Region.US_EAST_1.equals(regionName) || Region.US_STANDARD.equals(regionName) + || Region.AP_SOUTHEAST_1.equals(regionName); } public static String findAvailabilityZoneInArgsOrNull(GeneratedHttpRequest gRequest) { @@ -133,29 +133,28 @@ public class EC2Utils { return null; } - public static void indexStringArrayToFormValuesWithStringFormat(HttpRequest request, - String format, Object input) { - checkArgument(checkNotNull(input, "input") instanceof String[], - "this binder is only valid for String[] : " + input.getClass()); + public static R indexStringArrayToFormValuesWithStringFormat(R request, String format, + Object input) { + checkArgument(checkNotNull(input, "input") instanceof String[], "this binder is only valid for String[] : " + + input.getClass()); String[] values = (String[]) input; + Builder builder = ImmutableMultimap. builder(); for (int i = 0; i < values.length; i++) { - addFormParamTo(request, String.format(format, (i + 1)), checkNotNull(values[i], format - .toLowerCase() - + "s[" + i + "]")); + builder.put(String.format(format, (i + 1)), checkNotNull(values[i], format.toLowerCase() + "s[" + i + "]")); } + ImmutableMultimap forms = builder.build(); + return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms); } - private static final Pattern ELB_PATTERN = Pattern - .compile("([^.]+)-[^.]+\\.([^.]+)\\.elb\\.amazonaws\\.com"); + private static final Pattern ELB_PATTERN = Pattern.compile("([^.]+)-[^.]+\\.([^.]+)\\.elb\\.amazonaws\\.com"); public static Map getLoadBalancerNameAndRegionFromDnsName(String dnsName) { Matcher matcher = ELB_PATTERN.matcher(checkNotNull(dnsName, "dnsName")); - checkArgument(matcher.find(), "dnsName syntax is " + ELB_PATTERN + " didn't match: " - + dnsName); + checkArgument(matcher.find(), "dnsName syntax is " + ELB_PATTERN + " didn't match: " + dnsName); String loadBalancerName = matcher.group(1); String regionName = matcher.group(2); - checkArgument((isRegion(regionName)), String.format( - "Region (%s) parsed from (%s) is not a valid region", regionName, dnsName)); + checkArgument((isRegion(regionName)), + String.format("Region (%s) parsed from (%s) is not a valid region", regionName, dnsName)); return ImmutableMap. of(regionName, loadBalancerName); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindAvailabilityZonesToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindAvailabilityZonesToIndexedFormParams.java index 2ee7410a34..848b176e4f 100644 --- a/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindAvailabilityZonesToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindAvailabilityZonesToIndexedFormParams.java @@ -33,9 +33,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindAvailabilityZonesToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithStringFormat(request, "AvailabilityZones.member.%s", input); + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithStringFormat(request, "AvailabilityZones.member.%s", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindELBInstanceIdsToIndexedFormParams.java b/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindELBInstanceIdsToIndexedFormParams.java index e31b21930d..ee61ddc61b 100644 --- a/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindELBInstanceIdsToIndexedFormParams.java +++ b/aws/core/src/main/java/org/jclouds/aws/elb/binders/BindELBInstanceIdsToIndexedFormParams.java @@ -33,9 +33,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindELBInstanceIdsToIndexedFormParams implements Binder { - - public void bindToRequest(HttpRequest request, Object input) { - indexStringArrayToFormValuesWithStringFormat(request, "Instances.member.%s.InstanceId", input); + @Override + public R bindToRequest(R request, Object input) { + return indexStringArrayToFormValuesWithStringFormat(request, "Instances.member.%s.InstanceId", input); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/elb/xml/DescribeLoadBalancersResponseHandler.java b/aws/core/src/main/java/org/jclouds/aws/elb/xml/DescribeLoadBalancersResponseHandler.java index b24e5734c1..80aa2a8ba6 100644 --- a/aws/core/src/main/java/org/jclouds/aws/elb/xml/DescribeLoadBalancersResponseHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/elb/xml/DescribeLoadBalancersResponseHandler.java @@ -34,7 +34,6 @@ import org.jclouds.date.DateService; import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.ParseSax; import org.jclouds.logging.Logger; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.xml.sax.Attributes; import com.google.common.collect.Sets; diff --git a/aws/core/src/main/java/org/jclouds/aws/filters/FormSigner.java b/aws/core/src/main/java/org/jclouds/aws/filters/FormSigner.java index 15f17e0585..fb5a8bdc99 100755 --- a/aws/core/src/main/java/org/jclouds/aws/filters/FormSigner.java +++ b/aws/core/src/main/java/org/jclouds/aws/filters/FormSigner.java @@ -28,8 +28,6 @@ import static org.jclouds.aws.ec2.reference.EC2Parameters.SIGNATURE_METHOD; import static org.jclouds.aws.ec2.reference.EC2Parameters.SIGNATURE_VERSION; import static org.jclouds.aws.ec2.reference.EC2Parameters.TIMESTAMP; import static org.jclouds.aws.ec2.reference.EC2Parameters.VERSION; -import static org.jclouds.http.HttpUtils.makeQueryLine; -import static org.jclouds.http.HttpUtils.parseQueryToMap; import java.util.Arrays; import java.util.Comparator; @@ -52,10 +50,11 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpUtils; import org.jclouds.http.internal.SignatureWire; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.io.InputSuppliers; import org.jclouds.logging.Logger; import org.jclouds.rest.RequestSigner; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; @@ -73,7 +72,7 @@ import com.google.common.collect.Multimap; public class FormSigner implements HttpRequestFilter, RequestSigner { public static String[] mandatoryParametersForSignature = new String[] { ACTION, SIGNATURE_METHOD, SIGNATURE_VERSION, - VERSION }; + VERSION }; private final SignatureWire signatureWire; private final String accessKey; private final String secretKey; @@ -87,8 +86,8 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { @Inject public FormSigner(SignatureWire signatureWire, @Named(Constants.PROPERTY_IDENTITY) String accessKey, - @Named(Constants.PROPERTY_CREDENTIAL) String secretKey, @TimeStamp Provider dateService, - Crypto crypto, HttpUtils utils) { + @Named(Constants.PROPERTY_CREDENTIAL) String secretKey, @TimeStamp Provider dateService, + Crypto crypto, HttpUtils utils) { this.signatureWire = signatureWire; this.accessKey = accessKey; this.secretKey = secretKey; @@ -97,16 +96,18 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { this.utils = utils; } - public void filter(HttpRequest request) throws HttpException { + public HttpRequest filter(HttpRequest request) throws HttpException { checkNotNull(request.getFirstHeaderOrNull(HttpHeaders.HOST), "request is not ready to sign; host not present"); - Multimap decodedParams = parseQueryToMap(request.getPayload().getRawContent().toString()); + Multimap decodedParams = ModifyRequest.parseQueryToMap(request.getPayload().getRawContent() + .toString()); addSigningParams(decodedParams); validateParams(decodedParams); String stringToSign = createStringToSign(request, decodedParams); String signature = sign(stringToSign); addSignature(decodedParams, signature); - setPayload(request, decodedParams); + request = setPayload(request, decodedParams); utils.logRequest(signatureLog, request, "<<"); + return request; } String[] sortForSigning(String queryLine) { @@ -124,8 +125,8 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { return parts; } - void setPayload(HttpRequest request, Multimap decodedParams) { - request.setPayload(makeQueryLine(decodedParams, new Comparator>() { + HttpRequest setPayload(HttpRequest request, Multimap decodedParams) { + request.setPayload(ModifyRequest.makeQueryLine(decodedParams, new Comparator>() { public int compare(Entry o1, Entry o2) { if (o1.getKey().startsWith("Action") || o2.getKey().startsWith("AWSAccessKeyId")) return -1; @@ -135,6 +136,7 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { } })); request.getPayload().getContentMetadata().setContentType("application/x-www-form-urlencoded"); + return request; } @VisibleForTesting @@ -153,10 +155,10 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { public String sign(String stringToSign) { String signature; try { - signature = CryptoStreams.base64(CryptoStreams.mac(InputSuppliers.of(stringToSign), crypto - .hmacSHA256(secretKey.getBytes()))); + signature = CryptoStreams.base64(CryptoStreams.mac(InputSuppliers.of(stringToSign), + crypto.hmacSHA256(secretKey.getBytes()))); if (signatureWire.enabled()) - signatureWire.input(Utils.toInputStream(signature)); + signatureWire.input(Strings2.toInputStream(signature)); } catch (Exception e) { throw new HttpException("error signing request", e); } @@ -182,7 +184,7 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { @VisibleForTesting String buildCanonicalizedString(Multimap decodedParams) { - return makeQueryLine(decodedParams, new Comparator>() { + return ModifyRequest.makeQueryLine(decodedParams, new Comparator>() { public int compare(Map.Entry o1, Map.Entry o2) { if (o1.getKey().startsWith("AWSAccessKeyId")) return -1; @@ -201,7 +203,7 @@ public class FormSigner implements HttpRequestFilter, RequestSigner { } public String createStringToSign(HttpRequest input) { - return createStringToSign(input, parseQueryToMap(input.getPayload().getRawContent().toString())); + return createStringToSign(input, ModifyRequest.parseQueryToMap(input.getPayload().getRawContent().toString())); } } diff --git a/aws/core/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java b/aws/core/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java index f1ee23989d..dfeda7e118 100755 --- a/aws/core/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java @@ -64,7 +64,7 @@ public class AWSClientErrorRetryHandler implements HttpRetryHandler { // Content can be null in the case of HEAD requests if (response.getPayload() != null) { closeClientButKeepContentStream(response); - AWSError error = utils.parseAWSErrorFromContent(command.getRequest(), response); + AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response); if (error != null && ("RequestTimeout".equals(error.getCode()) || "OperationAborted".equals(error.getCode()) || "SignatureDoesNotMatch" diff --git a/aws/core/src/main/java/org/jclouds/aws/handlers/AWSRedirectionRetryHandler.java b/aws/core/src/main/java/org/jclouds/aws/handlers/AWSRedirectionRetryHandler.java index e6b8ddde5e..8b81fa9658 100755 --- a/aws/core/src/main/java/org/jclouds/aws/handlers/AWSRedirectionRetryHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/handlers/AWSRedirectionRetryHandler.java @@ -19,8 +19,6 @@ package org.jclouds.aws.handlers; -import static org.jclouds.http.HttpUtils.changeSchemeHostAndPortTo; -import static org.jclouds.http.HttpUtils.changeToGETRequest; import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream; import javax.inject.Inject; @@ -48,7 +46,7 @@ public class AWSRedirectionRetryHandler extends RedirectionRetryHandler { @Inject public AWSRedirectionRetryHandler(Provider uriBuilderProvider, - BackoffLimitedRetryHandler backoffHandler, AWSUtils utils) { + BackoffLimitedRetryHandler backoffHandler, AWSUtils utils) { super(uriBuilderProvider, backoffHandler); this.utils = utils; } @@ -56,24 +54,24 @@ public class AWSRedirectionRetryHandler extends RedirectionRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (response.getFirstHeaderOrNull(HttpHeaders.LOCATION) == null - && (response.getStatusCode() == 301 || response.getStatusCode() == 307)) { - if (command.getRequest().getMethod() == HttpMethod.HEAD) { - changeToGETRequest(command.getRequest()); + && (response.getStatusCode() == 301 || response.getStatusCode() == 307)) { + if (command.getCurrentRequest().getMethod() == HttpMethod.HEAD) { + command.setCurrentRequest(command.getCurrentRequest().toBuilder().method("GET").build()); return true; } else { command.incrementRedirectCount(); closeClientButKeepContentStream(response); - AWSError error = utils.parseAWSErrorFromContent(command.getRequest(), response); + AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response); String host = error.getDetails().get("Endpoint"); if (host != null) { - if (host.equals(command.getRequest().getEndpoint().getHost())) { + if (host.equals(command.getCurrentRequest().getEndpoint().getHost())) { // must be an amazon error related to // http://developer.amazonwebservices.com/connect/thread.jspa?messageID=72287𑩟 return backoffHandler.shouldRetryRequest(command, response); } else { - changeSchemeHostAndPortTo(command.getRequest(), command.getRequest() - .getEndpoint().getScheme(), host, command.getRequest().getEndpoint() - .getPort(), uriBuilderProvider.get()); + UriBuilder builder = uriBuilderProvider.get().uri(command.getCurrentRequest().getEndpoint()); + builder.host(host); + command.setCurrentRequest(command.getCurrentRequest().toBuilder().endpoint(builder.build()).build()); } return true; } else { 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 e005f16c3c..ec6b39862b 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 @@ -27,7 +27,6 @@ import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; -import org.jclouds.aws.AWSResponseException; import org.jclouds.aws.domain.AWSError; import org.jclouds.aws.util.AWSUtils; import org.jclouds.blobstore.ContainerNotFoundException; @@ -40,7 +39,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; @@ -65,7 +64,7 @@ public class ParseAWSErrorFromXmlContent implements HttpErrorHandler { } public void handleError(HttpCommand command, HttpResponse response) { - HttpRequest request = command.getRequest(); + HttpRequest request = command.getCurrentRequest(); Exception exception = new HttpResponseException(command, response); try { AWSError error = null; @@ -80,7 +79,7 @@ public class ParseAWSErrorFromXmlContent implements HttpErrorHandler { } } else { try { - message = Utils.toStringAndClose(response.getPayload().getInput()); + message = Strings2.toStringAndClose(response.getPayload().getInput()); exception = new HttpResponseException(command, response, message); } catch (IOException e) { } @@ -109,7 +108,7 @@ public class ParseAWSErrorFromXmlContent implements HttpErrorHandler { exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { String container = request.getEndpoint().getHost(); String key = request.getEndpoint().getPath(); if (key == null || key.equals("/")) diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/S3AsyncClient.java b/aws/core/src/main/java/org/jclouds/aws/s3/S3AsyncClient.java index b20ecbcd5f..586f35af9b 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/S3AsyncClient.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/S3AsyncClient.java @@ -39,7 +39,7 @@ import org.jclouds.aws.s3.binders.BindAsHostPrefixIfConfigured; import org.jclouds.aws.s3.binders.BindBucketLoggingToXmlPayload; import org.jclouds.aws.s3.binders.BindNoBucketLoggingToXmlPayload; import org.jclouds.aws.s3.binders.BindPayerToXmlPayload; -import org.jclouds.aws.s3.binders.BindS3ObjectToPayload; +import org.jclouds.aws.s3.binders.BindS3ObjectMetadataToRequest; import org.jclouds.aws.s3.domain.AccessControlList; import org.jclouds.aws.s3.domain.BucketLogging; import org.jclouds.aws.s3.domain.BucketMetadata; @@ -162,7 +162,7 @@ public interface S3AsyncClient { @ResponseParser(ParseETagHeader.class) ListenableFuture putObject( @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") @ParamParser(ObjectKey.class) @BinderParam(BindS3ObjectToPayload.class) S3Object object, + @PathParam("key") @ParamParser(ObjectKey.class) @BinderParam(BindS3ObjectMetadataToRequest.class) S3Object object, PutObjectOptions... options); /** diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindACLToXMLPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindACLToXMLPayload.java index ae6fe4b670..dfb3d06d1d 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindACLToXMLPayload.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindACLToXMLPayload.java @@ -44,8 +44,8 @@ import com.jamesmurty.utils.XMLBuilder; */ @Singleton public class BindACLToXMLPayload implements Binder { - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { AccessControlList from = (AccessControlList) payload; Properties outputProperties = new Properties(); outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); @@ -57,12 +57,13 @@ public class BindACLToXMLPayload implements Binder { Throwables.propagateIfPossible(e); throw new RuntimeException("error transforming acl: " + from, e); } + return request; } protected XMLBuilder generateBuilder(AccessControlList acl) throws ParserConfigurationException, - FactoryConfigurationError { + FactoryConfigurationError { XMLBuilder rootBuilder = XMLBuilder.create("AccessControlPolicy").attr("xmlns", - S3Constants.S3_REST_API_XML_NAMESPACE); + S3Constants.S3_REST_API_XML_NAMESPACE); if (acl.getOwner() != null) { XMLBuilder ownerBuilder = rootBuilder.elem("Owner"); ownerBuilder.elem("ID").text(acl.getOwner().getId()).up(); @@ -74,21 +75,19 @@ public class BindACLToXMLPayload implements Binder { for (Grant grant : acl.getGrants()) { XMLBuilder grantBuilder = grantsBuilder.elem("Grant"); XMLBuilder granteeBuilder = grantBuilder.elem("Grantee").attr("xmlns:xsi", - "http://www.w3.org/2001/XMLSchema-instance"); + "http://www.w3.org/2001/XMLSchema-instance"); if (grant.getGrantee() instanceof GroupGrantee) { - granteeBuilder.attr("xsi:type", "Group").elem("URI").text( - grant.getGrantee().getIdentifier()); + granteeBuilder.attr("xsi:type", "Group").elem("URI").text(grant.getGrantee().getIdentifier()); } else if (grant.getGrantee() instanceof CanonicalUserGrantee) { CanonicalUserGrantee grantee = (CanonicalUserGrantee) grant.getGrantee(); - granteeBuilder.attr("xsi:type", "CanonicalUser").elem("ID").text( - grantee.getIdentifier()).up(); + granteeBuilder.attr("xsi:type", "CanonicalUser").elem("ID").text(grantee.getIdentifier()).up(); if (grantee.getDisplayName() != null) { granteeBuilder.elem("DisplayName").text(grantee.getDisplayName()); } } else if (grant.getGrantee() instanceof EmailAddressGrantee) { - granteeBuilder.attr("xsi:type", "AmazonCustomerByEmail").elem("EmailAddress").text( - grant.getGrantee().getIdentifier()); + granteeBuilder.attr("xsi:type", "AmazonCustomerByEmail").elem("EmailAddress") + .text(grant.getGrantee().getIdentifier()); } grantBuilder.elem("Permission").text(grant.getPermission().toString()); } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfigured.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfigured.java index 8d5a4e3324..39c6c4caac 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfigured.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfigured.java @@ -21,7 +21,6 @@ package org.jclouds.aws.s3.binders; import static org.jclouds.aws.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH; import static org.jclouds.aws.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS; -import static org.jclouds.http.HttpUtils.urlEncode; import javax.inject.Inject; import javax.inject.Named; @@ -32,11 +31,12 @@ import javax.ws.rs.core.UriBuilder; import org.jclouds.aws.s3.S3AsyncClient; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.binders.BindAsHostPrefix; +import org.jclouds.util.Strings2; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; /** @@ -53,30 +53,31 @@ public class BindAsHostPrefixIfConfigured implements Binder { @Inject public BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix, - @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, - @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, - Provider uriBuilderProvider) { + @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, + @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, Provider uriBuilderProvider) { this.bindAsHostPrefix = bindAsHostPrefix; this.isVhostStyle = isVhostStyle; this.servicePath = servicePath; this.uriBuilderProvider = uriBuilderProvider; } - public void bindToRequest(HttpRequest request, Object payload) { + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Object payload) { if (isVhostStyle) { - bindAsHostPrefix.bindToRequest(request, payload); - request.getHeaders().replaceValues(HttpHeaders.HOST, - ImmutableSet.of(request.getEndpoint().getHost())); + request = bindAsHostPrefix.bindToRequest(request, payload); + return ModifyRequest.replaceHeader(request, HttpHeaders.HOST, request.getEndpoint().getHost()); } else { UriBuilder builder = uriBuilderProvider.get().uri(request.getEndpoint()); - StringBuilder path = new StringBuilder(urlEncode(request.getEndpoint().getPath(), - S3AsyncClient.class.getAnnotation(SkipEncoding.class).value())); + StringBuilder path = new StringBuilder(Strings2.urlEncode(request.getEndpoint().getPath(), S3AsyncClient.class + .getAnnotation(SkipEncoding.class).value())); int indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payload.toString()); builder.replacePath(path.toString()); - request.setEndpoint(builder.buildFromEncodedMap(Maps. newHashMap())); + return (R) request.toBuilder().endpoint(builder.buildFromEncodedMap(Maps. newLinkedHashMap())) + .build(); } } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayload.java index c00f16c1c3..ea387aa239 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayload.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayload.java @@ -44,8 +44,8 @@ import com.jamesmurty.utils.XMLBuilder; */ @Singleton public class BindBucketLoggingToXmlPayload implements Binder { - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { BucketLogging from = (BucketLogging) payload; Properties outputProperties = new Properties(); outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); @@ -57,33 +57,32 @@ public class BindBucketLoggingToXmlPayload implements Binder { Throwables.propagateIfPossible(e); throw new RuntimeException("error transforming bucketLogging: " + from, e); } + return request; } - protected XMLBuilder generateBuilder(BucketLogging bucketLogging) - throws ParserConfigurationException, FactoryConfigurationError { - XMLBuilder rootBuilder = XMLBuilder.create("BucketLoggingStatus").attr("xmlns", - S3Constants.S3_REST_API_XML_NAMESPACE).e("LoggingEnabled"); + protected XMLBuilder generateBuilder(BucketLogging bucketLogging) throws ParserConfigurationException, + FactoryConfigurationError { + XMLBuilder rootBuilder = XMLBuilder.create("BucketLoggingStatus") + .attr("xmlns", S3Constants.S3_REST_API_XML_NAMESPACE).e("LoggingEnabled"); rootBuilder.e("TargetBucket").t(bucketLogging.getTargetBucket()); rootBuilder.e("TargetPrefix").t(bucketLogging.getTargetPrefix()); XMLBuilder grantsBuilder = rootBuilder.elem("TargetGrants"); for (Grant grant : bucketLogging.getTargetGrants()) { XMLBuilder grantBuilder = grantsBuilder.elem("Grant"); XMLBuilder granteeBuilder = grantBuilder.elem("Grantee").attr("xmlns:xsi", - "http://www.w3.org/2001/XMLSchema-instance"); + "http://www.w3.org/2001/XMLSchema-instance"); if (grant.getGrantee() instanceof GroupGrantee) { - granteeBuilder.attr("xsi:type", "Group").elem("URI").text( - grant.getGrantee().getIdentifier()); + granteeBuilder.attr("xsi:type", "Group").elem("URI").text(grant.getGrantee().getIdentifier()); } else if (grant.getGrantee() instanceof CanonicalUserGrantee) { CanonicalUserGrantee grantee = (CanonicalUserGrantee) grant.getGrantee(); - granteeBuilder.attr("xsi:type", "CanonicalUser").elem("ID").text( - grantee.getIdentifier()).up(); + granteeBuilder.attr("xsi:type", "CanonicalUser").elem("ID").text(grantee.getIdentifier()).up(); if (grantee.getDisplayName() != null) { granteeBuilder.elem("DisplayName").text(grantee.getDisplayName()); } } else if (grant.getGrantee() instanceof EmailAddressGrantee) { - granteeBuilder.attr("xsi:type", "AmazonCustomerByEmail").elem("EmailAddress").text( - grant.getGrantee().getIdentifier()); + granteeBuilder.attr("xsi:type", "AmazonCustomerByEmail").elem("EmailAddress") + .text(grant.getGrantee().getIdentifier()); } grantBuilder.elem("Permission").text(grant.getPermission().toString()); } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayload.java index adbc59edf0..db43c9e0db 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayload.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayload.java @@ -38,10 +38,12 @@ public class BindNoBucketLoggingToXmlPayload implements Binder { this.bindAsHostPrefixIfConfigured = bindAsHostPrefixIfConfigured; } - public void bindToRequest(HttpRequest request, Object payload) { - bindAsHostPrefixIfConfigured.bindToRequest(request, payload); + @Override + public R bindToRequest(R request, Object payload) { + request = bindAsHostPrefixIfConfigured.bindToRequest(request, payload); String stringPayload = ""; request.setPayload(stringPayload); + return request; } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindPayerToXmlPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindPayerToXmlPayload.java index d588024b5a..3f0e8c37bd 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindPayerToXmlPayload.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindPayerToXmlPayload.java @@ -36,15 +36,15 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindPayerToXmlPayload implements Binder { - - public void bindToRequest(HttpRequest request, Object toBind) { - checkArgument(checkNotNull(toBind, "toBind") instanceof Payer, - "this binder is only valid for Payer!"); + @Override + public R bindToRequest(R request, Object toBind) { + checkArgument(checkNotNull(toBind, "toBind") instanceof Payer, "this binder is only valid for Payer!"); String text = String - .format( - "%s", - ((Payer) toBind).value()); + .format( + "%s", + ((Payer) toBind).value()); request.setPayload(text); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML); + return request; } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequest.java similarity index 58% rename from aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java rename to aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequest.java index 2cd7a11f4d..f844144542 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequest.java @@ -20,6 +20,7 @@ package org.jclouds.aws.s3.binders; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; import javax.inject.Singleton; @@ -29,6 +30,7 @@ import org.jclouds.aws.s3.blobstore.functions.ObjectToBlob; import org.jclouds.aws.s3.domain.S3Object; import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; /** @@ -36,27 +38,33 @@ import org.jclouds.rest.Binder; * @author Adrian Cole */ @Singleton -public class BindS3ObjectToPayload implements Binder { +public class BindS3ObjectMetadataToRequest implements Binder { private final BindUserMetadataToHeadersWithPrefix blobBinder; private final ObjectToBlob object2Blob; @Inject - public BindS3ObjectToPayload(ObjectToBlob object2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { - this.blobBinder = blobBinder; - this.object2Blob = object2Blob; + public BindS3ObjectMetadataToRequest(ObjectToBlob object2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { + this.blobBinder = checkNotNull(blobBinder, "blobBinder"); + this.object2Blob = checkNotNull(object2Blob, "object2Blob"); } - public void bindToRequest(HttpRequest request, Object payload) { - S3Object s3Object = (S3Object) payload; + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!"); + checkNotNull(request, "request"); + + S3Object s3Object = S3Object.class.cast(input); + checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, - "contentLength must be set, streaming not supported"); + "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5l * 1024 * 1024 * 1024, - "maximum size for put object is 5GB"); - blobBinder.bindToRequest(request, object2Blob.apply(s3Object)); + "maximum size for put object is 5GB"); + request = blobBinder.bindToRequest(request, object2Blob.apply(s3Object)); if (s3Object.getMetadata().getCacheControl() != null) { - request.getHeaders().put(HttpHeaders.CACHE_CONTROL, s3Object.getMetadata().getCacheControl()); + request = ModifyRequest.replaceHeader(request, HttpHeaders.CACHE_CONTROL, s3Object.getMetadata() + .getCacheControl()); } - + return request; } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java index 369eeaf758..6743110ee9 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java @@ -52,7 +52,7 @@ import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; -import org.jclouds.util.Utils; +import org.jclouds.util.Assertions; import com.google.common.base.Function; import com.google.common.base.Supplier; @@ -160,7 +160,7 @@ public class S3BlobStore extends BaseBlobStore { */ public void clearAndDeleteContainer(final String container) { try { - if (!Utils.eventuallyTrue(new Supplier() { + if (!Assertions.eventuallyTrue(new Supplier() { public Boolean get() { clearContainer(container); return sync.deleteBucketIfEmpty(container); diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java index 771d3fbc2f..446a174181 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java @@ -32,10 +32,10 @@ import com.google.inject.TypeLiteral; */ public class ScaleUpCloudBlobStoreContextModule extends S3BlobStoreContextModule { - @SuppressWarnings("rawtypes") + @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void bindBucketLocationStrategy() { bind(new TypeLiteral>() { - }).toInstance((Function)Functions.constant(null)); + }).toInstance((Function) Functions.constant(null)); } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignature.java b/aws/core/src/main/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignature.java index 58329ea6d5..053f704af2 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignature.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignature.java @@ -31,7 +31,6 @@ import static org.jclouds.util.Patterns.NEWLINE_PATTERN; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Set; import java.util.TreeSet; @@ -52,16 +51,20 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpUtils; import org.jclouds.http.internal.SignatureWire; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.io.InputSuppliers; import org.jclouds.logging.Logger; import org.jclouds.rest.RequestSigner; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; +import com.google.common.collect.Multimaps; /** * Signs the S3 request. @@ -75,7 +78,7 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign private final String[] firstHeadersToSign = new String[] { HttpHeaders.DATE }; public static Set SPECIAL_QUERIES = ImmutableSet.of("acl", "torrent", "logging", "location", - "requestPayment"); + "requestPayment"); private final SignatureWire signatureWire; private final String accessKey; private final String secretKey; @@ -94,10 +97,10 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign @Inject public RequestAuthorizeSignature(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag, - @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, - @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag, - @Named(PROPERTY_IDENTITY) String accessKey, @Named(PROPERTY_CREDENTIAL) String secretKey, - @TimeStamp Provider timeStampProvider, Crypto crypto, HttpUtils utils) { + @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, + @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag, + @Named(PROPERTY_IDENTITY) String accessKey, @Named(PROPERTY_CREDENTIAL) String secretKey, + @TimeStamp Provider timeStampProvider, Crypto crypto, HttpUtils utils) { this.isVhostStyle = isVhostStyle; this.servicePath = servicePath; this.headerTag = headerTag; @@ -110,11 +113,26 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign this.utils = utils; } - public void filter(HttpRequest request) throws HttpException { - replaceDateHeader(request); - String toSign = createStringToSign(request); - calculateAndReplaceAuthHeader(request, toSign); + public HttpRequest filter(HttpRequest request) throws HttpException { + request = replaceDateHeader(request); + String signature = calculateSignature(createStringToSign(request)); + request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); + return request; + } + + HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) { + request = ModifyRequest.replaceHeader(request, HttpHeaders.AUTHORIZATION, authTag + " " + accessKey + ":" + + signature); + return request; + } + + HttpRequest replaceDateHeader(HttpRequest request) { + Builder builder = ImmutableMap.builder(); + String date = timeStampProvider.get(); + builder.put(HttpHeaders.DATE, date); + request = ModifyRequest.replaceHeaders(request, Multimaps.forMap(builder.build())); + return request; } public String createStringToSign(HttpRequest request) { @@ -133,19 +151,18 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign return buffer.toString(); } - void calculateAndReplaceAuthHeader(HttpRequest request, String toSign) throws HttpException { + String calculateSignature(String toSign) throws HttpException { String signature = sign(toSign); if (signatureWire.enabled()) - signatureWire.input(Utils.toInputStream(signature)); - request.getHeaders().replaceValues(HttpHeaders.AUTHORIZATION, - Collections.singletonList(authTag + " " + accessKey + ":" + signature)); + signatureWire.input(Strings2.toInputStream(signature)); + return signature; } public String sign(String toSign) { String signature; try { - signature = CryptoStreams.base64(CryptoStreams.mac(InputSuppliers.of(toSign), crypto.hmacSHA1(secretKey - .getBytes()))); + signature = CryptoStreams.base64(CryptoStreams.mac(InputSuppliers.of(toSign), + crypto.hmacSHA1(secretKey.getBytes()))); } catch (Exception e) { throw new HttpException("error signing request", e); } @@ -156,17 +173,13 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign toSign.append(request.getMethod()).append("\n"); } - void replaceDateHeader(HttpRequest request) { - request.getHeaders().replaceValues(HttpHeaders.DATE, Collections.singletonList(timeStampProvider.get())); - } - void appendAmzHeaders(HttpRequest request, StringBuilder toSign) { Set headers = new TreeSet(request.getHeaders().keySet()); for (String header : headers) { if (header.startsWith("x-" + headerTag + "-")) { toSign.append(header.toLowerCase()).append(":"); for (String value : request.getHeaders().get(header)) { - toSign.append(Utils.replaceAll(value, NEWLINE_PATTERN, "")).append(","); + toSign.append(Strings2.replaceAll(value, NEWLINE_PATTERN, "")).append(","); } toSign.deleteCharAt(toSign.lastIndexOf(",")); toSign.append("\n"); @@ -176,11 +189,11 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) { buffer.append( - utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() - .getContentMD5())).append("\n"); + utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() + .getContentMD5())).append("\n"); buffer.append( - utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() - .getContentType())).append("\n"); + utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() + .getContentType())).append("\n"); } void appendHttpHeaders(HttpRequest request, StringBuilder toSign) { @@ -197,12 +210,12 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign for (int i = 0; i < request.getJavaMethod().getParameterAnnotations().length; i++) { if (Iterables.any(Arrays.asList(request.getJavaMethod().getParameterAnnotations()[i]), - new Predicate() { - public boolean apply(Annotation input) { - return input.annotationType().equals(Bucket.class); - } - })) { - bucketName = (String) request.getArgs()[i]; + new Predicate() { + public boolean apply(Annotation input) { + return input.annotationType().equals(Bucket.class); + } + })) { + bucketName = (String) request.getArgs().get(i); break; } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/functions/BindRegionToXmlPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/functions/BindRegionToXmlPayload.java index 0641e9eba8..cad73875d6 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/functions/BindRegionToXmlPayload.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/functions/BindRegionToXmlPayload.java @@ -55,20 +55,20 @@ public class BindRegionToXmlPayload extends BindToStringPayload { @Inject BindRegionToXmlPayload(@Named(PROPERTY_DEFAULT_REGIONS) String defaultRegions, - @Named(PROPERTY_REGIONS) String regions) { + @Named(PROPERTY_REGIONS) String regions) { this.defaultRegions = Splitter.on(',').split(defaultRegions); this.regions = Splitter.on(',').split(regions); } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { input = input == null ? Iterables.get(defaultRegions, 0) : input; checkArgument(input instanceof String, "this binder is only valid for Region!"); String constraint = (String) input; String value = null; if (Iterables.contains(defaultRegions, constraint)) { // nothing to bind as this is default. - return; + return request; } else if (Iterables.contains(regions, constraint)) { value = constraint; } else { @@ -79,10 +79,12 @@ public class BindRegionToXmlPayload extends BindToStringPayload { value = constraint; } } - String payload = String.format( - "%s", - value); - super.bindToRequest(request, payload); + String payload = String + .format( + "%s", + value); + request = super.bindToRequest(request, payload); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML); + return request; } } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectFromHeadersAndHttpContent.java b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectFromHeadersAndHttpContent.java index 8989aa0091..96e55dc66a 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectFromHeadersAndHttpContent.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectFromHeadersAndHttpContent.java @@ -35,14 +35,15 @@ import com.google.common.base.Function; * @see ParseMetadataFromHeaders * @author Adrian Cole */ -public class ParseObjectFromHeadersAndHttpContent implements Function, InvocationContext { +public class ParseObjectFromHeadersAndHttpContent implements Function, + InvocationContext { private final ParseObjectMetadataFromHeaders metadataParser; private final S3Object.Factory objectProvider; @Inject public ParseObjectFromHeadersAndHttpContent(ParseObjectMetadataFromHeaders metadataParser, - S3Object.Factory objectProvider) { + S3Object.Factory objectProvider) { this.metadataParser = metadataParser; this.objectProvider = objectProvider; } diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeaders.java b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeaders.java index 883241babd..035ad1d832 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeaders.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeaders.java @@ -44,14 +44,15 @@ import com.google.common.base.Function; * @see * @author Adrian Cole */ -public class ParseObjectMetadataFromHeaders implements Function, InvocationContext { +public class ParseObjectMetadataFromHeaders implements Function, + InvocationContext { private final ParseSystemAndUserMetadataFromHeaders blobMetadataParser; private final BlobToObjectMetadata blobToObjectMetadata; private final String userMdPrefix; @Inject public ParseObjectMetadataFromHeaders(ParseSystemAndUserMetadataFromHeaders blobMetadataParser, - BlobToObjectMetadata blobToObjectMetadata, @Named(PROPERTY_USER_METADATA_PREFIX) String userMdPrefix) { + BlobToObjectMetadata blobToObjectMetadata, @Named(PROPERTY_USER_METADATA_PREFIX) String userMdPrefix) { this.blobMetadataParser = blobMetadataParser; this.blobToObjectMetadata = blobToObjectMetadata; this.userMdPrefix = userMdPrefix; diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java index a9512fd53e..dff7fc4aec 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java @@ -23,7 +23,7 @@ import static com.google.common.base.Throwables.getCausalChain; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.size; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.util.List; diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnTrueOn404OrNotFoundFalseIfNotEmpty.java b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnTrueOn404OrNotFoundFalseIfNotEmpty.java index 257ef8b419..d76b97694e 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnTrueOn404OrNotFoundFalseIfNotEmpty.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnTrueOn404OrNotFoundFalseIfNotEmpty.java @@ -25,7 +25,7 @@ import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.size; import static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.util.List; diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/xml/ListBucketHandler.java b/aws/core/src/main/java/org/jclouds/aws/s3/xml/ListBucketHandler.java index 2dde94a309..c5e344fee8 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/xml/ListBucketHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/xml/ListBucketHandler.java @@ -33,7 +33,7 @@ import org.jclouds.aws.s3.domain.internal.ListBucketResponseImpl; import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.DateService; import org.jclouds.http.functions.ParseSax; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.xml.sax.Attributes; import com.google.common.collect.Sets; @@ -101,7 +101,7 @@ public class ListBucketHandler extends ParseSax.HandlerWithResult entry : credentialsMap.entrySet()) { Credentials credentials = computeContext.credentialStore().get(entry.getKey()); - assertEquals(Utils.toStringAndClose(entry.getValue()), String.format( + assertEquals(Strings2.toStringAndClose(entry.getValue()), String.format( "{\"identity\":\"%s\",\"credential\":\"%s\"}", credentials.identity, credentials.credential)); } } diff --git a/aws/core/src/test/java/org/jclouds/aws/ProvidersInPropertiesTest.java b/aws/core/src/test/java/org/jclouds/aws/ProvidersInPropertiesTest.java index 08f7cef0c1..d8887cf3cf 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ProvidersInPropertiesTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ProvidersInPropertiesTest.java @@ -21,7 +21,7 @@ package org.jclouds.aws; import org.jclouds.blobstore.util.BlobStoreUtils; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -49,7 +49,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "sqs") : providers; assert Iterables.contains(providers, "elb") : providers; assert Iterables.contains(providers, "s3") : providers; diff --git a/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchAsyncClientTest.java index 545edf3847..24f9dee445 100644 --- a/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchAsyncClientTest.java @@ -51,7 +51,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudwatch.MonitoringAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CloudWatchAsyncClientTest") public class CloudWatchAsyncClientTest extends RestClientTest { public void testRegisterInstancesWithMeasure() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchClientLiveTest.java index c1dd1db7be..0b25025959 100644 --- a/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/cloudwatch/CloudWatchClientLiveTest.java @@ -43,7 +43,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "cloudwatch.CloudWatchClientLiveTest") +@Test(groups = "live", sequential = true) public class CloudWatchClientLiveTest { private CloudWatchClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/cloudwatch/xml/GetMetricStatisticsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/cloudwatch/xml/GetMetricStatisticsResponseHandlerTest.java index e09260a98f..c27ac41b16 100644 --- a/aws/core/src/test/java/org/jclouds/aws/cloudwatch/xml/GetMetricStatisticsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/cloudwatch/xml/GetMetricStatisticsResponseHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudwatch.GetMetricStatisticsResponseHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "GetMetricStatisticsResponseHandlerTest") public class GetMetricStatisticsResponseHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { DateService dateService = injector.getInstance(DateService.class); diff --git a/aws/core/src/test/java/org/jclouds/aws/config/AWSRestClientModuleTest.java b/aws/core/src/test/java/org/jclouds/aws/config/AWSRestClientModuleTest.java index f155553465..0edd8ffae7 100644 --- a/aws/core/src/test/java/org/jclouds/aws/config/AWSRestClientModuleTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/config/AWSRestClientModuleTest.java @@ -35,7 +35,7 @@ import com.google.common.collect.ImmutableMap; * * @author Adrian Cole */ -@Test(sequential = true, groups = { "unit" }, testName = "aws.AWSRestClientModuleTest") +@Test(sequential = true, groups = { "unit" }) public class AWSRestClientModuleTest { @Test diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/CloudApplicationArchitecturesEC2ClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/CloudApplicationArchitecturesEC2ClientLiveTest.java index 4850106f0a..cd6caad098 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/CloudApplicationArchitecturesEC2ClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/CloudApplicationArchitecturesEC2ClientLiveTest.java @@ -37,6 +37,7 @@ import java.util.concurrent.TimeoutException; import org.jclouds.Constants; import org.jclouds.aws.AWSResponseException; import org.jclouds.aws.ec2.domain.BlockDeviceMapping; +import org.jclouds.aws.ec2.domain.Image.EbsBlockDevice; import org.jclouds.aws.ec2.domain.InstanceState; import org.jclouds.aws.ec2.domain.InstanceType; import org.jclouds.aws.ec2.domain.IpProtocol; @@ -44,10 +45,10 @@ import org.jclouds.aws.ec2.domain.KeyPair; import org.jclouds.aws.ec2.domain.PublicIpInstanceIdPair; import org.jclouds.aws.ec2.domain.Reservation; import org.jclouds.aws.ec2.domain.RunningInstance; -import org.jclouds.aws.ec2.domain.Image.EbsBlockDevice; import org.jclouds.aws.ec2.domain.Volume.InstanceInitiatedShutdownBehavior; import org.jclouds.aws.ec2.predicates.InstanceHasIpAddress; import org.jclouds.aws.ec2.predicates.InstanceStateRunning; +import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.net.IPSocket; @@ -78,7 +79,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", enabled = false, sequential = true, testName = "ec2.CloudApplicationArchitecturesEC2ClientLiveTest") +@Test(groups = "live", enabled = false, sequential = true) public class CloudApplicationArchitecturesEC2ClientLiveTest { private EC2Client client; @@ -102,10 +103,10 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { protected void setupCredentials() { identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); + + ".credential"); endpoint = checkNotNull(System.getProperty("test." + provider + ".endpoint"), "test." + provider + ".endpoint"); apiversion = checkNotNull(System.getProperty("test." + provider + ".apiversion"), "test." + provider - + ".apiversion"); + + ".apiversion"); } protected Properties setupProperties() { @@ -124,11 +125,11 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { setupCredentials(); Properties overrides = setupProperties(); Injector injector = new RestContextFactory().createContextBuilder(provider, - ImmutableSet. of(new Log4JLoggingModule()), overrides).buildInjector(); + ImmutableSet. of(new Log4JLoggingModule()), overrides).buildInjector(); client = injector.getInstance(EC2Client.class); sshFactory = injector.getInstance(SshClient.Factory.class); runningTester = new RetryablePredicate(new InstanceStateRunning(client), 180, 5, - TimeUnit.SECONDS); + TimeUnit.SECONDS); hasIpTester = new RetryablePredicate(new InstanceHasIpAddress(client), 180, 5, TimeUnit.SECONDS); SocketOpen socketOpen = injector.getInstance(SocketOpen.class); socketTester = new RetryablePredicate(socketOpen, 180, 1, TimeUnit.SECONDS); @@ -146,7 +147,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { client.getSecurityGroupServices().createSecurityGroupInRegion(null, securityGroupName, securityGroupName); for (int port : new int[] { 80, 443, 22 }) { client.getSecurityGroupServices().authorizeSecurityGroupIngressInRegion(null, securityGroupName, - IpProtocol.TCP, port, port, "0.0.0.0/0"); + IpProtocol.TCP, port, port, "0.0.0.0/0"); } } @@ -170,9 +171,9 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { @Test(enabled = false, dependsOnMethods = { "testCreateKeyPair", "testCreateSecurityGroupIngressCidr" }) public void testCreateRunningInstance() throws Exception { String script = new ScriptBuilder() // lamp install script - .addStatement(exec("runurl run.alestic.com/apt/upgrade"))// - .addStatement(exec("runurl run.alestic.com/install/lamp"))// - .render(OsFamily.UNIX); + .addStatement(exec("runurl run.alestic.com/apt/upgrade"))// + .addStatement(exec("runurl run.alestic.com/install/lamp"))// + .render(OsFamily.UNIX); RunningInstance instance = null; while (instance == null) { @@ -180,25 +181,25 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { System.out.printf("%d: running instance%n", System.currentTimeMillis()); Reservation reservation = client.getInstanceServices().runInstancesInRegion( - null, null, // allow - // ec2 - // to - // chose - // an - // availability - // zone - "ami-ccf615a5", // alestic ami allows auto-invoke of - // user data scripts - 1, // minimum instances - 1, // maximum instances - asType(InstanceType.M1_SMALL) // smallest instance size - .withKeyName(keyPair.getKeyName()) // key I - // created - // above - .withSecurityGroup(securityGroupName) // group I - // created - // above - .withUserData(script.getBytes())); // script to + null, null, // allow + // ec2 + // to + // chose + // an + // availability + // zone + "ami-ccf615a5", // alestic ami allows auto-invoke of + // user data scripts + 1, // minimum instances + 1, // maximum instances + asType(InstanceType.M1_SMALL) // smallest instance size + .withKeyName(keyPair.getKeyName()) // key I + // created + // above + .withSecurityGroup(securityGroupName) // group I + // created + // above + .withUserData(script.getBytes())); // script to // run as root instance = Iterables.getOnlyElement(reservation); @@ -232,14 +233,14 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { assert client.getInstanceServices().getKernelForInstanceInRegion(null, instanceId).startsWith("aki-"); - assertEquals(InstanceType.M1_SMALL, client.getInstanceServices().getInstanceTypeForInstanceInRegion(null, - instanceId)); + assertEquals(InstanceType.M1_SMALL, + client.getInstanceServices().getInstanceTypeForInstanceInRegion(null, instanceId)); assertEquals(InstanceInitiatedShutdownBehavior.TERMINATE, client.getInstanceServices() - .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, instanceId)); + .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, instanceId)); assertEquals(ImmutableMap. of(), client.getInstanceServices() - .getBlockDeviceMappingForInstanceInRegion(null, instanceId)); + .getBlockDeviceMappingForInstanceInRegion(null, instanceId)); } private void setApiTerminationDisabledForInstanceInRegion() { @@ -310,7 +311,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { private void setInstanceInitiatedShutdownBehaviorForInstanceInRegion() { try { client.getInstanceServices().setInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, instanceId, - InstanceInitiatedShutdownBehavior.STOP); + InstanceInitiatedShutdownBehavior.STOP); assert false : "shouldn't be allowed, as instance needs to be ebs based-ami"; } catch (AWSResponseException e) { assertEquals("UnsupportedInstanceAttribute", e.getError().getCode()); @@ -325,8 +326,8 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { Thread.sleep(1000); instance = getInstance(instanceId); blockUntilWeCanSshIntoInstance(instance); - SshClient ssh = sshFactory.create(new IPSocket(instance.getIpAddress(), 22), "root", keyPair.getKeyMaterial() - .getBytes()); + SshClient ssh = sshFactory.create(new IPSocket(instance.getIpAddress(), 22), + new Credentials("root", keyPair.getKeyMaterial())); try { ssh.connect(); ExecResponse uptime = ssh.exec("uptime"); @@ -343,7 +344,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { assertNotNull(address); PublicIpInstanceIdPair compare = Iterables.getLast(client.getElasticIPAddressServices() - .describeAddressesInRegion(null, address)); + .describeAddressesInRegion(null, address)); assertEquals(compare.getPublicIp(), address); assert compare.getInstanceId() == null; @@ -356,7 +357,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { assertEquals(compare.getInstanceId(), instanceId); Reservation reservation = Iterables.getOnlyElement(client.getInstanceServices() - .describeInstancesInRegion(null, instanceId)); + .describeInstancesInRegion(null, instanceId)); assertNotNull(Iterables.getOnlyElement(reservation).getIpAddress()); assertFalse(Iterables.getOnlyElement(reservation).getIpAddress().equals(address)); @@ -382,7 +383,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { instance = getInstance(instance.getId()); System.out - .printf("%d: %s awaiting instance to have ip assigned %n", System.currentTimeMillis(), instance.getId()); + .printf("%d: %s awaiting instance to have ip assigned %n", System.currentTimeMillis(), instance.getId()); assert hasIpTester.apply(instance); System.out.printf("%d: %s awaiting ssh service to start%n", System.currentTimeMillis(), instance.getIpAddress()); @@ -401,7 +402,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { private RunningInstance getInstance(String instanceId) { // search my identity for the instance I just created Set> reservations = client.getInstanceServices() - .describeInstancesInRegion(null, instanceId); // last parameter + .describeInstancesInRegion(null, instanceId); // last parameter // (ids) narrows the // search @@ -430,7 +431,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest { } private void doCheckKey(String address) { - SshClient ssh = sshFactory.create(new IPSocket(address, 22), "root", keyPair.getKeyMaterial().getBytes()); + SshClient ssh = sshFactory.create(new IPSocket(address, 22), new Credentials("root", keyPair.getKeyMaterial())); try { ssh.connect(); ExecResponse hello = ssh.exec("echo hello"); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/EBSBootEC2ClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/EBSBootEC2ClientLiveTest.java index 6ed2e2fab2..a68d783746 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/EBSBootEC2ClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/EBSBootEC2ClientLiveTest.java @@ -40,6 +40,8 @@ import org.jclouds.aws.AWSResponseException; import org.jclouds.aws.ec2.domain.Attachment; import org.jclouds.aws.ec2.domain.BlockDeviceMapping; import org.jclouds.aws.ec2.domain.Image; +import org.jclouds.aws.ec2.domain.Image.Architecture; +import org.jclouds.aws.ec2.domain.Image.ImageType; import org.jclouds.aws.ec2.domain.InstanceState; import org.jclouds.aws.ec2.domain.InstanceType; import org.jclouds.aws.ec2.domain.IpProtocol; @@ -49,8 +51,6 @@ import org.jclouds.aws.ec2.domain.RootDeviceType; import org.jclouds.aws.ec2.domain.RunningInstance; import org.jclouds.aws.ec2.domain.Snapshot; import org.jclouds.aws.ec2.domain.Volume; -import org.jclouds.aws.ec2.domain.Image.Architecture; -import org.jclouds.aws.ec2.domain.Image.ImageType; import org.jclouds.aws.ec2.domain.Volume.InstanceInitiatedShutdownBehavior; import org.jclouds.aws.ec2.predicates.InstanceStateRunning; import org.jclouds.aws.ec2.predicates.InstanceStateStopped; @@ -58,6 +58,7 @@ import org.jclouds.aws.ec2.predicates.InstanceStateTerminated; import org.jclouds.aws.ec2.predicates.SnapshotCompleted; import org.jclouds.aws.ec2.predicates.VolumeAttached; import org.jclouds.aws.ec2.predicates.VolumeAvailable; +import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payloads; import org.jclouds.logging.log4j.config.Log4JLoggingModule; @@ -94,7 +95,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", enabled = false, sequential = true, testName = "ec2.EBSBootEC2ClientLiveTest") +@Test(groups = "live", enabled = false, sequential = true) public class EBSBootEC2ClientLiveTest { // don't need a lot of space. 2GB should be more than enough for testing private static final int VOLUME_SIZE = 2; @@ -132,10 +133,10 @@ public class EBSBootEC2ClientLiveTest { protected void setupCredentials() { identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); + + ".credential"); endpoint = checkNotNull(System.getProperty("test." + provider + ".endpoint"), "test." + provider + ".endpoint"); apiversion = checkNotNull(System.getProperty("test." + provider + ".apiversion"), "test." + provider - + ".apiversion"); + + ".apiversion"); } protected Properties setupProperties() { @@ -154,7 +155,7 @@ public class EBSBootEC2ClientLiveTest { setupCredentials(); Properties overrides = setupProperties(); Injector injector = new RestContextFactory().createContextBuilder(provider, - ImmutableSet. of(new Log4JLoggingModule()), overrides).buildInjector(); + ImmutableSet. of(new Log4JLoggingModule()), overrides).buildInjector(); client = injector.getInstance(EC2Client.class); sshFactory = injector.getInstance(SshClient.Factory.class); SocketOpen socketOpen = injector.getInstance(SocketOpen.class); @@ -170,7 +171,7 @@ public class EBSBootEC2ClientLiveTest { attachTester = new RetryablePredicate(volumeAttached, 60, 1, TimeUnit.SECONDS); runningTester = new RetryablePredicate(new InstanceStateRunning(client), 180, 5, - TimeUnit.SECONDS); + TimeUnit.SECONDS); InstanceStateStopped instanceStateStopped = injector.getInstance(InstanceStateStopped.class); stoppedTester = new RetryablePredicate(instanceStateStopped, 60, 1, TimeUnit.SECONDS); @@ -192,11 +193,11 @@ public class EBSBootEC2ClientLiveTest { client.getSecurityGroupServices().createSecurityGroupInRegion(null, securityGroupName, securityGroupName); client.getSecurityGroupServices().authorizeSecurityGroupIngressInRegion(null, securityGroupName, IpProtocol.TCP, - 80, 80, "0.0.0.0/0"); + 80, 80, "0.0.0.0/0"); client.getSecurityGroupServices().authorizeSecurityGroupIngressInRegion(null, securityGroupName, IpProtocol.TCP, - 443, 443, "0.0.0.0/0"); + 443, 443, "0.0.0.0/0"); client.getSecurityGroupServices().authorizeSecurityGroupIngressInRegion(null, securityGroupName, IpProtocol.TCP, - 22, 22, "0.0.0.0/0"); + 22, 22, "0.0.0.0/0"); } @Test(enabled = false) @@ -226,19 +227,19 @@ public class EBSBootEC2ClientLiveTest { try { System.out.printf("%d: running instance%n", System.currentTimeMillis()); Reservation reservation = client.getInstanceServices().runInstancesInRegion( - null, null, // allow - // ec2 - // to - // chose - // an - // availability - // zone - imageId, 1, // minimum instances - 1, // maximum instances - withKeyName(keyPair.getKeyName())// key I created above - .asType(InstanceType.M1_SMALL)// smallest instance - // size - .withSecurityGroup(securityGroupName));// group I + null, null, // allow + // ec2 + // to + // chose + // an + // availability + // zone + imageId, 1, // minimum instances + 1, // maximum instances + withKeyName(keyPair.getKeyName())// key I created above + .asType(InstanceType.M1_SMALL)// smallest instance + // size + .withSecurityGroup(securityGroupName));// group I // created // above instance = Iterables.getOnlyElement(reservation); @@ -257,13 +258,13 @@ public class EBSBootEC2ClientLiveTest { @Test(enabled = false, dependsOnMethods = "testCreateRunningInstance") void testCreateAndAttachVolume() { volume = client.getElasticBlockStoreServices().createVolumeInAvailabilityZone(instance.getAvailabilityZone(), - VOLUME_SIZE); + VOLUME_SIZE); System.out.printf("%d: %s awaiting volume to become available%n", System.currentTimeMillis(), volume.getId()); assert volumeTester.apply(volume); Attachment attachment = client.getElasticBlockStoreServices().attachVolumeInRegion(instance.getRegion(), - volume.getId(), instance.getId(), "/dev/sdh"); + volume.getId(), instance.getId(), "/dev/sdh"); System.out.printf("%d: %s awaiting attachment to complete%n", System.currentTimeMillis(), attachment.getId()); @@ -277,35 +278,32 @@ public class EBSBootEC2ClientLiveTest { void makeScript() { mkEbsBoot = new InitBuilder( - "mkebsboot",// name of the script - "/tmp",// working directory - "/tmp/logs",// location of stdout.log and stderr.log - ImmutableMap.of("imageDir", "/mnt/tmp", "ebsDevice", "/dev/sdh", "ebsMountPoint", "/mnt/ebs"), - ImmutableList - . of(Statements - .interpret( - "echo creating a filesystem and mounting the ebs volume", - "{md} {varl}IMAGE_DIR{varr} {varl}EBS_MOUNT_POINT{varr}", - "rm -rf {varl}IMAGE_DIR{varr}/*", - "yes| mkfs -t ext3 {varl}EBS_DEVICE{varr} 2>&-", - "mount {varl}EBS_DEVICE{varr} {varl}EBS_MOUNT_POINT{varr}", - "echo making a local working copy of the boot disk", - "rsync -ax --exclude /ubuntu/.bash_history --exclude /home/*/.bash_history --exclude /etc/ssh/ssh_host_* --exclude /etc/ssh/moduli --exclude /etc/udev/rules.d/*persistent-net.rules --exclude /var/lib/ec2/* --exclude=/mnt/* --exclude=/proc/* --exclude=/tmp/* --exclude=/dev/log / {varl}IMAGE_DIR{varr}", - "echo preparing the local working copy", - "touch {varl}IMAGE_DIR{varr}/etc/init.d/ec2-init-user-data", - "echo copying the local working copy to the ebs mount", - "{cd} {varl}IMAGE_DIR{varr}", - "tar -cSf - * | tar xf - -C {varl}EBS_MOUNT_POINT{varr}", "echo size of ebs", - "du -sk {varl}EBS_MOUNT_POINT{varr}", "echo size of source", - "du -sk {varl}IMAGE_DIR{varr}", "rm -rf {varl}IMAGE_DIR{varr}/*", - "umount {varl}EBS_MOUNT_POINT{varr}", "echo " + SCRIPT_END))) - .render(OsFamily.UNIX); + "mkebsboot",// name of the script + "/tmp",// working directory + "/tmp/logs",// location of stdout.log and stderr.log + ImmutableMap.of("imageDir", "/mnt/tmp", "ebsDevice", "/dev/sdh", "ebsMountPoint", "/mnt/ebs"), + ImmutableList. of(Statements + .interpret( + "echo creating a filesystem and mounting the ebs volume", + "{md} {varl}IMAGE_DIR{varr} {varl}EBS_MOUNT_POINT{varr}", + "rm -rf {varl}IMAGE_DIR{varr}/*", + "yes| mkfs -t ext3 {varl}EBS_DEVICE{varr} 2>&-", + "mount {varl}EBS_DEVICE{varr} {varl}EBS_MOUNT_POINT{varr}", + "echo making a local working copy of the boot disk", + "rsync -ax --exclude /ubuntu/.bash_history --exclude /home/*/.bash_history --exclude /etc/ssh/ssh_host_* --exclude /etc/ssh/moduli --exclude /etc/udev/rules.d/*persistent-net.rules --exclude /var/lib/ec2/* --exclude=/mnt/* --exclude=/proc/* --exclude=/tmp/* --exclude=/dev/log / {varl}IMAGE_DIR{varr}", + "echo preparing the local working copy", + "touch {varl}IMAGE_DIR{varr}/etc/init.d/ec2-init-user-data", + "echo copying the local working copy to the ebs mount", "{cd} {varl}IMAGE_DIR{varr}", + "tar -cSf - * | tar xf - -C {varl}EBS_MOUNT_POINT{varr}", "echo size of ebs", + "du -sk {varl}EBS_MOUNT_POINT{varr}", "echo size of source", "du -sk {varl}IMAGE_DIR{varr}", + "rm -rf {varl}IMAGE_DIR{varr}/*", "umount {varl}EBS_MOUNT_POINT{varr}", "echo " + SCRIPT_END))) + .render(OsFamily.UNIX); } @Test(enabled = false, dependsOnMethods = "testCreateAndAttachVolume") void testBundleInstance() { - SshClient ssh = sshFactory.create(new IPSocket(instance.getIpAddress(), 22), "ubuntu", keyPair.getKeyMaterial() - .getBytes()); + SshClient ssh = sshFactory.create(new IPSocket(instance.getIpAddress(), 22), + new Credentials("ubuntu", keyPair.getKeyMaterial())); try { ssh.connect(); } catch (SshException e) {// try twice in case there is a network timeout @@ -330,7 +328,7 @@ public class EBSBootEC2ClientLiveTest { assert !output.getOutput().trim().equals("") : output; RetryablePredicate scriptTester = new RetryablePredicate(new ScriptTester(ssh, SCRIPT_END), - 600, 10, TimeUnit.SECONDS); + 600, 10, TimeUnit.SECONDS); scriptTester.apply(script); } finally { if (ssh != null) @@ -360,7 +358,7 @@ public class EBSBootEC2ClientLiveTest { output = ssh.exec(script + " tailerr"); String stderr = output.getOutput().trim(); throw new RuntimeException(String.format( - "script %s ended without token: stdout.log: [%s]; stderr.log: [%s]; ", script, stdout, stderr)); + "script %s ended without token: stdout.log: [%s]; stderr.log: [%s]; ", script, stdout, stderr)); } } return false; @@ -371,7 +369,7 @@ public class EBSBootEC2ClientLiveTest { @Test(enabled = false, dependsOnMethods = "testBundleInstance") void testAMIFromBundle() { volume = Iterables.getOnlyElement(client.getElasticBlockStoreServices().describeVolumesInRegion( - volume.getRegion(), volume.getId())); + volume.getRegion(), volume.getId())); if (volume.getAttachments().size() > 0) { // should be cleanly unmounted, so force is not necessary. client.getElasticBlockStoreServices().detachVolumeInRegion(instance.getRegion(), volume.getId(), false); @@ -382,31 +380,31 @@ public class EBSBootEC2ClientLiveTest { // detach } snapshot = client.getElasticBlockStoreServices().createSnapshotInRegion(volume.getRegion(), volume.getId(), - withDescription("EBS Ubuntu Hardy")); + withDescription("EBS Ubuntu Hardy")); System.out.printf("%d: %s awaiting snapshot to complete%n", System.currentTimeMillis(), snapshot.getId()); assert snapshotTester.apply(snapshot); Image image = Iterables.getOnlyElement(client.getAMIServices().describeImagesInRegion(snapshot.getRegion(), - imageIds(IMAGE_ID))); + imageIds(IMAGE_ID))); String description = image.getDescription() == null ? "jclouds" : image.getDescription(); System.out.printf("%d: %s creating ami from snapshot%n", System.currentTimeMillis(), snapshot.getId()); String amiId = client.getAMIServices().registerUnixImageBackedByEbsInRegion( - snapshot.getRegion(), - "ebsboot-" + image.getId(), - snapshot.getId(), - withKernelId(image.getKernelId()).withRamdisk(image.getRamdiskId()).withDescription(description) - .asArchitecture(Architecture.I386)); + snapshot.getRegion(), + "ebsboot-" + image.getId(), + snapshot.getId(), + withKernelId(image.getKernelId()).withRamdisk(image.getRamdiskId()).withDescription(description) + .asArchitecture(Architecture.I386)); try { ebsImage = Iterables.getOnlyElement(client.getAMIServices().describeImagesInRegion(snapshot.getRegion(), - imageIds(amiId))); + imageIds(amiId))); } catch (AWSResponseException e) { // TODO add a retry handler for this HTTP code 400 and the below error if (e.getError().getClass().equals("InvalidAMIID.NotFound")) ebsImage = Iterables.getOnlyElement(client.getAMIServices().describeImagesInRegion(snapshot.getRegion(), - imageIds(amiId))); + imageIds(amiId))); else throw e; } @@ -433,8 +431,8 @@ public class EBSBootEC2ClientLiveTest { assertEquals(ebsImage.getImageType(), ImageType.MACHINE); assertEquals(ebsImage.getRootDeviceType(), RootDeviceType.EBS); assertEquals(ebsImage.getRootDeviceName(), "/dev/sda1"); - assertEquals(ebsImage.getEbsBlockDevices().entrySet(), ImmutableMap.of("/dev/sda1", - new Image.EbsBlockDevice(snapshot.getId(), VOLUME_SIZE, true)).entrySet()); + assertEquals(ebsImage.getEbsBlockDevices().entrySet(), + ImmutableMap.of("/dev/sda1", new Image.EbsBlockDevice(snapshot.getId(), VOLUME_SIZE, true)).entrySet()); } private void tryToChangeStuff() { @@ -465,12 +463,12 @@ public class EBSBootEC2ClientLiveTest { private void setInstanceTypeForInstanceInRegion() { client.getInstanceServices() - .setInstanceTypeForInstanceInRegion(null, ebsInstance.getId(), InstanceType.C1_MEDIUM); - assertEquals(InstanceType.C1_MEDIUM, client.getInstanceServices().getInstanceTypeForInstanceInRegion(null, - ebsInstance.getId())); + .setInstanceTypeForInstanceInRegion(null, ebsInstance.getId(), InstanceType.C1_MEDIUM); + assertEquals(InstanceType.C1_MEDIUM, + client.getInstanceServices().getInstanceTypeForInstanceInRegion(null, ebsInstance.getId())); client.getInstanceServices().setInstanceTypeForInstanceInRegion(null, ebsInstance.getId(), InstanceType.M1_SMALL); - assertEquals(InstanceType.M1_SMALL, client.getInstanceServices().getInstanceTypeForInstanceInRegion(null, - ebsInstance.getId())); + assertEquals(InstanceType.M1_SMALL, + client.getInstanceServices().getInstanceTypeForInstanceInRegion(null, ebsInstance.getId())); } private void setBlockDeviceMappingForInstanceInRegion() { @@ -480,10 +478,10 @@ public class EBSBootEC2ClientLiveTest { blockDeviceMapping.addEbsBlockDevice("/dev/sda1", new RunningInstance.EbsBlockDevice(volumeId, false)); try { client.getInstanceServices().setBlockDeviceMappingForInstanceInRegion(null, ebsInstance.getId(), - blockDeviceMapping); + blockDeviceMapping); Map devices = client.getInstanceServices() - .getBlockDeviceMappingForInstanceInRegion(null, ebsInstance.getId()); + .getBlockDeviceMappingForInstanceInRegion(null, ebsInstance.getId()); assertEquals(devices.size(), 1); String deviceName = Iterables.getOnlyElement(devices.keySet()); RunningInstance.EbsBlockDevice device = Iterables.getOnlyElement(devices.values()); @@ -504,15 +502,15 @@ public class EBSBootEC2ClientLiveTest { try { client.getInstanceServices().setInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, - ebsInstance.getId(), InstanceInitiatedShutdownBehavior.STOP); + ebsInstance.getId(), InstanceInitiatedShutdownBehavior.STOP); assertEquals(InstanceInitiatedShutdownBehavior.STOP, client.getInstanceServices() - .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, ebsInstance.getId())); + .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, ebsInstance.getId())); client.getInstanceServices().setInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, - ebsInstance.getId(), InstanceInitiatedShutdownBehavior.TERMINATE); + ebsInstance.getId(), InstanceInitiatedShutdownBehavior.TERMINATE); assertEquals(InstanceInitiatedShutdownBehavior.TERMINATE, client.getInstanceServices() - .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, ebsInstance.getId())); + .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, ebsInstance.getId())); System.out.println("OK: setInstanceInitiatedShutdownBehaviorForInstanceInRegion"); } catch (Exception e) { System.err.println("setInstanceInitiatedShutdownBehaviorForInstanceInRegion"); @@ -542,7 +540,7 @@ public class EBSBootEC2ClientLiveTest { } private void doCheckKey(String address) { - SshClient ssh = sshFactory.create(new IPSocket(address, 22), "ubuntu", keyPair.getKeyMaterial().getBytes()); + SshClient ssh = sshFactory.create(new IPSocket(address, 22), new Credentials("ubuntu", keyPair.getKeyMaterial())); try { ssh.connect(); ExecResponse hello = ssh.exec("echo hello"); @@ -559,7 +557,7 @@ public class EBSBootEC2ClientLiveTest { // search my identity for the instance I just created Set> reservations = client.getInstanceServices() - .describeInstancesInRegion(instance.getRegion(), instance.getId()); // last + .describeInstancesInRegion(instance.getRegion(), instance.getId()); // last // parameter // (ids) // narrows diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/EC2AsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/EC2AsyncClientTest.java index 49e3b8c38a..4af41c438e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/EC2AsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/EC2AsyncClientTest.java @@ -31,11 +31,12 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code EC2Client} + * Tests behavior of {@code EC2AsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.EC2ClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "EC2AsyncClientTest") public class EC2AsyncClientTest extends BaseEC2AsyncClientTest { private EC2AsyncClient asyncClient; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParamsTest.java new file mode 100644 index 0000000000..94f659cfdf --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBlockDeviceMappingToIndexedFormParamsTest.java @@ -0,0 +1,75 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; +import java.util.Date; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.aws.ec2.domain.Attachment.Status; +import org.jclouds.aws.ec2.domain.BlockDeviceMapping; +import org.jclouds.aws.ec2.domain.RunningInstance; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindBlockDeviceMappingToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindBlockDeviceMappingToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindBlockDeviceMappingToIndexedFormParams binder = injector + .getInstance(BindBlockDeviceMappingToIndexedFormParams.class); + + public void testMapping() { + BlockDeviceMapping mapping = new BlockDeviceMapping(); + mapping.addEbsBlockDevice("apple", new RunningInstance.EbsBlockDevice("appleId", true)); + Date date = new Date(999999l); + mapping.addEbsBlockDevice("cranberry", new RunningInstance.EbsBlockDevice("cranberry", Status.ATTACHED, date, + false)); + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, mapping); + assertEquals( + request.getPayload().getRawContent(), + "BlockDeviceMapping.1.Ebs.VolumeId=appleId&BlockDeviceMapping.1.DeviceName=apple&BlockDeviceMapping.1.Ebs.DeleteOnTermination=true&BlockDeviceMapping.2.Ebs.VolumeId=cranberry&BlockDeviceMapping.2.DeviceName=cranberry&BlockDeviceMapping.2.Ebs.DeleteOnTermination=false"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeBlockDeviceMapping() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParamsTest.java new file mode 100644 index 0000000000..1710ec51dc --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindBundleIdsToIndexedFormParamsTest.java @@ -0,0 +1,63 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindBundleIdsToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindBundleIdsToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindBundleIdsToIndexedFormParams binder = injector.getInstance(BindBundleIdsToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new String[] { "alpha", "omega" }); + assertEquals(request.getPayload().getRawContent(), "BundleId.1=alpha&BundleId.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeArray() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParamsTest.java new file mode 100644 index 0000000000..12f02d9ddb --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindGroupNamesToIndexedFormParamsTest.java @@ -0,0 +1,63 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindGroupNamesToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindGroupNamesToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindGroupNamesToIndexedFormParams binder = injector.getInstance(BindGroupNamesToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new String[] { "alpha", "omega" }); + assertEquals(request.getPayload().getRawContent(), "GroupName.1=alpha&GroupName.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeArray() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParamsTest.java new file mode 100644 index 0000000000..a52b4f8a11 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindInstanceIdsToIndexedFormParamsTest.java @@ -0,0 +1,63 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindInstanceIdsToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindInstanceIdsToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindInstanceIdsToIndexedFormParams binder = injector.getInstance(BindInstanceIdsToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new String[] { "alpha", "omega" }); + assertEquals(request.getPayload().getRawContent(), "InstanceId.1=alpha&InstanceId.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeArray() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParamsTest.java new file mode 100644 index 0000000000..2c1ccbcccb --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindKeyNamesToIndexedFormParamsTest.java @@ -0,0 +1,63 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindKeyNamesToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindKeyNamesToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindKeyNamesToIndexedFormParams binder = injector.getInstance(BindKeyNamesToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new String[] { "alpha", "omega" }); + assertEquals(request.getPayload().getRawContent(), "KeyName.1=alpha&KeyName.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeArray() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParamsTest.java new file mode 100644 index 0000000000..ac719871d5 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindProductCodesToIndexedFormParamsTest.java @@ -0,0 +1,64 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +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 BindProductCodesToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindProductCodesToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindProductCodesToIndexedFormParams binder = injector.getInstance(BindProductCodesToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, ImmutableSet.of("alpha", "omega")); + assertEquals(request.getPayload().getRawContent(), "ProductCode.1=alpha&ProductCode.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeIterable() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParamsTest.java new file mode 100644 index 0000000000..0753d8b30f --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindPublicIpsToIndexedFormParamsTest.java @@ -0,0 +1,63 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindPublicIpsToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindPublicIpsToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindPublicIpsToIndexedFormParams binder = injector.getInstance(BindPublicIpsToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new String[] { "alpha", "omega" }); + assertEquals(request.getPayload().getRawContent(), "PublicIp.1=alpha&PublicIp.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeArray() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignatureTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignatureTest.java new file mode 100644 index 0000000000..083e953373 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindS3UploadPolicyAndSignatureTest.java @@ -0,0 +1,64 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.aws.s3.BaseS3AsyncClientTest; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Tests behavior of {@code BindS3UploadPolicyAndSignature} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindS3UploadPolicyAndSignatureTest") +public class BindS3UploadPolicyAndSignatureTest extends BaseS3AsyncClientTest { + private BindS3UploadPolicyAndSignature binder; + + @BeforeClass + @Override + protected void setupFactory() throws IOException { + super.setupFactory(); + binder = injector.getInstance(BindS3UploadPolicyAndSignature.class); + } + + public void testMapping() { + String json = "{\"foo\":true}"; + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, json); + assertEquals( + request.getPayload().getRawContent(), + "Storage.S3.UploadPolicy=eyJmb28iOnRydWV9&Storage.S3.UploadPolicySignature=UbDQLDM5P3aZ840aqJoH%2B6rwDcRo5KrIfsG7vJWHIVY%3D"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParamsTest.java new file mode 100644 index 0000000000..ee240c0da3 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserGroupsToIndexedFormParamsTest.java @@ -0,0 +1,69 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +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 BindUserGroupsToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindUserGroupsToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindUserGroupsToIndexedFormParams binder = injector.getInstance(BindUserGroupsToIndexedFormParams.class); + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testOnlyAllIsValid() { + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, ImmutableSet.of("alpha")); + } + + public void test() { + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, ImmutableSet.of("all")); + assertEquals(request.getPayload().getRawContent(), "UserGroup.1=all"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeIterable() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParamsTest.java new file mode 100644 index 0000000000..0aedd5f6db --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParamsTest.java @@ -0,0 +1,66 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.aws.ec2.domain.UserIdGroupPair; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindUserIdGroupPairToSourceSecurityGroupFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindUserIdGroupPairToSourceSecurityGroupFormParamsTest { + Injector injector = Guice.createInjector(); + BindUserIdGroupPairToSourceSecurityGroupFormParams binder = injector + .getInstance(BindUserIdGroupPairToSourceSecurityGroupFormParams.class); + + public void testUserIdGroupPair() { + UserIdGroupPair pair = new UserIdGroupPair("id", "group"); + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, pair); + assertEquals(request.getPayload().getRawContent(), "SourceSecurityGroupOwnerId=id&SourceSecurityGroupName=group"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeUserIdGroupPair() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParamsTest.java new file mode 100644 index 0000000000..014e08ece9 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindUserIdsToIndexedFormParamsTest.java @@ -0,0 +1,64 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +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 BindUserIdsToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindUserIdsToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindUserIdsToIndexedFormParams binder = injector.getInstance(BindUserIdsToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, ImmutableSet.of("alpha", "omega")); + assertEquals(request.getPayload().getRawContent(), "UserId.1=alpha&UserId.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeIterable() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParamsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParamsTest.java new file mode 100644 index 0000000000..51adc1c952 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/BindVolumeIdsToIndexedFormParamsTest.java @@ -0,0 +1,63 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code BindVolumeIdsToIndexedFormParams} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindVolumeIdsToIndexedFormParamsTest { + Injector injector = Guice.createInjector(); + BindVolumeIdsToIndexedFormParams binder = injector.getInstance(BindVolumeIdsToIndexedFormParams.class); + + public void test() { + + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new String[] { "alpha", "omega" }); + assertEquals(request.getPayload().getRawContent(), "VolumeId.1=alpha&VolumeId.2=omega"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeArray() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParamTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParamTest.java new file mode 100644 index 0000000000..ea533d551b --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/binders/IfNotNullBindAvailabilityZoneToFormParamTest.java @@ -0,0 +1,65 @@ +/** + * + * 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.aws.ec2.binders; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertSame; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * Tests behavior of {@code IfNotNullBindAvailabilityZoneToFormParam} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class IfNotNullBindAvailabilityZoneToFormParamTest { + Injector injector = Guice.createInjector(); + IfNotNullBindAvailabilityZoneToFormParam binder = injector + .getInstance(IfNotNullBindAvailabilityZoneToFormParam.class); + + public void test() { + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, "us-east-1a"); + assertEquals(request.getPayload().getRawContent(), "Placement.AvailabilityZone=us-east-1a"); + } + + public void testWhenNullReturnsSame() { + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + HttpRequest request2 = binder.bindToRequest(request, null); + assertSame(request, request2); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeString() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/BlobStoreAndComputeServiceLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/BlobStoreAndComputeServiceLiveTest.java index 5dbed6d16f..215dc57a61 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/BlobStoreAndComputeServiceLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/BlobStoreAndComputeServiceLiveTest.java @@ -99,8 +99,7 @@ public class BlobStoreAndComputeServiceLiveTest { for (NodeMetadata node : nodes) { IPSocket socket = new IPSocket(get(node.getPublicAddresses(), 0), 22); - SshClient ssh = computeContext.utils().sshFactory() - .create(socket, node.getCredentials().identity, node.getCredentials().credential.getBytes()); + SshClient ssh = computeContext.utils().sshFactory().create(socket, node.getCredentials()); try { ssh.connect(); ExecResponse exec = ssh.exec(cmd); 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 47cb94c0a8..5eb56ee3ed 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 @@ -61,7 +61,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.EC2ComputeServiceLiveTest") +@Test(groups = "live", sequential = true) public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { public EC2ComputeServiceLiveTest() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2LoadBalancerServiceLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2LoadBalancerServiceLiveTest.java index 89c5cbe932..439b69c478 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2LoadBalancerServiceLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2LoadBalancerServiceLiveTest.java @@ -46,7 +46,7 @@ import com.google.common.collect.ImmutableSet; * * @author Lili Nadar */ -@Test(groups = "live", sequential = true, testName = "ec2.EC2LoadBalancerServiceLiveTest") +@Test(groups = "live", sequential = true) public class EC2LoadBalancerServiceLiveTest extends BaseLoadBalancerServiceLiveTest { private RestContext elbContext; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2TemplateBuilderLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2TemplateBuilderLiveTest.java index 0bae72c07d..3951d9931c 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2TemplateBuilderLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2TemplateBuilderLiveTest.java @@ -44,7 +44,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", testName = "ec2.EC2TemplateBuilderLiveTest") +@Test(groups = "live") public class EC2TemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public EC2TemplateBuilderLiveTest() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java index 991f7e15e6..48471cb0f4 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java @@ -32,7 +32,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "ec2.EucalyptusComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class EucalyptusComputeServiceLiveTestDisabled extends EC2ComputeServiceLiveTest { public EucalyptusComputeServiceLiveTestDisabled() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaComputeServiceLiveTestDisabled.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaComputeServiceLiveTestDisabled.java index 0f3d26259f..c9bbf14e46 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaComputeServiceLiveTestDisabled.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaComputeServiceLiveTestDisabled.java @@ -30,7 +30,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(enabled = false, groups = "live", sequential = true, testName = "ec2.NebulaComputeServiceLiveTest") +@Test(enabled = false, groups = "live", sequential = true) public class NovaComputeServiceLiveTestDisabled extends EC2ComputeServiceLiveTest { public NovaComputeServiceLiveTestDisabled() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaTemplateBuilderLiveTestDisabled.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaTemplateBuilderLiveTestDisabled.java index 575e33139c..db4455789e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaTemplateBuilderLiveTestDisabled.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/NovaTemplateBuilderLiveTestDisabled.java @@ -42,7 +42,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(enabled = false, groups = "live", testName = "ec2.NebulaTemplateBuilderLiveTest") +@Test(enabled = false, groups = "live") public class NovaTemplateBuilderLiveTestDisabled { protected String provider = "nova"; protected String identity; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CreateUniqueKeyPairTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CreateUniqueKeyPairTest.java index edbc35ae5c..b3326d18a5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CreateUniqueKeyPairTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CreateUniqueKeyPairTest.java @@ -37,7 +37,7 @@ import com.google.common.base.Supplier; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.CreateUniqueKeyPairTest") +@Test(groups = "unit") public class CreateUniqueKeyPairTest { @SuppressWarnings( { "unchecked" }) @Test diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java index 37f4ba9c91..cac397345c 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java @@ -19,60 +19,14 @@ package org.jclouds.aws.ec2.compute.functions; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; -import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_small; -import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m2_4xlarge; -import static org.jclouds.aws.ec2.options.DescribeImagesOptions.Builder.imageIds; -import static org.testng.Assert.assertEquals; - -import java.net.UnknownHostException; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.jclouds.aws.domain.Region; -import org.jclouds.aws.ec2.EC2Client; -import org.jclouds.aws.ec2.compute.domain.RegionAndName; -import org.jclouds.aws.ec2.domain.Attachment; -import org.jclouds.aws.ec2.domain.AvailabilityZone; -import org.jclouds.aws.ec2.domain.Image; -import org.jclouds.aws.ec2.domain.InstanceState; -import org.jclouds.aws.ec2.domain.InstanceType; -import org.jclouds.aws.ec2.domain.KeyPair; -import org.jclouds.aws.ec2.domain.RootDeviceType; -import org.jclouds.aws.ec2.domain.RunningInstance; -import org.jclouds.aws.ec2.domain.RunningInstance.EbsBlockDevice; -import org.jclouds.aws.ec2.services.AMIClient; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Volume; -import org.jclouds.compute.domain.internal.VolumeImpl; -import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.date.DateService; import org.jclouds.date.internal.SimpleDateFormatDateService; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationScope; -import org.jclouds.domain.internal.LocationImpl; import org.testng.annotations.Test; -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; - /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.CredentialsForInstanceTest") +@Test(groups = "unit") public class CredentialsForInstanceTest { DateService dateService = new SimpleDateFormatDateService(); 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 99aa26d442..37bd9e3fad 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 @@ -52,7 +52,7 @@ import com.google.inject.Guice; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "compute.ImageParserTest") +@Test(groups = "unit") public class ImageParserTest { public void testParseAlesticCanonicalImage() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RegionAndIdToImageTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RegionAndIdToImageTest.java index 6b048fb308..aa754ba655 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RegionAndIdToImageTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RegionAndIdToImageTest.java @@ -42,10 +42,10 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.RegionAndIdToImageTest") +@Test(groups = "unit") public class RegionAndIdToImageTest { - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testApply() { @@ -77,7 +77,7 @@ public class RegionAndIdToImageTest { } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testApplyNotFound() { @@ -109,7 +109,7 @@ public class RegionAndIdToImageTest { } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testApplyNoSuchElementException() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index a0044b6b73..d4197e727a 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -58,7 +58,7 @@ import javax.annotation.Nullable; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.RunningInstanceToNodeMetadataTest") +@Test(groups = "unit") public class RunningInstanceToNodeMetadataTest { public void testAllStatesCovered() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java index 29cf9eb0e9..dabb8d004c 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java @@ -53,7 +53,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest") +@Test(groups = "unit") public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest { public void testExecuteWithDefaultOptionsEC2() throws SecurityException, NoSuchMethodException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java index 413c1eea73..4a85843df8 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java @@ -58,7 +58,7 @@ import com.google.common.collect.Iterables; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.EC2RunNodesAndAddToSetStrategyTest") +@Test(groups = "unit") public class EC2RunNodesAndAddToSetStrategyTest { @Test @@ -92,7 +92,7 @@ public class EC2RunNodesAndAddToSetStrategyTest { return null; } - @SuppressWarnings( { "unchecked" }) + @SuppressWarnings({ "unchecked", "rawtypes" }) private void assertRegionAndZoneForLocation(Location location, String region, String zone) { String imageId = "ami1"; String instanceCreatedId = "instance1"; @@ -102,20 +102,21 @@ public class EC2RunNodesAndAddToSetStrategyTest { InstanceClient instanceClient = createMock(InstanceClient.class); RunInstancesOptions ec2Options = createMock(RunInstancesOptions.class); RunningInstance instance = createMock(RunningInstance.class); - Reservation reservation = new Reservation(region, ImmutableSet - . of(), ImmutableSet. of(instance), "ownerId", "requesterId", "reservationId"); + Reservation reservation = new Reservation(region, + ImmutableSet. of(), ImmutableSet. of(instance), "ownerId", "requesterId", + "reservationId"); NodeMetadata nodeMetadata = createMock(NodeMetadata.class); // setup expectations expect(strategy.client.getInstanceServices()).andReturn(instanceClient).atLeastOnce(); expect( - strategy.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region, input.tag, - input.template)).andReturn(ec2Options); + strategy.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region, input.tag, + input.template)).andReturn(ec2Options); expect(input.template.getLocation()).andReturn(input.location).atLeastOnce(); expect(input.template.getImage()).andReturn(input.image).atLeastOnce(); expect(input.image.getProviderId()).andReturn(imageId).atLeastOnce(); expect(instanceClient.runInstancesInRegion(region, zone, imageId, 1, input.count, ec2Options)).andReturn( - (Reservation) reservation); + (Reservation) reservation); expect(instance.getId()).andReturn(instanceCreatedId).atLeastOnce(); // simulate a lazy credentials fetch Credentials creds = new Credentials("foo", "bar"); @@ -129,8 +130,8 @@ public class EC2RunNodesAndAddToSetStrategyTest { expect(strategy.runningInstanceToNodeMetadata.apply(instance)).andReturn(nodeMetadata); expect( - strategy.utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(eq(input.options), - containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes))).andReturn(null); + strategy.utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(eq(input.options), + containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes))).andReturn(null); // replay mocks replay(instanceClient); @@ -153,9 +154,9 @@ public class EC2RunNodesAndAddToSetStrategyTest { } private static final Location REGION_AP_SOUTHEAST_1 = new LocationImpl(LocationScope.REGION, Region.AP_SOUTHEAST_1, - Region.AP_SOUTHEAST_1, new LocationImpl(LocationScope.PROVIDER, "ec2", "ec2", null)); + Region.AP_SOUTHEAST_1, new LocationImpl(LocationScope.PROVIDER, "ec2", "ec2", null)); private static final Location ZONE_AP_SOUTHEAST_1A = new LocationImpl(LocationScope.ZONE, - AvailabilityZone.AP_SOUTHEAST_1A, AvailabilityZone.AP_SOUTHEAST_1A, REGION_AP_SOUTHEAST_1); + AvailabilityZone.AP_SOUTHEAST_1A, AvailabilityZone.AP_SOUTHEAST_1A, REGION_AP_SOUTHEAST_1); // ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unchecked") @@ -213,7 +214,7 @@ public class EC2RunNodesAndAddToSetStrategyTest { Map credentialStore = createMock(Map.class); ComputeUtils utils = createMock(ComputeUtils.class); return new EC2RunNodesAndAddToSetStrategy(client, createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions, - instanceStateRunning, runningInstanceToNodeMetadata, instanceToCredentials, credentialStore, utils); + instanceStateRunning, runningInstanceToNodeMetadata, instanceToCredentials, credentialStore, utils); } private void replayStrategy(EC2RunNodesAndAddToSetStrategy strategy) { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/functions/ConvertUnencodedBytesToBase64EncodedStringTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/functions/ConvertUnencodedBytesToBase64EncodedStringTest.java index 6178acddd2..5060159891 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/functions/ConvertUnencodedBytesToBase64EncodedStringTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/functions/ConvertUnencodedBytesToBase64EncodedStringTest.java @@ -33,7 +33,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.ConvertUnencodedBytesToBase64EncodedStringTest") +@Test(groups = "unit") public class ConvertUnencodedBytesToBase64EncodedStringTest { Injector injector = Guice.createInjector(); 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 b85b84d1a4..7079d4a7d5 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 @@ -49,7 +49,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.AMIAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AMIAsyncClientTest") public class AMIAsyncClientTest extends BaseEC2AsyncClientTest { public void testCreateImage() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIClientLiveTest.java index 673ef2b69b..0cb4670651 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AMIClientLiveTest.java @@ -58,7 +58,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.AMIClientLiveTest") +@Test(groups = "live", sequential = true) public class AMIClientLiveTest { private AMIClient client; 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 a3b4cec5cc..6dab576bce 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,7 +45,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.AvailabilityZoneAndRegionAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AvailabilityZoneAndRegionAsyncClientTest") public class AvailabilityZoneAndRegionAsyncClientTest extends BaseEC2AsyncClientTest { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionClientLiveTest.java index 3ef0c93d3c..93fcf9c967 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/AvailabilityZoneAndRegionClientLiveTest.java @@ -55,7 +55,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.AvailabilityZoneAndRegionClientLiveTest") +@Test(groups = "live", sequential = true) public class AvailabilityZoneAndRegionClientLiveTest { private AvailabilityZoneAndRegionClient client; 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 da56c739a6..d618438c48 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 @@ -42,16 +42,16 @@ import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.inject.Injector; import com.google.inject.Module; /** - * - * * @author Adrian Cole */ +@Test(groups = "unit") public abstract class BaseEC2AsyncClientTest extends RestClientTest { @RequiresHttp @ConfiguresRestClient @@ -66,8 +66,8 @@ public abstract class BaseEC2AsyncClientTest extends RestClientTest { @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")); + 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 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 4bf0b376b8..8ae6f5ddc3 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 @@ -52,7 +52,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.ElasticBlockStoreAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ElasticBlockStoreAsyncClientTest") public class ElasticBlockStoreAsyncClientTest extends BaseEC2AsyncClientTest { public void testCreateVolume() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreClientLiveTest.java index daabd9d99d..063d9ce34d 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticBlockStoreClientLiveTest.java @@ -59,7 +59,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.ElasticBlockStoreClientLiveTest") +@Test(groups = "live", sequential = true) public class ElasticBlockStoreClientLiveTest { private ElasticBlockStoreClient client; private RestContext context; 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 6945b7cf85..f468f23456 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 @@ -39,7 +39,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.ElasticIPAddressAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ElasticIPAddressAsyncClientTest") public class ElasticIPAddressAsyncClientTest extends BaseEC2AsyncClientTest { public void testDisassociateAddress() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressClientLiveTest.java index c479de7213..510d858b15 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/ElasticIPAddressClientLiveTest.java @@ -48,7 +48,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.ElasticIPAddressClientLiveTest") +@Test(groups = "live", sequential = true) public class ElasticIPAddressClientLiveTest { private ElasticIPAddressClient client; 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 98f5883c59..4bc10f9f83 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 @@ -53,7 +53,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.InstanceAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "InstanceAsyncClientTest") public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest { public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException { Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", String.class, String[].class); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceClientLiveTest.java index 138ee600e1..91bf8fddc0 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/InstanceClientLiveTest.java @@ -47,7 +47,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.InstanceClientLiveTest") +@Test(groups = "live", sequential = true) public class InstanceClientLiveTest { public static final String PREFIX = System.getProperty("user.name") + "-ec2"; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairAsyncClientTest.java index a58305635a..1edb703530 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairAsyncClientTest.java @@ -38,7 +38,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.KeyPairAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "KeyPairAsyncClientTest") public class KeyPairAsyncClientTest extends BaseEC2AsyncClientTest { public void testDeleteKeyPair() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairClientLiveTest.java index c4857468ff..7fe8f85175 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/KeyPairClientLiveTest.java @@ -49,7 +49,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.KeyPairClientLiveTest") +@Test(groups = "live", sequential = true) public class KeyPairClientLiveTest { private KeyPairClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringAsyncClientTest.java index 5ec3ae5b92..57a12df361 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringAsyncClientTest.java @@ -36,7 +36,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.MonitoringAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "MonitoringAsyncClientTest") public class MonitoringAsyncClientTest extends BaseEC2AsyncClientTest { public void testUnmonitorInstances() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringClientLiveTest.java index 967003ba28..b4e40b240f 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/MonitoringClientLiveTest.java @@ -43,7 +43,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.MonitoringClientLiveTest") +@Test(groups = "live", sequential = true) public class MonitoringClientLiveTest { private MonitoringClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClientTest.java index fc8d17424d..0c7684b640 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupAsyncClientTest.java @@ -38,7 +38,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.PlacementGroupAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "PlacementGroupAsyncClientTest") public class PlacementGroupAsyncClientTest extends BaseEC2AsyncClientTest { public void testDeletePlacementGroup() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java index d13b7aa6f5..acf5600fcc 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java @@ -72,7 +72,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.PlacementGroupClientLiveTest") +@Test(groups = "live", sequential = true) public class PlacementGroupClientLiveTest { private EC2Client client; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClientTest.java index f73d8017de..b5c395b275 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupAsyncClientTest.java @@ -41,7 +41,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.SecurityGroupAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SecurityGroupAsyncClientTest") public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest { public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupClientLiveTest.java index 1925480e90..696da43e19 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/SecurityGroupClientLiveTest.java @@ -55,7 +55,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.SecurityGroupClientLiveTest") +@Test(groups = "live", sequential = true) public class SecurityGroupClientLiveTest { private SecurityGroupClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsAsyncClientTest.java index e88e7a7d20..ed9d48efd1 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsAsyncClientTest.java @@ -38,7 +38,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.WindowsAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "WindowsAsyncClientTest") public class WindowsAsyncClientTest extends BaseEC2AsyncClientTest { public void testBundleInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsClientLiveTest.java index 26b86f665b..48c26ed91a 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/services/WindowsClientLiveTest.java @@ -40,7 +40,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "ec2.WindowsClientLiveTest") +@Test(groups = "live", sequential = true) public class WindowsClientLiveTest { private WindowsClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/utils/EC2UtilsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/utils/EC2UtilsTest.java index be7ce45ba5..7179794cea 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/utils/EC2UtilsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/utils/EC2UtilsTest.java @@ -29,7 +29,7 @@ import com.google.common.collect.ImmutableMap; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.EC2UtilsTest") +@Test(groups = "unit") public class EC2UtilsTest { public void testGetLoadBalancerNameAndRegionFromDnsName() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AllocateAddressResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AllocateAddressResponseHandlerTest.java index c19b129ed5..1da779b980 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AllocateAddressResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AllocateAddressResponseHandlerTest.java @@ -32,7 +32,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.AllocateAddressResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AllocateAddressResponseHandlerTest") public class AllocateAddressResponseHandlerTest extends BaseHandlerTest { public void testApplyInputStream() throws UnknownHostException { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AttachmentHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AttachmentHandlerTest.java index 32a2350e28..aab4436156 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AttachmentHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/AttachmentHandlerTest.java @@ -32,20 +32,22 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; + /** * Tests behavior of {@code AttachmentHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.AttachmentHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AttachmentHandlerTest") public class AttachmentHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { DateService dateService = injector.getInstance(DateService.class); InputStream is = getClass().getResourceAsStream("/ec2/attach.xml"); Attachment expected = new Attachment(defaultRegion, "vol-4d826724", "i-6058a509", "/dev/sdh", - Attachment.Status.ATTACHING, dateService - .iso8601DateParse("2008-05-07T11:51:50.000Z")); + Attachment.Status.ATTACHING, dateService.iso8601DateParse("2008-05-07T11:51:50.000Z")); AttachmentHandler handler = injector.getInstance(AttachmentHandler.class); addDefaultRegionToHandler(handler); @@ -56,7 +58,7 @@ public class AttachmentHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList. of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BaseEC2HandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BaseEC2HandlerTest.java index c8968a0fca..5697967ebf 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BaseEC2HandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BaseEC2HandlerTest.java @@ -29,6 +29,7 @@ import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.config.SaxParserModule; import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.inject.AbstractModule; @@ -39,13 +40,10 @@ import com.google.inject.Provides; * * @author Adrian Cole */ +@Test(groups = "unit") public class BaseEC2HandlerTest extends BaseHandlerTest { protected String defaultRegion = Region.US_EAST_1; - public BaseEC2HandlerTest() { - super(); - } - @BeforeTest @Override protected void setUpInjector() { @@ -68,8 +66,7 @@ public class BaseEC2HandlerTest extends BaseHandlerTest { @Singleton @Provides Map provideAvailabilityZoneRegionMap() { - return ImmutableMap. of(AvailabilityZone.US_EAST_1A, - Region.US_EAST_1); + return ImmutableMap. of(AvailabilityZone.US_EAST_1A, Region.US_EAST_1); } }); factory = injector.getInstance(ParseSax.Factory.class); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BlockDeviceMappingHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BlockDeviceMappingHandlerTest.java index 57f70df565..d0c0f28674 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BlockDeviceMappingHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BlockDeviceMappingHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableMap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.BlockDeviceMappingHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BlockDeviceMappingHandlerTest") public class BlockDeviceMappingHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BundleTaskHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BundleTaskHandlerTest.java index c051f7d029..5279826a6e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BundleTaskHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/BundleTaskHandlerTest.java @@ -32,12 +32,15 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; + /** * Tests behavior of {@code BundleTaskHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.BundleTaskHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BundleTaskHandlerTest") public class BundleTaskHandlerTest extends BaseEC2HandlerTest { public void testBundleInstance() { DateService dateService = injector.getInstance(DateService.class); @@ -70,7 +73,7 @@ public class BundleTaskHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/CreateVolumeResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/CreateVolumeResponseHandlerTest.java index 39783875bd..8bfcf9a8d9 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/CreateVolumeResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/CreateVolumeResponseHandlerTest.java @@ -26,7 +26,6 @@ import static org.testng.Assert.assertEquals; import java.io.InputStream; - import org.jclouds.aws.domain.Region; import org.jclouds.aws.ec2.domain.Attachment; import org.jclouds.aws.ec2.domain.AvailabilityZone; @@ -36,6 +35,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; /** @@ -43,7 +43,8 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.CreateVolumeResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CreateVolumeResponseHandlerTest") public class CreateVolumeResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { @@ -64,7 +65,7 @@ public class CreateVolumeResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAddressesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAddressesResponseHandlerTest.java index b2197e101b..15362f5d95 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAddressesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAddressesResponseHandlerTest.java @@ -40,7 +40,8 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeAddressesResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeAddressesResponseHandlerTest") public class DescribeAddressesResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() throws UnknownHostException { @@ -59,7 +60,7 @@ public class DescribeAddressesResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandlerTest.java index 1e5153eacd..a6be7e4fa3 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeAvailabilityZonesResponseHandlerTest.java @@ -41,7 +41,8 @@ import com.google.inject.Guice; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeAvailabilityZonesResponseHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeAvailabilityZonesResponseHandlerTest") public class DescribeAvailabilityZonesResponseHandlerTest extends BaseHandlerTest { @BeforeTest diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeBundleTasksResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeBundleTasksResponseHandlerTest.java index 8d4e8203df..76c8f97fbb 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeBundleTasksResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeBundleTasksResponseHandlerTest.java @@ -32,6 +32,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; /** @@ -39,7 +40,8 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeBundleTasksResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeBundleTasksResponseHandlerTest") public class DescribeBundleTasksResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { DateService dateService = injector.getInstance(DateService.class); @@ -58,7 +60,7 @@ public class DescribeBundleTasksResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java index 4c51f9329c..5b2277c8c5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java @@ -48,7 +48,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeImagesResponseHandlerTest") +@Test(groups = "unit") public class DescribeImagesResponseHandlerTest { public void testUNIX() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstanceAttributeTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstanceAttributeTest.java index 44ddf3bfb5..f9cac02d8b 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstanceAttributeTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstanceAttributeTest.java @@ -29,11 +29,12 @@ import org.jclouds.http.functions.BaseHandlerTest; import org.testng.annotations.Test; /** - * Tests behavior of {@code InstanceInitiatedShutdownBehaviorHandler}, {@code InstanceTypeHandler} + * Tests behavior of {@code DescribeInstanceAttribute} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeInstanceAttributeTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeInstanceAttributeTest") public class DescribeInstanceAttributeTest extends BaseHandlerTest { public void testInstanceInitiatedShutdownBehaviorHandler() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java index f2d6d4e210..d72ff44389 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java @@ -47,13 +47,13 @@ import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; - /** * Tests behavior of {@code DescribeInstancesResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeInstancesResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeInstancesResponseHandlerTest") public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { private DateService dateService; diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeKeyPairsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeKeyPairsResponseHandlerTest.java index b2f9084479..074b39c28e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeKeyPairsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeKeyPairsResponseHandlerTest.java @@ -32,14 +32,16 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** - * Tests behavior of {@code DescribeKeyPairsHandler} + * Tests behavior of {@code DescribeKeyPairsResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeKeyPairsHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeKeyPairsResponseHandlerTest") public class DescribeKeyPairsResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { @@ -57,7 +59,7 @@ public class DescribeKeyPairsResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribePlacementGroupsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribePlacementGroupsResponseHandlerTest.java index af99771dc2..b66792ea93 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribePlacementGroupsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribePlacementGroupsResponseHandlerTest.java @@ -31,6 +31,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; /** @@ -38,7 +39,8 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribePlacementGroupsResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribePlacementGroupsResponseHandlerTest") public class DescribePlacementGroupsResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { InputStream is = getClass().getResourceAsStream("/ec2/describe_placement_groups.xml"); @@ -55,7 +57,7 @@ public class DescribePlacementGroupsResponseHandlerTest extends BaseEC2HandlerTe private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeRegionsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeRegionsResponseHandlerTest.java index ec6159ebaf..b29418fff5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeRegionsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeRegionsResponseHandlerTest.java @@ -30,7 +30,7 @@ import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.config.SaxParserModule; import org.jclouds.rest.annotations.Provider; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -39,11 +39,12 @@ import com.google.inject.AbstractModule; import com.google.inject.Guice; /** - * Tests behavior of {@code RegionEndpointHandler} + * Tests behavior of {@code DescribeRegionsResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.RegionEndpointHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeRegionsResponseHandlerTest") public class DescribeRegionsResponseHandlerTest extends BaseHandlerTest { @BeforeTest @Override @@ -83,7 +84,7 @@ public class DescribeRegionsResponseHandlerTest extends BaseHandlerTest { public void testEuc() { - InputStream is = Utils + InputStream is = Strings2 .toInputStream("6a3b36f9-9ff4-47cf-87e3-285b08fbe5e5Eucalyptushttp://173.205.188.130:8773/services/EucalyptusWalrushttp://173.205.188.130:8773/services/Walrus"); Map expected = ImmutableMap. of("Eucalyptus", @@ -98,7 +99,7 @@ public class DescribeRegionsResponseHandlerTest extends BaseHandlerTest { public void testEuc2() { - InputStream is = Utils + InputStream is = Strings2 .toInputStream("1LAQRTCLTLPS6CEIC627http://10.255.255.1:8773/services/Cloudnova"); Map expected = ImmutableMap. of("nova", diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeReservedInstancesOfferingResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeReservedInstancesOfferingResponseHandlerTest.java index 4eac3b537c..7aa09571b1 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeReservedInstancesOfferingResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeReservedInstancesOfferingResponseHandlerTest.java @@ -31,6 +31,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; /** @@ -38,7 +39,8 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeReservedInstancesOfferingResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeReservedInstancesOfferingResponseHandlerTest") public class DescribeReservedInstancesOfferingResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { InputStream is = getClass().getResourceAsStream("/ec2/describe_reserved_instances_offerings.xml"); @@ -56,7 +58,7 @@ public class DescribeReservedInstancesOfferingResponseHandlerTest extends BaseEC private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java index cd0995f18a..45c2505c4e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java @@ -35,14 +35,16 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** - * Tests behavior of {@code DescribeSecurityGroupsHandler} + * Tests behavior of {@code DescribeSecurityGroupsResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeSecurityGroupsHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeSecurityGroupsResponseHandlerTest") public class DescribeSecurityGroupsResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { @@ -67,7 +69,7 @@ public class DescribeSecurityGroupsResponseHandlerTest extends BaseEC2HandlerTes private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSnapshotsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSnapshotsResponseHandlerTest.java index 09d9ab065c..71f050e5b9 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSnapshotsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeSnapshotsResponseHandlerTest.java @@ -33,6 +33,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; /** @@ -40,7 +41,8 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeSnapshotsResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeSnapshotsResponseHandlerTest") public class DescribeSnapshotsResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { DateService dateService = injector.getInstance(DateService.class); @@ -61,7 +63,7 @@ public class DescribeSnapshotsResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeVolumesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeVolumesResponseHandlerTest.java index eff6685615..0354b62057 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeVolumesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeVolumesResponseHandlerTest.java @@ -35,6 +35,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; /** @@ -42,7 +43,8 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.DescribeVolumesResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeVolumesResponseHandlerTest") public class DescribeVolumesResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { @@ -70,7 +72,7 @@ public class DescribeVolumesResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/InstanceStateChangeHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/InstanceStateChangeHandlerTest.java index e758636760..378f9a21d7 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/InstanceStateChangeHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/InstanceStateChangeHandlerTest.java @@ -35,6 +35,7 @@ import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** @@ -42,7 +43,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.InstanceStateChangeHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "InstanceStateChangeHandlerTest") public class InstanceStateChangeHandlerTest extends BaseEC2HandlerTest { private DateService dateService; @@ -95,7 +97,7 @@ public class InstanceStateChangeHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/KeyPairResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/KeyPairResponseHandlerTest.java index 08c058bd9c..18376b0d68 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/KeyPairResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/KeyPairResponseHandlerTest.java @@ -31,12 +31,15 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; + /** * Tests behavior of {@code KeyPairResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.KeyPairResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "KeyPairResponseHandlerTest") public class KeyPairResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { @@ -79,7 +82,7 @@ public class KeyPairResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/MonitoringStateHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/MonitoringStateHandlerTest.java index 19fd3451da..4bfeaae3b2 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/MonitoringStateHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/MonitoringStateHandlerTest.java @@ -35,7 +35,8 @@ import com.google.common.collect.ImmutableMap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.MonitoringStateHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "MonitoringStateHandlerTest") public class MonitoringStateHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/PermissionHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/PermissionHandlerTest.java index b214458dac..9f144c1232 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/PermissionHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/PermissionHandlerTest.java @@ -34,7 +34,8 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.PermissionHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "PermissionHandlerTest") public class PermissionHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/ProductCodesHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/ProductCodesHandlerTest.java index 4d38fda062..ba2d9e5fd3 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/ProductCodesHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/ProductCodesHandlerTest.java @@ -34,7 +34,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.ProductCodesHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ProductCodesHandlerTest") public class ProductCodesHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/RunInstancesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/RunInstancesResponseHandlerTest.java index 2612a79735..14da525efa 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/RunInstancesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/RunInstancesResponseHandlerTest.java @@ -40,6 +40,7 @@ import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; @@ -49,7 +50,8 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.RunInstancesResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "RunInstancesResponseHandlerTest") public class RunInstancesResponseHandlerTest extends BaseEC2HandlerTest { private DateService dateService; @@ -94,7 +96,7 @@ public class RunInstancesResponseHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/SnapshotHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/SnapshotHandlerTest.java index 59b31cd0b5..8f7715f1ff 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/SnapshotHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/SnapshotHandlerTest.java @@ -32,12 +32,15 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; + /** * Tests behavior of {@code SnapshotHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.SnapshotHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SnapshotHandlerTest") public class SnapshotHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { DateService dateService = injector.getInstance(DateService.class); @@ -55,7 +58,7 @@ public class SnapshotHandlerTest extends BaseEC2HandlerTest { private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/elb/ELBAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/elb/ELBAsyncClientTest.java index 7626f036da..fa55ef96e4 100644 --- a/aws/core/src/test/java/org/jclouds/aws/elb/ELBAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/elb/ELBAsyncClientTest.java @@ -50,7 +50,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "elb.ELBAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ELBAsyncClientTest") public class ELBAsyncClientTest extends RestClientTest { public void testRegisterInstancesWithLoadBalancer() throws SecurityException, diff --git a/aws/core/src/test/java/org/jclouds/aws/elb/ELBClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/elb/ELBClientLiveTest.java index 8ebe8e32a1..c8580918f2 100644 --- a/aws/core/src/test/java/org/jclouds/aws/elb/ELBClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/elb/ELBClientLiveTest.java @@ -47,7 +47,7 @@ import com.google.inject.Module; * * @author Lili Nader */ -@Test(groups = "live", sequential = true, testName = "ec2.ELBClientLiveTest") +@Test(groups = "live", sequential = true) public class ELBClientLiveTest { private ELBClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/elb/xml/DescribeLoadBalancerResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/elb/xml/DescribeLoadBalancerResponseHandlerTest.java index aeaf909836..6548a018b0 100644 --- a/aws/core/src/test/java/org/jclouds/aws/elb/xml/DescribeLoadBalancerResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/elb/xml/DescribeLoadBalancerResponseHandlerTest.java @@ -33,15 +33,17 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** - * Tests behavior of {@code DescribeLoadBalancersResponseHandler} + * Tests behavior of {@code DescribeLoadBalancerResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "elb.DescribeLoadBalancersResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "DescribeLoadBalancerResponseHandlerTest") public class DescribeLoadBalancerResponseHandlerTest extends BaseEC2HandlerTest { public void testParse() { @@ -68,7 +70,7 @@ public class DescribeLoadBalancerResponseHandlerTest extends BaseEC2HandlerTest private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { null }); + expect(request.getArgs()).andReturn(ImmutableList.of()); replay(request); handler.setContext(request); } diff --git a/aws/core/src/test/java/org/jclouds/aws/elb/xml/RegisterInstancesWithLoadBalancerResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/elb/xml/RegisterInstancesWithLoadBalancerResponseHandlerTest.java index 90016843dc..29710e1ec9 100644 --- a/aws/core/src/test/java/org/jclouds/aws/elb/xml/RegisterInstancesWithLoadBalancerResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/elb/xml/RegisterInstancesWithLoadBalancerResponseHandlerTest.java @@ -30,11 +30,12 @@ import org.testng.annotations.Test; import com.google.common.collect.Sets; /** - * Tests behavior of {@code DescribeLoadBalancersResponseHandler} + * Tests behavior of {@code RegisterInstancesWithLoadBalancerResponseHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.RegisterInstancesWithLoadBalancerResponseHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "RegisterInstancesWithLoadBalancerResponseHandlerTest") public class RegisterInstancesWithLoadBalancerResponseHandlerTest extends BaseEC2HandlerTest { public void testParse() { diff --git a/aws/core/src/test/java/org/jclouds/aws/filters/FormSignerTest.java b/aws/core/src/test/java/org/jclouds/aws/filters/FormSignerTest.java index 46f6cbeb24..92a1099ce4 100644 --- a/aws/core/src/test/java/org/jclouds/aws/filters/FormSignerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/filters/FormSignerTest.java @@ -28,18 +28,23 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableMultimap; import com.google.inject.TypeLiteral; -@Test(groups = "unit", testName = "aws.FormSignerTest") +/** + * Tests behavior of {@code FormSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "FormSignerTest") public class FormSignerTest extends BaseEC2AsyncClientTest { @Test void testBuildCanonicalizedString() { assertEquals( - filter.buildCanonicalizedString(new ImmutableMultimap.Builder().put( - "AWSAccessKeyId", "foo").put("Action", "DescribeImages").put("Expires", - "2008-02-10T12:00:00Z").put("ImageId.1", "ami-2bb65342").put( - "SignatureMethod", "HmacSHA256").put("SignatureVersion", "2").put( - "Version", "2010-06-15").build()), - "AWSAccessKeyId=foo&Action=DescribeImages&Expires=2008-02-10T12%3A00%3A00Z&ImageId.1=ami-2bb65342&SignatureMethod=HmacSHA256&SignatureVersion=2&Version=2010-06-15"); + filter.buildCanonicalizedString(new ImmutableMultimap.Builder() + .put("AWSAccessKeyId", "foo").put("Action", "DescribeImages").put("Expires", "2008-02-10T12:00:00Z") + .put("ImageId.1", "ami-2bb65342").put("SignatureMethod", "HmacSHA256").put("SignatureVersion", "2") + .put("Version", "2010-06-15").build()), + "AWSAccessKeyId=foo&Action=DescribeImages&Expires=2008-02-10T12%3A00%3A00Z&ImageId.1=ami-2bb65342&SignatureMethod=HmacSHA256&SignatureVersion=2&Version=2010-06-15"); } @Override diff --git a/aws/core/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java index 8cbf41c281..20df61ea3d 100644 --- a/aws/core/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java @@ -34,7 +34,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.AWSClientErrorRetryHandlerTest") +@Test(groups = "unit") public class AWSClientErrorRetryHandlerTest { @Test public void test401DoesNotRetry() { diff --git a/aws/core/src/test/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContentTest.java b/aws/core/src/test/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContentTest.java index 0ffba50712..4a5fb34f77 100644 --- a/aws/core/src/test/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContentTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContentTest.java @@ -37,7 +37,7 @@ import org.jclouds.io.Payloads; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.RequestSigner; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.inject.AbstractModule; @@ -142,11 +142,11 @@ public class ParseAWSErrorFromXmlContentTest { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); - HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils + HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Strings2 .toInputStream(content))); response.getPayload().getContentMetadata().setContentType(contentType); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); 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 dc921fe0c4..56fa45581c 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 @@ -32,9 +32,15 @@ import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.google.inject.TypeLiteral; +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") public abstract class BaseS3AsyncClientTest extends RestClientTest { protected BlobToObject blobToS3Object; 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 b8a5e6b2bd..7e09897df1 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 @@ -66,7 +66,7 @@ import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.options.GetOptions; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Supplier; @@ -74,16 +74,17 @@ import com.google.common.collect.ImmutableSet; import com.google.inject.Module; /** - * Tests behavior of {@code S3Client} + * Tests behavior of {@code S3AsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.S3ClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "S3AsyncClientTest") 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"); } @@ -97,12 +98,12 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertPayloadEquals(request, null, null, false); - filter.filter(request); + request = filter.filter(request); 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); @@ -134,9 +135,9 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { 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); @@ -152,9 +153,9 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { 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); @@ -164,8 +165,8 @@ 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()); + Method method = S3AsyncClient.class.getMethod("listBucket", String.class, + Array.newInstance(ListBucketOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "bucket"); assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/ HTTP/1.1"); @@ -196,23 +197,23 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { @Test(expectedExceptions = IllegalArgumentException.class) public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, SecurityException, - IllegalArgumentException, NoSuchMethodException, IOException { + IllegalArgumentException, NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("copyObject", String.class, String.class, String.class, - String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass()); + String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass()); processor.createRequest(method, "sourceBucket", "sourceObject", "destinationBucket", "destinationObject"); } public void testCopyObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { + NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("copyObject", String.class, String.class, String.class, - String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass()); + String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "sourceBucket", "sourceObject", "destinationbucket", - "destinationObject"); + "destinationObject"); 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); @@ -269,7 +270,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } public void testGetObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { + NoSuchMethodException, IOException { Method method = S3AsyncClient.class.getMethod("getObject", String.class, String.class, GetOptions[].class); HttpRequest request = processor.createRequest(method, "bucket", "object"); @@ -354,15 +355,15 @@ 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")); + 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); @@ -372,9 +373,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"); @@ -389,16 +390,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } 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()); + 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); + "EU", + "text/xml", false); assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); assertSaxResponseParserClassEquals(method, null); @@ -408,12 +409,12 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { } public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { + NoSuchMethodException, IOException { Method method = S3AsyncClient.class - .getMethod("putObject", String.class, S3Object.class, PutObjectOptions[].class); - HttpRequest request = processor.createRequest(method, "bucket", blobToS3Object - .apply(BindBlobToMultipartFormTest.TEST_BLOB)); + .getMethod("putObject", String.class, S3Object.class, PutObjectOptions[].class); + HttpRequest request = processor.createRequest(method, "bucket", + blobToS3Object.apply(BindBlobToMultipartFormTest.TEST_BLOB)); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/hello HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); @@ -428,16 +429,16 @@ 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")); + .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); @@ -468,7 +469,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { 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); + "text/xml", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -480,13 +481,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest { 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)))); + .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, Strings2.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/s3/S3ClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/S3ClientLiveTest.java index 302e093249..915b1e9048 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/S3ClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/S3ClientLiveTest.java @@ -50,7 +50,7 @@ import org.jclouds.aws.s3.domain.AccessControlList.Permission; import org.jclouds.aws.s3.options.PutObjectOptions; import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; import org.jclouds.http.HttpResponseException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Throwables; @@ -61,7 +61,7 @@ import com.google.common.collect.Maps; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "s3.S3ClientLiveTest") +@Test(groups = { "integration", "live" }) public class S3ClientLiveTest extends BaseBlobStoreIntegrationTest { public S3Client getApi() { return (S3Client) context.getProviderSpecificContext().getApi(); @@ -98,7 +98,7 @@ public class S3ClientLiveTest extends BaseBlobStoreIntegrationTest { withAcl(CannedAccessPolicy.PUBLIC_READ)); URL url = new URL(String.format("http://%1$s.s3.amazonaws.com/%2$s", containerName, key)); - Utils.toStringAndClose(url.openStream()); + Strings2.toStringAndClose(url.openStream()); } finally { returnContainer(containerName); } @@ -119,7 +119,7 @@ public class S3ClientLiveTest extends BaseBlobStoreIntegrationTest { URL url = new URL(String.format("http://%1$s.s3.amazonaws.com/%2$s", destinationContainer, destinationKey)); - Utils.toStringAndClose(url.openStream()); + Strings2.toStringAndClose(url.openStream()); } finally { returnContainer(containerName); @@ -280,7 +280,7 @@ public class S3ClientLiveTest extends BaseBlobStoreIntegrationTest { assertConsistencyAwareContainerSize(sourceContainer, 1); S3Object newObject = getApi().getObject(sourceContainer, key); assert newObject != null; - assertEquals(Utils.toStringAndClose(newObject.getPayload().getInput()), TEST_STRING); + assertEquals(Strings2.toStringAndClose(newObject.getPayload().getInput()), TEST_STRING); return newObject; } diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfiguredTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfiguredTest.java index 404195589a..799d091dcb 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfiguredTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindAsHostPrefixIfConfiguredTest.java @@ -37,16 +37,16 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.BindAsHostPrefixIfConfiguredTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindAsHostPrefixIfConfiguredTest") public class BindAsHostPrefixIfConfiguredTest extends BaseS3AsyncClientTest { public void testBucket() throws IOException { HttpRequest request = new HttpRequest("GET", URI.create("http://euc/services/Walrus")); - BindAsHostPrefixIfConfigured binder = injector - .getInstance(BindAsHostPrefixIfConfigured.class); + BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class); - binder.bindToRequest(request, "bucket"); + request = binder.bindToRequest(request, "bucket"); assertEquals(request.getRequestLine(), "GET http://euc/services/Walrus/bucket HTTP/1.1"); } @@ -55,20 +55,17 @@ public class BindAsHostPrefixIfConfiguredTest extends BaseS3AsyncClientTest { public void testObject(String key) throws InterruptedException { HttpRequest request = new HttpRequest("GET", URI.create("http://euc/services/Walrus/object")); - BindAsHostPrefixIfConfigured binder = injector - .getInstance(BindAsHostPrefixIfConfigured.class); + BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class); - binder.bindToRequest(request, "bucket"); - assertEquals(request.getRequestLine(), - "GET http://euc/services/Walrus/bucket/object HTTP/1.1"); + request = binder.bindToRequest(request, "bucket"); + assertEquals(request.getRequestLine(), "GET http://euc/services/Walrus/bucket/object HTTP/1.1"); } @DataProvider(name = "objects") public Object[][] createData() { - return new Object[][] { { "normal" }, { "sp ace" }, { "qu?stion" }, { "unic₪de" }, - { "path/foo" }, { "colon:" }, { "asteri*k" }, { "quote\"" }, { "{greaten" }, { "p|pe" } }; + return new Object[][] { { "normal" }, { "sp ace" }, { "qu?stion" }, { "unic₪de" }, { "path/foo" }, + { "colon:" }, { "asteri*k" }, { "quote\"" }, { "{greaten" }, { "p|pe" } }; } @Override diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayloadTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayloadTest.java index f2b88fffb9..9e430b99e9 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayloadTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindBucketLoggingToXmlPayloadTest.java @@ -30,7 +30,7 @@ import org.jclouds.aws.s3.domain.AccessControlList.Grant; import org.jclouds.aws.s3.domain.AccessControlList.Permission; import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.BaseHandlerTest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; @@ -40,7 +40,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.BindBucketLoggingToXmlPayloadTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindBucketLoggingToXmlPayloadTest") public class BindBucketLoggingToXmlPayloadTest extends BaseHandlerTest { public void testApplyInputStream() throws IOException { @@ -49,7 +50,7 @@ public class BindBucketLoggingToXmlPayloadTest extends BaseHandlerTest { . of(new Grant(new EmailAddressGrantee("adrian@jclouds.org"), Permission.FULL_CONTROL))); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream( + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream( "/s3/bucket_logging.xml")); HttpRequest request = new HttpRequest("GET", URI.create("http://test")); diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayloadTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayloadTest.java index f3f10dd5b8..62689885b5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayloadTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindNoBucketLoggingToXmlPayloadTest.java @@ -33,18 +33,18 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.BindNoBucketLoggingToXmlPayloadTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindNoBucketLoggingToXmlPayloadTest") public class BindNoBucketLoggingToXmlPayloadTest extends BaseS3AsyncClientTest { public void testApplyInputStream() throws IOException { HttpRequest request = new HttpRequest("GET", URI.create("http://test")); - BindNoBucketLoggingToXmlPayload binder = injector - .getInstance(BindNoBucketLoggingToXmlPayload.class); + BindNoBucketLoggingToXmlPayload binder = injector.getInstance(BindNoBucketLoggingToXmlPayload.class); - binder.bindToRequest(request, "bucket"); + request = binder.bindToRequest(request, "bucket"); assertEquals(request.getPayload().getRawContent(), - ""); + ""); } } diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequestTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequestTest.java new file mode 100644 index 0000000000..d19a62a5ab --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectMetadataToRequestTest.java @@ -0,0 +1,131 @@ +/** + * + * 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.aws.s3.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.aws.s3.BaseS3AsyncClientTest; +import org.jclouds.aws.s3.domain.S3Object; +import org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix; +import org.jclouds.http.HttpRequest; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMultimap; + +/** + * Tests behavior of {@code BindS3ObjectMetadataToRequest} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindS3ObjectMetadataToRequestTest") +public class BindS3ObjectMetadataToRequestTest extends BaseS3AsyncClientTest { + + @Test + public void testPassWithMinimumDetailsAndPayload5GB() { + S3Object object = injector.getInstance(S3Object.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5368709120l); + object.setPayload(payload); + object.getMetadata().setKey("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); + + assertEquals(binder.bindToRequest(request, object), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build()); + } + + @Test + public void testExtendedPropertiesBind() { + S3Object object = injector.getInstance(S3Object.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5368709120l); + object.setPayload(payload); + object.getMetadata().setKey("foo"); + object.getMetadata().setCacheControl("no-cache"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); + + assertEquals( + binder.bindToRequest(request, object), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")) + .headers(ImmutableMultimap.of("Cache-Control", "no-cache")).build()); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNoContentLengthIsBad() { + S3Object object = injector.getInstance(S3Object.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(null); + object.setPayload(payload); + object.getMetadata().setKey("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); + binder.bindToRequest(request, object); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNoKeyIsBad() { + S3Object object = injector.getInstance(S3Object.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5368709120000l); + object.setPayload(payload); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); + binder.bindToRequest(request, object); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testOver5GBIsBad() { + S3Object object = injector.getInstance(S3Object.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5368709120000l); + object.setPayload(payload); + object.getMetadata().setKey("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); + binder.bindToRequest(request, object); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeS3Object() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + injector.getInstance(BindS3ObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayloadTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayloadTest.java deleted file mode 100644 index 7e6430910c..0000000000 --- a/aws/core/src/test/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayloadTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * - * 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.aws.s3.binders; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import org.jclouds.aws.s3.blobstore.functions.ObjectToBlob; -import org.jclouds.aws.s3.domain.MutableObjectMetadata; -import org.jclouds.aws.s3.domain.S3Object; -import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.http.HttpRequest; -import org.jclouds.io.MutableContentMetadata; -import org.jclouds.io.Payload; -import org.testng.annotations.Test; - -import com.google.common.collect.Multimap; - -/** - * Tests behavior of {@code BindS3ObjectToPayload} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "s3.BindS3ObjectToPayloadTest") -public class BindS3ObjectToPayloadTest { - @Test - public void testPassWithMinimumDetailsAndPayload5GB() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - ObjectToBlob object2Blob = createMock(ObjectToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - S3Object object = createMock(S3Object.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableObjectMetadata md = createMock(MutableObjectMetadata.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - - expect(content.getContentLength()).andReturn(5368709120l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getMetadata()).andReturn(md).atLeastOnce(); - expect(md.getCacheControl()).andReturn(null).atLeastOnce(); - - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindS3ObjectToPayload binder = new BindS3ObjectToPayload(object2Blob, mdBinder); - - binder.bindToRequest(request, object); - - verify(payload); - verify(content); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } - - @SuppressWarnings("unchecked") - @Test - public void testExtendedPropertiesBind() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - ObjectToBlob object2Blob = createMock(ObjectToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - S3Object object = createMock(S3Object.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableObjectMetadata md = createMock(MutableObjectMetadata.class); - Multimap headers = createMock(Multimap.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(content.getContentLength()).andReturn(5368709120l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getMetadata()).andReturn(md).atLeastOnce(); - expect(request.getHeaders()).andReturn(headers).atLeastOnce(); - expect(md.getCacheControl()).andReturn("no-cache").atLeastOnce(); - expect(headers.put("Cache-Control", "no-cache")).andReturn(true); - - replay(headers); - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindS3ObjectToPayload binder = new BindS3ObjectToPayload(object2Blob, mdBinder); - - binder.bindToRequest(request, object); - - verify(headers); - verify(content); - verify(payload); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testOver5GBIsBad() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - ObjectToBlob object2Blob = createMock(ObjectToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - S3Object object = createMock(S3Object.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableObjectMetadata md = createMock(MutableObjectMetadata.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(content.getContentLength()).andReturn(5368709121l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getMetadata()).andReturn(md).atLeastOnce(); - expect(md.getCacheControl()).andReturn(null).atLeastOnce(); - expect(content.getContentDisposition()).andReturn(null).atLeastOnce(); - expect(content.getContentEncoding()).andReturn(null).atLeastOnce(); - - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindS3ObjectToPayload bindS3ObjectToPayload = new BindS3ObjectToPayload(object2Blob, mdBinder); - - bindS3ObjectToPayload.bindToRequest(request, object); - - verify(payload); - verify(content); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } -} diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/S3BlobRequestSignerTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/S3BlobRequestSignerTest.java index 93ef1a7b3a..58619293dd 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/S3BlobRequestSignerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/S3BlobRequestSignerTest.java @@ -45,7 +45,13 @@ import com.google.common.base.Supplier; import com.google.inject.Module; import com.google.inject.TypeLiteral; -@Test(groups = "unit", testName = "s3.S3BlobRequestSignerTest") +/** + * Tests behavior of {@code S3BlobRequestSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "S3BlobRequestSignerTest") public class S3BlobRequestSignerTest extends RestClientTest { private BlobRequestSigner signer; diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/functions/BlobToHttpGetOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/functions/BlobToHttpGetOptionsTest.java index cd957cd0a5..8c02829eaa 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/functions/BlobToHttpGetOptionsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/functions/BlobToHttpGetOptionsTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; -@Test(groups = "unit", testName = "s3.BlobToHttpGetOptionsTest") +@Test(groups = "unit") public class BlobToHttpGetOptionsTest { @Test diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobIntegrationLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobIntegrationLiveTest.java index 2071fd2ccc..65e26b32ee 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobIntegrationLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobIntegrationLiveTest.java @@ -30,7 +30,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "s3.S3BlobIntegrationTest") +@Test(groups = { "live" }) public class S3BlobIntegrationLiveTest extends BaseBlobIntegrationTest { @Override diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobLiveTest.java index 79416d4b3e..834f201d54 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobLiveTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "s3.S3BlobLiveTest") +@Test(groups = { "live" }) public class S3BlobLiveTest extends BaseBlobLiveTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobMapIntegrationLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobMapIntegrationLiveTest.java index d8fd00231e..f3af868a81 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobMapIntegrationLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobMapIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "s3.S3BlobMapIntegrationTest") +@Test(groups = { "live" }) public class S3BlobMapIntegrationLiveTest extends BaseBlobMapIntegrationTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobSignerLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobSignerLiveTest.java index a42b1b4d41..412fe458e4 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobSignerLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3BlobSignerLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "s3.S3BlobSignerLiveTest") +@Test(groups = { "live" }) public class S3BlobSignerLiveTest extends BaseBlobSignerLiveTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerIntegrationLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerIntegrationLiveTest.java index 0fbb2a04a8..00a81d6cb6 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerIntegrationLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerIntegrationLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "s3.S3ContainerIntegrationTest") +@Test(groups = { "live" }) public class S3ContainerIntegrationLiveTest extends BaseContainerIntegrationTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerLiveTest.java index 9482cdf252..e43a3db89a 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ContainerLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "s3.S3ContainerLiveTest") +@Test(groups = { "live" }) public class S3ContainerLiveTest extends BaseContainerLiveTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3InputStreamMapIntegrationLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3InputStreamMapIntegrationLiveTest.java index c3d797bc38..570ccf9726 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3InputStreamMapIntegrationLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3InputStreamMapIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "s3.S3InputStreamMapIntegrationTest") +@Test(groups = { "integration", "live" }) public class S3InputStreamMapIntegrationLiveTest extends BaseInputStreamMapIntegrationTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ServiceIntegrationLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ServiceIntegrationLiveTest.java index 9a0c755d1d..33c589e137 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ServiceIntegrationLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/blobstore/integration/S3ServiceIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = {"live" }, testName = "s3.S3ServiceIntegrationTest") +@Test(groups = {"live" }) public class S3ServiceIntegrationLiveTest extends BaseServiceIntegrationTest { } \ No newline at end of file diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/config/S3RestClientModuleTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/config/S3RestClientModuleTest.java index d496944bd6..f38f0f1ac0 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/config/S3RestClientModuleTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/config/S3RestClientModuleTest.java @@ -43,7 +43,7 @@ import com.google.inject.Injector; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.S3RestClientModuleTest") +@Test(groups = "unit") public class S3RestClientModuleTest { Injector createInjector() throws IOException { diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignatureTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignatureTest.java index 9832691881..663ed634d9 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignatureTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/filters/RequestAuthorizeSignatureTest.java @@ -38,7 +38,13 @@ import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -@Test(groups = "unit", testName = "s3.RequestAuthorizeSignatureTest") +/** + * Tests behavior of {@code RequestAuthorizeSignature} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "RequestAuthorizeSignatureTest") public class RequestAuthorizeSignatureTest extends BaseS3AsyncClientTest { @DataProvider(parallel = true) diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeadersTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeadersTest.java index 4d6135e1f8..2cee19f1ae 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeadersTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/functions/ParseObjectMetadataFromHeadersTest.java @@ -43,6 +43,7 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; /** * @author Adrian Cole @@ -52,14 +53,14 @@ public class ParseObjectMetadataFromHeadersTest { @Test void testNormal() throws Exception { - HttpResponse http = new HttpResponse(400, "boa", Payloads.newStringPayload("")); + HttpResponse http = new HttpResponse(400, "boa", Payloads.newStringPayload(""), ImmutableMultimap.of( + HttpHeaders.CACHE_CONTROL, "cacheControl")); http.getPayload().getContentMetadata().setContentLength(1025l); - - http.getHeaders().put(HttpHeaders.CACHE_CONTROL, "cacheControl"); http.getPayload().getContentMetadata().setContentDisposition("contentDisposition"); http.getPayload().getContentMetadata().setContentEncoding("encoding"); + ParseObjectMetadataFromHeaders parser = new ParseObjectMetadataFromHeaders(blobParser(http, "\"abcd\""), - blobToObjectMetadata, "x-amz-meta-"); + blobToObjectMetadata, "x-amz-meta-"); MutableObjectMetadata response = parser.apply(http); assertEquals(response, expects); } @@ -67,14 +68,14 @@ public class ParseObjectMetadataFromHeadersTest { @Test void testAmzEtag() throws Exception { - HttpResponse http = new HttpResponse(400, "boa", Payloads.newStringPayload("")); + HttpResponse http = new HttpResponse(400, "boa", Payloads.newStringPayload(""), ImmutableMultimap.of( + HttpHeaders.CACHE_CONTROL, "cacheControl", "x-amz-meta-object-eTag", "\"abcd\"")); + http.getPayload().getContentMetadata().setContentLength(1025l); http.getPayload().getContentMetadata().setContentDisposition("contentDisposition"); http.getPayload().getContentMetadata().setContentEncoding("encoding"); - http.getHeaders().put(HttpHeaders.CACHE_CONTROL, "cacheControl"); - http.getHeaders().put("x-amz-meta-object-eTag", "\"abcd\""); ParseObjectMetadataFromHeaders parser = new ParseObjectMetadataFromHeaders(blobParser(http, null), - blobToObjectMetadata, "x-amz-meta-"); + blobToObjectMetadata, "x-amz-meta-"); MutableObjectMetadata response = parser.apply(http); assertEquals(response, expects); } diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/options/CopyObjectOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/options/CopyObjectOptionsTest.java index bfbd9c138b..3e03b9db0c 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/options/CopyObjectOptionsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/options/CopyObjectOptionsTest.java @@ -47,7 +47,7 @@ import com.google.common.collect.Multimap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.CopyObjectOptionsTest") +@Test(groups = "unit") public class CopyObjectOptionsTest { private String etag; diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/options/PutBucketOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/options/PutBucketOptionsTest.java index 92c9cafc8c..43678623ee 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/options/PutBucketOptionsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/options/PutBucketOptionsTest.java @@ -35,7 +35,7 @@ import com.google.common.collect.Multimap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.PutBucketOptionsTest") +@Test(groups = "unit") public class PutBucketOptionsTest { @Test diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/options/PutObjectOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/options/PutObjectOptionsTest.java index 9320f2eb42..1820d1b9f9 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/options/PutObjectOptionsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/options/PutObjectOptionsTest.java @@ -35,7 +35,7 @@ import com.google.common.collect.Multimap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.PutObjectOptionsTest") +@Test(groups = "unit") public class PutObjectOptionsTest { @Test diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/services/BucketsLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/services/BucketsLiveTest.java index da9db89386..7898c867d7 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/services/BucketsLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/services/BucketsLiveTest.java @@ -52,7 +52,7 @@ import org.jclouds.aws.s3.domain.Payer; import org.jclouds.aws.s3.domain.S3Object; import org.jclouds.aws.s3.internal.StubS3AsyncClient; import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Throwables; @@ -64,7 +64,7 @@ import com.google.common.collect.Iterables; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "s3.S3ClientLiveTest") +@Test(groups = { "integration", "live" }) public class BucketsLiveTest extends BaseBlobStoreIntegrationTest { public S3Client getApi() { return (S3Client) context.getProviderSpecificContext().getApi(); @@ -166,7 +166,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest { String bucketName = getContainerName(); try { URL url = new URL(String.format("https://%s.s3.amazonaws.com", bucketName)); - Utils.toStringAndClose(url.openStream()); + Strings2.toStringAndClose(url.openStream()); } finally { returnContainer(bucketName); } diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/xml/AccessControlListHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/xml/AccessControlListHandlerTest.java index f7f1f371a7..0a27cd4edf 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/xml/AccessControlListHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/xml/AccessControlListHandlerTest.java @@ -28,10 +28,16 @@ import org.jclouds.aws.s3.domain.AccessControlList.Permission; import org.jclouds.http.HttpException; import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.ParseSax; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; -@Test(groups = "unit", testName = "s3.AccessControlListHandlerTest") +/** + * Tests behavior of {@code AccessControlListHandler} + * + * @author Adrian Cole + */ +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AccessControlListHandlerTest") public class AccessControlListHandlerTest extends BaseHandlerTest { public static final String aclOwnerOnly = "1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677cjamesmurty1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677cjamesmurtyFULL_CONTROL"; public static final String aclExtreme = "1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677cjamesmurtyhttp://acs.amazonaws.com/groups/global/AuthenticatedUsersWRITEhttp://acs.amazonaws.com/groups/global/AuthenticatedUsersREAD_ACP1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677cjamesmurtyWRITEhttp://acs.amazonaws.com/groups/global/AuthenticatedUsersWRITE_ACPhttp://acs.amazonaws.com/groups/global/AllUsersREADhttp://acs.amazonaws.com/groups/global/AuthenticatedUsersREADhttp://acs.amazonaws.com/groups/s3/LogDeliveryWRITE1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677cjamesmurtyREAD1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677cjamesmurtyFULL_CONTROL"; @@ -45,7 +51,7 @@ public class AccessControlListHandlerTest extends BaseHandlerTest { @Test public void testAccessControlListOwnerOnly() throws HttpException { String ownerId = "1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c"; - AccessControlList acl = createParser().parse(Utils.toInputStream(aclOwnerOnly)); + AccessControlList acl = createParser().parse(Strings2.toInputStream(aclOwnerOnly)); assertEquals(acl.getOwner().getId(), ownerId); assertEquals(acl.getOwner().getDisplayName(), "jamesmurty"); assertEquals(acl.getPermissions(ownerId).size(), 1); @@ -59,7 +65,7 @@ public class AccessControlListHandlerTest extends BaseHandlerTest { @Test public void testAccessControlListExtreme() throws HttpException { String ownerId = "1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c"; - AccessControlList acl = createParser().parse(Utils.toInputStream(aclExtreme)); + AccessControlList acl = createParser().parse(Strings2.toInputStream(aclExtreme)); assertEquals(acl.getOwner().getId(), ownerId); assertEquals(acl.getOwner().getDisplayName(), "jamesmurty"); assertEquals(acl.getPermissions(ownerId).size(), 3); diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/xml/BucketLoggingHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/xml/BucketLoggingHandlerTest.java index b6f308064d..9c59f64249 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/xml/BucketLoggingHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/xml/BucketLoggingHandlerTest.java @@ -23,10 +23,10 @@ import static org.testng.Assert.assertEquals; import java.io.InputStream; -import org.jclouds.aws.s3.domain.BucketLogging; import org.jclouds.aws.s3.domain.AccessControlList.EmailAddressGrantee; import org.jclouds.aws.s3.domain.AccessControlList.Grant; import org.jclouds.aws.s3.domain.AccessControlList.Permission; +import org.jclouds.aws.s3.domain.BucketLogging; import org.jclouds.http.functions.BaseHandlerTest; import org.testng.annotations.Test; @@ -37,14 +37,14 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.BucketLoggingHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BucketLoggingHandlerTest") public class BucketLoggingHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { InputStream is = getClass().getResourceAsStream("/s3/bucket_logging.xml"); - BucketLogging expected = new BucketLogging("mylogs", "access_log-", ImmutableSet - . of(new Grant(new EmailAddressGrantee("adrian@jclouds.org"), - Permission.FULL_CONTROL))); + BucketLogging expected = new BucketLogging("mylogs", "access_log-", ImmutableSet. of(new Grant( + new EmailAddressGrantee("adrian@jclouds.org"), Permission.FULL_CONTROL))); BucketLoggingHandler handler = injector.getInstance(BucketLoggingHandler.class); BucketLogging result = factory.create(handler).parse(is); diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/xml/CopyObjectHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/xml/CopyObjectHandlerTest.java index 829fe967ac..2d31aded32 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/xml/CopyObjectHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/xml/CopyObjectHandlerTest.java @@ -36,7 +36,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "s3.CopyObjectHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CopyObjectHandlerTest") public class CopyObjectHandlerTest extends BaseHandlerTest { private DateService dateService; diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/xml/ListBucketHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/xml/ListBucketHandlerTest.java index 2b38657309..af48823b0b 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/xml/ListBucketHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/xml/ListBucketHandlerTest.java @@ -35,13 +35,19 @@ import org.jclouds.date.DateService; import org.jclouds.http.HttpException; import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.ParseSax; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; -@Test(groups = "unit", testName = "s3.ListBucketHandlerTest") +/** + * Tests behavior of {@code ListBucketHandler} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ListBucketHandlerTest") public class ListBucketHandlerTest extends BaseHandlerTest { public static final String listBucketWithPrefixAppsSlash = "adriancole.org.jclouds.aws.s3.amazons3testdelimiterapps/1000falseapps/02009-05-07T18:27:08.000Z"c82e6a0025c31c5de5947fda62ac51ab"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/12009-05-07T18:27:09.000Z"944fab2c5a9a6bacf07db5e688310d7a"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/22009-05-07T18:27:09.000Z"a227b8888045c8fd159fb495214000f0"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/32009-05-07T18:27:09.000Z"c9caa76c3dec53e2a192608ce73eef03"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/42009-05-07T18:27:09.000Z"1ce5d0dcc6154a647ea90c7bdf82a224"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/52009-05-07T18:27:09.000Z"79433524d87462ee05708a8ef894ed55"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/62009-05-07T18:27:10.000Z"dd00a060b28ddca8bc5a21a49e306f67"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/72009-05-07T18:27:10.000Z"8cd06eca6e819a927b07a285d750b100"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/82009-05-07T18:27:10.000Z"174495094d0633b92cbe46603eee6bad"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/92009-05-07T18:27:10.000Z"cd8a19b26fea8a827276df0ad11c580d"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARD"; public static final String listBucketWithSlashDelimiterAndCommonPrefixApps = " / apps/"; @@ -58,62 +64,50 @@ public class ListBucketHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { InputStream is = getClass().getResourceAsStream("/s3/list_bucket.xml"); CanonicalUser owner = new CanonicalUser("e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0", - "ferncam"); + "ferncam"); ListBucketResponse expected = new ListBucketResponseImpl("adriancole.org.jclouds.aws.s3.amazons3testdelimiter", - ImmutableList - .of( - (ObjectMetadata) new BucketListObjectMetadata("apps/0", dateService - .iso8601DateParse("2009-05-07T18:27:08.000Z"), - "\"c82e6a0025c31c5de5947fda62ac51ab\"", CryptoStreams - .hex("c82e6a0025c31c5de5947fda62ac51ab"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/1", dateService.iso8601DateParse("2009-05-07T18:27:09.000Z"), - "\"944fab2c5a9a6bacf07db5e688310d7a\"", CryptoStreams - .hex("944fab2c5a9a6bacf07db5e688310d7a"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/2", dateService.iso8601DateParse("2009-05-07T18:27:09.000Z"), - "\"a227b8888045c8fd159fb495214000f0\"", CryptoStreams - .hex("a227b8888045c8fd159fb495214000f0"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/3", dateService.iso8601DateParse("2009-05-07T18:27:09.000Z"), - "\"c9caa76c3dec53e2a192608ce73eef03\"", CryptoStreams - .hex("c9caa76c3dec53e2a192608ce73eef03"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/4", dateService.iso8601DateParse("2009-05-07T18:27:09.000Z"), - "\"1ce5d0dcc6154a647ea90c7bdf82a224\"", CryptoStreams - .hex("1ce5d0dcc6154a647ea90c7bdf82a224"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/5", dateService.iso8601DateParse("2009-05-07T18:27:09.000Z"), - "\"79433524d87462ee05708a8ef894ed55\"", CryptoStreams - .hex("79433524d87462ee05708a8ef894ed55"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/6", dateService.iso8601DateParse("2009-05-07T18:27:10.000Z"), - "\"dd00a060b28ddca8bc5a21a49e306f67\"", CryptoStreams - .hex("dd00a060b28ddca8bc5a21a49e306f67"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/7", dateService.iso8601DateParse("2009-05-07T18:27:10.000Z"), - "\"8cd06eca6e819a927b07a285d750b100\"", CryptoStreams - .hex("8cd06eca6e819a927b07a285d750b100"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/8", dateService.iso8601DateParse("2009-05-07T18:27:10.000Z"), - "\"174495094d0633b92cbe46603eee6bad\"", CryptoStreams - .hex("174495094d0633b92cbe46603eee6bad"), 8, owner, - StorageClass.STANDARD), (ObjectMetadata) new BucketListObjectMetadata( - "apps/9", dateService.iso8601DateParse("2009-05-07T18:27:10.000Z"), - "\"cd8a19b26fea8a827276df0ad11c580d\"", CryptoStreams - .hex("cd8a19b26fea8a827276df0ad11c580d"), 8, owner, - StorageClass.STANDARD)), "apps/", null, null, 1000, null, false, - new TreeSet()); + ImmutableList.of( + (ObjectMetadata) new BucketListObjectMetadata("apps/0", dateService + .iso8601DateParse("2009-05-07T18:27:08.000Z"), "\"c82e6a0025c31c5de5947fda62ac51ab\"", + CryptoStreams.hex("c82e6a0025c31c5de5947fda62ac51ab"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/1", dateService + .iso8601DateParse("2009-05-07T18:27:09.000Z"), "\"944fab2c5a9a6bacf07db5e688310d7a\"", + CryptoStreams.hex("944fab2c5a9a6bacf07db5e688310d7a"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/2", dateService + .iso8601DateParse("2009-05-07T18:27:09.000Z"), "\"a227b8888045c8fd159fb495214000f0\"", + CryptoStreams.hex("a227b8888045c8fd159fb495214000f0"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/3", dateService + .iso8601DateParse("2009-05-07T18:27:09.000Z"), "\"c9caa76c3dec53e2a192608ce73eef03\"", + CryptoStreams.hex("c9caa76c3dec53e2a192608ce73eef03"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/4", dateService + .iso8601DateParse("2009-05-07T18:27:09.000Z"), "\"1ce5d0dcc6154a647ea90c7bdf82a224\"", + CryptoStreams.hex("1ce5d0dcc6154a647ea90c7bdf82a224"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/5", dateService + .iso8601DateParse("2009-05-07T18:27:09.000Z"), "\"79433524d87462ee05708a8ef894ed55\"", + CryptoStreams.hex("79433524d87462ee05708a8ef894ed55"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/6", dateService + .iso8601DateParse("2009-05-07T18:27:10.000Z"), "\"dd00a060b28ddca8bc5a21a49e306f67\"", + CryptoStreams.hex("dd00a060b28ddca8bc5a21a49e306f67"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/7", dateService + .iso8601DateParse("2009-05-07T18:27:10.000Z"), "\"8cd06eca6e819a927b07a285d750b100\"", + CryptoStreams.hex("8cd06eca6e819a927b07a285d750b100"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/8", dateService + .iso8601DateParse("2009-05-07T18:27:10.000Z"), "\"174495094d0633b92cbe46603eee6bad\"", + CryptoStreams.hex("174495094d0633b92cbe46603eee6bad"), 8, owner, StorageClass.STANDARD), + (ObjectMetadata) new BucketListObjectMetadata("apps/9", dateService + .iso8601DateParse("2009-05-07T18:27:10.000Z"), "\"cd8a19b26fea8a827276df0ad11c580d\"", + CryptoStreams.hex("cd8a19b26fea8a827276df0ad11c580d"), 8, owner, StorageClass.STANDARD)), + "apps/", null, null, 1000, null, false, new TreeSet()); ListBucketResponse result = (ListBucketResponse) factory.create(injector.getInstance(ListBucketHandler.class)) - .parse(is); + .parse(is); assertEquals(result, expected); } ParseSax createParser() { ParseSax parser = (ParseSax) factory.create(injector - .getInstance(ListBucketHandler.class)); + .getInstance(ListBucketHandler.class)); return parser; } @@ -121,7 +115,7 @@ public class ListBucketHandlerTest extends BaseHandlerTest { public void testListMyBucketsWithDelimiterSlashAndCommonPrefixesAppsSlash() throws HttpException { ListBucketResponse bucket = createParser().parse( - Utils.toInputStream(listBucketWithSlashDelimiterAndCommonPrefixApps)); + Strings2.toInputStream(listBucketWithSlashDelimiterAndCommonPrefixApps)); assertEquals(bucket.getCommonPrefixes().iterator().next(), "apps/"); assertEquals(bucket.getDelimiter(), "/"); assert bucket.getMarker() == null; @@ -130,7 +124,7 @@ public class ListBucketHandlerTest extends BaseHandlerTest { @Test public void testListMyBucketsWithPrefixAppsSlash() throws HttpException { - ListBucketResponse bucket = createParser().parse(Utils.toInputStream(listBucketWithPrefixAppsSlash)); + ListBucketResponse bucket = createParser().parse(Strings2.toInputStream(listBucketWithPrefixAppsSlash)); assertEquals(bucket.getPrefix(), "apps/"); assertEquals(bucket.getMaxKeys(), 1000); assert bucket.getMarker() == null; diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/xml/PayerHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/xml/PayerHandlerTest.java index 9d38e7f83b..9690932063 100644 --- a/aws/core/src/test/java/org/jclouds/aws/s3/xml/PayerHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/xml/PayerHandlerTest.java @@ -25,10 +25,16 @@ import org.jclouds.aws.s3.domain.Payer; import org.jclouds.http.HttpException; import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.ParseSax; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; -@Test(groups = "unit", testName = "s3.PayerHandlerTest") +/** + * Tests behavior of {@code PayerHandler} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "PayerHandlerTest") public class PayerHandlerTest extends BaseHandlerTest { ParseSax createParser() { @@ -41,7 +47,7 @@ public class PayerHandlerTest extends BaseHandlerTest { public void testPayerRequester() throws HttpException { Payer payer = createParser() .parse( - Utils + Strings2 .toInputStream("Requester")); assertEquals(payer, Payer.REQUESTER); @@ -51,7 +57,7 @@ public class PayerHandlerTest extends BaseHandlerTest { public void testPayerBucketOwner() throws HttpException { Payer payer = createParser() .parse( - Utils + Strings2 .toInputStream("BucketOwner")); assertEquals(payer, Payer.BUCKET_OWNER); diff --git a/aws/core/src/test/java/org/jclouds/aws/s3/xml/S3ParserTest.java b/aws/core/src/test/java/org/jclouds/aws/s3/xml/S3ParserTest.java index 744c7b7e7f..7a61269b23 100755 --- a/aws/core/src/test/java/org/jclouds/aws/s3/xml/S3ParserTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/s3/xml/S3ParserTest.java @@ -40,7 +40,7 @@ import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.http.HttpException; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.config.SaxParserModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -55,7 +55,8 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = { "performance" }, testName = "s3.S3ParserTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "S3ParserTest") public class S3ParserTest extends PerformanceTest { Injector injector = null; ParseSax.Factory factory; @@ -83,7 +84,7 @@ public class S3ParserTest extends PerformanceTest { private Set runParseListAllMyBuckets() throws HttpException { return factory.create(injector.getInstance(ListAllMyBucketsHandler.class)).parse( - Utils.toInputStream(listAllMyBucketsResultOn200)); + Strings2.toInputStream(listAllMyBucketsResultOn200)); } @Test @@ -140,14 +141,14 @@ public class S3ParserTest extends PerformanceTest { private ListBucketResponse runParseListContainerResult() throws HttpException { return (ListBucketResponse) factory.create(injector.getInstance(ListBucketHandler.class)).parse( - Utils.toInputStream(listContainerResult)); + Strings2.toInputStream(listContainerResult)); } public static final String successfulCopyObject200 = "2009-03-19T13:23:27.000Z\"92836a3ea45a6984d1b4d23a747d46bb\""; private ObjectMetadata runParseCopyObjectResult() throws HttpException { return (ObjectMetadata) factory.create(injector.getInstance(CopyObjectHandler.class)).parse( - Utils.toInputStream(successfulCopyObject200)); + Strings2.toInputStream(successfulCopyObject200)); } public void testCanParseCopyObjectResult() throws HttpException, UnsupportedEncodingException { diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java index 47e8d470b5..947dd6ec7c 100644 --- a/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java @@ -49,7 +49,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "simpledb.SimpleDBAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SimpleDBAsyncClientTest") public class SimpleDBAsyncClientTest extends RestClientTest { @RequiresHttp diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java index cfb5ae5d21..0310616ed5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java @@ -46,7 +46,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "simpledb.SimpleDBClientLiveTest") +@Test(groups = "live", sequential = true) public class SimpleDBClientLiveTest { private SimpleDBClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java index e7ada93906..d844879ecf 100644 --- a/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java @@ -44,7 +44,7 @@ import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "simpledb.SimpleDBRestClientModuleTest") +@Test(groups = "unit") public class SimpleDBRestClientModuleTest { Injector createInjector() { diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java index 2dbc2517be..d1d46b72a2 100644 --- a/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java @@ -34,7 +34,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "simpledb.ListDomainsResponseHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ListDomainsResponseHandlerTest") public class ListDomainsResponseHandlerTest extends BaseHandlerTest { public void test() { 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 0db2cac132..d9f352b365 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 @@ -57,7 +57,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "sqs.SQSAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SQSAsyncClientTest") public class SQSAsyncClientTest extends RestClientTest { @RequiresHttp diff --git a/aws/core/src/test/java/org/jclouds/aws/sqs/SQSClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/sqs/SQSClientLiveTest.java index 53b57d3186..fc856c9c2e 100644 --- a/aws/core/src/test/java/org/jclouds/aws/sqs/SQSClientLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/sqs/SQSClientLiveTest.java @@ -51,7 +51,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "sqs.SQSClientLiveTest") +@Test(groups = "live", sequential = true) public class SQSClientLiveTest { private SQSClient client; diff --git a/aws/core/src/test/java/org/jclouds/aws/sqs/config/SQSRestClientModuleTest.java b/aws/core/src/test/java/org/jclouds/aws/sqs/config/SQSRestClientModuleTest.java index 9c1262f564..26711f681d 100644 --- a/aws/core/src/test/java/org/jclouds/aws/sqs/config/SQSRestClientModuleTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/sqs/config/SQSRestClientModuleTest.java @@ -44,7 +44,7 @@ import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "sqs.SQSRestClientModuleTest") +@Test(groups = "unit") public class SQSRestClientModuleTest { Injector createInjector() { diff --git a/aws/core/src/test/java/org/jclouds/aws/sqs/xml/ListQueuesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/sqs/xml/ListQueuesResponseHandlerTest.java index 392e3ee599..feec50e4cd 100644 --- a/aws/core/src/test/java/org/jclouds/aws/sqs/xml/ListQueuesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/sqs/xml/ListQueuesResponseHandlerTest.java @@ -61,7 +61,8 @@ import com.sun.jersey.api.uri.UriBuilderImpl; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "sqs.ListQueuesResponseHandlerrTest") +// NOTE:without testName, this will fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "ListQueuesResponseHandlerTest") public class ListQueuesResponseHandlerTest extends PerformanceTest { private Injector injector; diff --git a/aws/core/src/test/java/org/jclouds/aws/util/AWSUtilsTest.java b/aws/core/src/test/java/org/jclouds/aws/util/AWSUtilsTest.java index 67029eef17..7998b4ff63 100644 --- a/aws/core/src/test/java/org/jclouds/aws/util/AWSUtilsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/util/AWSUtilsTest.java @@ -34,12 +34,13 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; import org.jclouds.logging.config.NullLoggingModule; -import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.BaseRestClientTest.MockModule; +import org.jclouds.rest.RestContextFactory; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.inject.Injector; @@ -48,7 +49,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(sequential = true, groups = { "unit" }, testName = "aws.AWSUtilsTest") +@Test(sequential = true, groups = { "unit" }) public class AWSUtilsTest { AWSUtils utils = null; private HttpCommand command; @@ -57,12 +58,12 @@ public class AWSUtilsTest { protected void setUpInjector() throws IOException { Injector injector = new RestContextFactory().createContextBuilder("s3", "foo", "bar", - ImmutableSet.of(new MockModule(), new NullLoggingModule()), new Properties()).buildInjector(); + ImmutableSet.of(new MockModule(), new NullLoggingModule()), new Properties()).buildInjector(); utils = injector.getInstance(AWSUtils.class); command = createMock(HttpCommand.class); - expect(command.getRequest()).andReturn(createMock(HttpRequest.class)).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(createMock(HttpRequest.class)).atLeastOnce(); replay(command); } @@ -72,17 +73,16 @@ public class AWSUtilsTest { } HttpResponse response(InputStream content) { - HttpResponse response = new HttpResponse(400, "boa", Payloads.newInputStreamPayload(content)); + HttpResponse response = new HttpResponse(400, "boa", Payloads.newInputStreamPayload(content), + ImmutableMultimap. of("x-amz-request-id", "requestid", "x-amz-id-2", "requesttoken")); response.getPayload().getContentMetadata().setContentType("text/xml"); - response.getHeaders().put("x-amz-request-id", "requestid"); - response.getHeaders().put("x-amz-id-2", "requesttoken"); return response; } @Test public void testParseAWSErrorFromContentHttpCommandHttpResponseInputStream() { - AWSError error = utils.parseAWSErrorFromContent(command.getRequest(), response(getClass().getResourceAsStream( - "/error.xml"))); + AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response(getClass() + .getResourceAsStream("/error.xml"))); assertEquals(error.getCode(), "NoSuchKey"); assertEquals(error.getMessage(), "The resource you requested does not exist"); assertEquals(error.getRequestToken(), "requesttoken"); diff --git a/aws/core/src/test/java/org/jclouds/aws/xml/ErrorHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/xml/ErrorHandlerTest.java index dabd1c7a38..4d2c4b2d21 100755 --- a/aws/core/src/test/java/org/jclouds/aws/xml/ErrorHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/xml/ErrorHandlerTest.java @@ -25,10 +25,16 @@ import org.jclouds.aws.domain.AWSError; import org.jclouds.http.HttpException; import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.ParseSax; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; -@Test(groups = "unit", testName = "s3.ErrorHandlerTest") +/** + * Tests behavior of {@code ErrorHandler} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ErrorHandlerTest") public class ErrorHandlerTest extends BaseHandlerTest { public static final String errorFromAmazonIfYouDontRemoveTransferEncodingHeader = "NotImplementedA header you provided implies functionality that is not implemented
Transfer-Encoding
7C59925D75D15561fbskVU51OZJg2yZS/wNIxoE2PmCf0ZqFd0iH6Vrzw0uKG3KmokswBytL/Bfp/GWb
"; @@ -40,7 +46,7 @@ public class ErrorHandlerTest extends BaseHandlerTest { @Test public void testErrorFromAmazonIfYouDontRemoveTransferEncodingHeader() throws HttpException { ParseSax parser = createParser(); - AWSError error = parser.parse(Utils.toInputStream(errorFromAmazonIfYouDontRemoveTransferEncodingHeader)); + AWSError error = parser.parse(Strings2.toInputStream(errorFromAmazonIfYouDontRemoveTransferEncodingHeader)); assertEquals(error.getCode(), "NotImplemented"); assertEquals(error.getMessage(), "A header you provided implies functionality that is not implemented"); assertEquals(error.getDetails().get("Header"), "Transfer-Encoding"); @@ -51,7 +57,7 @@ public class ErrorHandlerTest extends BaseHandlerTest { public void testErrorFromEucalyptusWhenGroupAlreadyExists() throws HttpException { ParseSax parser = createParser(); AWSError error = parser - .parse(Utils + .parse(Strings2 .toInputStream("Groups\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists\nError adding network group: group named jclouds#eucrun#Eucalyptus already existse0133975-3bc5-456d-9753-1d61b27e07e9")); assertEquals(error.getCode(), "Groups"); assertEquals( diff --git a/aws/demos/googleappengine/src/test/java/org/jclouds/samples/googleappengine/functest/GoogleAppEngineLiveTest.java b/aws/demos/googleappengine/src/test/java/org/jclouds/samples/googleappengine/functest/GoogleAppEngineLiveTest.java index 8a7543fc20..5c2c73068d 100755 --- a/aws/demos/googleappengine/src/test/java/org/jclouds/samples/googleappengine/functest/GoogleAppEngineLiveTest.java +++ b/aws/demos/googleappengine/src/test/java/org/jclouds/samples/googleappengine/functest/GoogleAppEngineLiveTest.java @@ -26,7 +26,7 @@ import java.io.InputStream; import java.net.URL; import java.util.Properties; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @@ -37,7 +37,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "functionalTests") +@Test(groups = "live", sequential = true) public class GoogleAppEngineLiveTest { GoogleDevServer server; @@ -68,7 +68,7 @@ public class GoogleAppEngineLiveTest { @Test public void shouldPass() throws InterruptedException, IOException { InputStream i = url.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Welcome") >= 0 : string; } @@ -76,7 +76,7 @@ public class GoogleAppEngineLiveTest { public void testGuiceJCloudsSerial() throws InterruptedException, IOException { URL gurl = new URL(url, "/guice/status.check"); InputStream i = gurl.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("List") >= 0 : string; } @@ -84,7 +84,7 @@ public class GoogleAppEngineLiveTest { public void testGuiceJCloudsParallel() throws InterruptedException, IOException { URL gurl = new URL(url, "/guice/status.check"); InputStream i = gurl.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("List") >= 0 : string; } } diff --git a/aws/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java b/aws/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java index a60a85d361..bd889d1a28 100755 --- a/aws/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java +++ b/aws/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java @@ -42,7 +42,7 @@ import com.amazonaws.services.s3.model.PutObjectRequest; * * @author Adrian Cole */ -@Test(sequential = true, timeOut = 2 * 60 * 1000, testName = "perftest.AmazonPerformanceLiveTest", groups = { "live" }) +@Test(sequential = true, timeOut = 2 * 60 * 1000, groups = { "live" }) public class AmazonPerformanceLiveTest extends BasePerformanceLiveTest { private AmazonS3 s3; diff --git a/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java b/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java index a049e7fe13..a72c965014 100644 --- a/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java +++ b/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java @@ -39,7 +39,7 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; -@Test(sequential = true, testName = "perftest.JCloudsApacheHCPerformanceLiveTest", groups = { "live" }) +@Test(sequential = true, groups = { "live" }) public class JCloudsApacheHCPerformanceLiveTest extends BaseJCloudsPerformanceLiveTest { @Override diff --git a/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java b/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java index 835a9680bb..d1479e06e7 100755 --- a/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java +++ b/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java @@ -45,7 +45,7 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(enabled = false, sequential = true, testName = "perftest.JCloudsGaePerformanceLiveTest", groups = { "disabled" }) +@Test(enabled = false, sequential = true, groups = { "disabled" }) public class JCloudsGaePerformanceLiveTest extends BaseJCloudsPerformanceLiveTest { @Override diff --git a/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java b/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java index 66f988f21d..32e5e1ed44 100755 --- a/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java +++ b/aws/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java @@ -42,7 +42,7 @@ import com.google.common.collect.ImmutableSet; * @author Adrian Cole * */ -@Test(sequential = true, timeOut = 2 * 60 * 1000, testName = "perftest.JCloudsPerformanceLiveTest", groups = { "live" }) +@Test(sequential = true, timeOut = 2 * 60 * 1000, groups = { "live" }) public class JCloudsPerformanceLiveTest extends BaseJCloudsPerformanceLiveTest { @Override diff --git a/aws/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java b/aws/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java index e03314ecf7..51e15e5d31 100755 --- a/aws/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java +++ b/aws/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java @@ -41,7 +41,7 @@ import com.google.appengine.repackaged.com.google.common.base.Throwables; * * @author Adrian Cole */ -@Test(sequential = true, timeOut = 2 * 60 * 1000, testName = "perftest.Jets3tPerformanceLiveTest", groups = { "live" }) +@Test(sequential = true, timeOut = 2 * 60 * 1000, groups = { "live" }) public class Jets3tPerformanceLiveTest extends BasePerformanceLiveTest { private S3Service jetClient; diff --git a/azure/src/main/java/org/jclouds/azure/storage/AzureStoragePropertiesBuilder.java b/azure/src/main/java/org/jclouds/azure/storage/AzureStoragePropertiesBuilder.java index bdea7349bb..328d3b4290 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/AzureStoragePropertiesBuilder.java +++ b/azure/src/main/java/org/jclouds/azure/storage/AzureStoragePropertiesBuilder.java @@ -28,7 +28,7 @@ import java.util.Properties; import java.util.regex.Pattern; import org.jclouds.PropertiesBuilder; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * Builds properties used in AzureBlob Connections @@ -59,7 +59,7 @@ public class AzureStoragePropertiesBuilder extends PropertiesBuilder { String endpoint = properties.getProperty(PROPERTY_ENDPOINT); String identity = properties.getProperty(PROPERTY_IDENTITY); - properties.setProperty(PROPERTY_ENDPOINT, Utils.replaceAll(endpoint, IDENTITY_PATTERN, + properties.setProperty(PROPERTY_ENDPOINT, Strings2.replaceAll(endpoint, IDENTITY_PATTERN, identity)); return super.build(); } diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClient.java b/azure/src/main/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClient.java index aea4257808..a809d3e099 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClient.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/AzureBlobAsyncClient.java @@ -29,7 +29,7 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; -import org.jclouds.azure.storage.blob.binders.BindAzureBlobToPayload; +import org.jclouds.azure.storage.blob.binders.BindAzureBlobMetadataToRequest; import org.jclouds.azure.storage.blob.domain.BlobProperties; import org.jclouds.azure.storage.blob.domain.ContainerProperties; import org.jclouds.azure.storage.blob.domain.ListBlobsResponse; @@ -93,7 +93,6 @@ public interface AzureBlobAsyncClient { */ @GET @XMLResponseParser(AccountNameEnumerationResultsHandler.class) - @Path("") @QueryParams(keys = "comp", values = "list") ListenableFuture> listContainers( ListOptions... listOptions); @@ -196,7 +195,7 @@ public interface AzureBlobAsyncClient { @ResponseParser(ParseETagHeader.class) ListenableFuture putBlob( @PathParam("container") @ParamValidators( { ContainerNameValidator.class }) String container, - @PathParam("name") @ParamParser(BlobName.class) @BinderParam(BindAzureBlobToPayload.class) org.jclouds.azure.storage.blob.domain.AzureBlob object); + @PathParam("name") @ParamParser(BlobName.class) @BinderParam(BindAzureBlobMetadataToRequest.class) org.jclouds.azure.storage.blob.domain.AzureBlob object); /** * @see AzureBlobClient#getBlob diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequest.java b/azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequest.java new file mode 100644 index 0000000000..d5265f5aca --- /dev/null +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequest.java @@ -0,0 +1,80 @@ +/** + * + * 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.azure.storage.blob.binders; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.azure.storage.blob.blobstore.functions.AzureBlobToBlob; +import org.jclouds.azure.storage.blob.domain.AzureBlob; +import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; +import org.jclouds.rest.Binder; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Multimaps; + +@Singleton +public class BindAzureBlobMetadataToRequest implements Binder { + + private final AzureBlobToBlob azureBlob2Blob; + private final BindUserMetadataToHeadersWithPrefix blobBinder; + + @Inject + public BindAzureBlobMetadataToRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { + this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob"); + this.blobBinder = checkNotNull(blobBinder, "blobBinder"); + } + + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof AzureBlob, "this binder is only valid for AzureBlobs!"); + checkNotNull(request, "request"); + AzureBlob blob = AzureBlob.class.cast(input); + + checkArgument(blob.getPayload().getContentMetadata().getContentLength() != null + && blob.getPayload().getContentMetadata().getContentLength() >= 0, "size must be set"); + + Builder headers = ImmutableMap. builder(); + + headers.put("x-ms-blob-type", blob.getProperties().getType().toString()); + + switch (blob.getProperties().getType()) { + case PAGE_BLOB: + headers.put(HttpHeaders.CONTENT_LENGTH, "0"); + headers.put("x-ms-blob-content-length", blob.getPayload().getContentMetadata().getContentLength().toString()); + break; + case BLOCK_BLOB: + checkArgument( + checkNotNull(blob.getPayload().getContentMetadata().getContentLength(), "blob.getContentLength()") <= 64l * 1024 * 1024, + "maximum size for put Blob is 64MB"); + break; + } + request = ModifyRequest.putHeaders(request, Multimaps.forMap(headers.build())); + + return blobBinder.bindToRequest(request, azureBlob2Blob.apply(blob)); + } +} diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayload.java b/azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayload.java deleted file mode 100644 index 640a303635..0000000000 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayload.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * - * 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.azure.storage.blob.binders; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.ws.rs.core.HttpHeaders; - -import org.jclouds.azure.storage.blob.blobstore.functions.AzureBlobToBlob; -import org.jclouds.azure.storage.blob.domain.AzureBlob; -import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.Binder; - -@Singleton -public class BindAzureBlobToPayload implements Binder { - - private final AzureBlobToBlob azureBlob2Blob; - private final BindUserMetadataToHeadersWithPrefix blobBinder; - - @Inject - public BindAzureBlobToPayload(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { - this.azureBlob2Blob = azureBlob2Blob; - this.blobBinder = blobBinder; - } - - public void bindToRequest(HttpRequest request, Object payload) { - AzureBlob blob = (AzureBlob) payload; - checkArgument(blob.getPayload().getContentMetadata().getContentLength() != null - && blob.getPayload().getContentMetadata().getContentLength() >= 0, "size must be set"); - request.getHeaders().put("x-ms-blob-type", blob.getProperties().getType().toString()); - - switch (blob.getProperties().getType()) { - case PAGE_BLOB: - request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, "0"); - request.getHeaders().put("x-ms-blob-content-length", - blob.getPayload().getContentMetadata().getContentLength().toString()); - break; - case BLOCK_BLOB: - checkArgument(checkNotNull(blob.getPayload().getContentMetadata().getContentLength(), - "blob.getContentLength()") <= 64l * 1024 * 1024, "maximum size for put Blob is 64MB"); - break; - } - blobBinder.bindToRequest(request, azureBlob2Blob.apply(blob)); - } -} diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/AzureBlobToBlob.java b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/AzureBlobToBlob.java index a35f62c1da..56322f5a0a 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/AzureBlobToBlob.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/AzureBlobToBlob.java @@ -40,8 +40,8 @@ public class AzureBlobToBlob implements Function { @Inject AzureBlobToBlob(Factory blobFactory, BlobPropertiesToBlobMetadata blobPr2BlobMd) { - this.blobFactory = blobFactory; - this.blobPr2BlobMd = blobPr2BlobMd; + this.blobFactory = checkNotNull(blobFactory, "blobFactory"); + this.blobPr2BlobMd = checkNotNull(blobPr2BlobMd, "blobPr2BlobMd"); } public Blob apply(AzureBlob from) { diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/BlobPropertiesToBlobMetadata.java b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/BlobPropertiesToBlobMetadata.java index cd761bb25e..5310a41cc7 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/BlobPropertiesToBlobMetadata.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/functions/BlobPropertiesToBlobMetadata.java @@ -19,6 +19,8 @@ package org.jclouds.azure.storage.blob.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Inject; import javax.inject.Singleton; @@ -40,7 +42,7 @@ public class BlobPropertiesToBlobMetadata implements Function, - InvocationContext { + InvocationContext { private final ParseBlobPropertiesFromHeaders metadataParser; private final AzureBlob.Factory blobFactory; @Inject public ParseBlobFromHeadersAndHttpContent(ParseBlobPropertiesFromHeaders metadataParser, - AzureBlob.Factory blobFactory) { + AzureBlob.Factory blobFactory) { this.metadataParser = metadataParser; this.blobFactory = blobFactory; } diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseBlobPropertiesFromHeaders.java b/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseBlobPropertiesFromHeaders.java index 6a9a3e2ece..553ae778d3 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseBlobPropertiesFromHeaders.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseBlobPropertiesFromHeaders.java @@ -38,13 +38,14 @@ import com.google.common.base.Function; * * @author Adrian Cole */ -public class ParseBlobPropertiesFromHeaders implements Function, InvocationContext { +public class ParseBlobPropertiesFromHeaders implements Function, + InvocationContext { private final ParseSystemAndUserMetadataFromHeaders blobMetadataParser; private final BlobMetadataToBlobProperties blobToBlobProperties; @Inject public ParseBlobPropertiesFromHeaders(ParseSystemAndUserMetadataFromHeaders blobMetadataParser, - BlobMetadataToBlobProperties blobToBlobProperties) { + BlobMetadataToBlobProperties blobToBlobProperties) { this.blobMetadataParser = blobMetadataParser; this.blobToBlobProperties = blobToBlobProperties; } diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseContainerPropertiesFromHeaders.java b/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseContainerPropertiesFromHeaders.java index da00660a3b..cc8d318178 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseContainerPropertiesFromHeaders.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ParseContainerPropertiesFromHeaders.java @@ -48,8 +48,8 @@ import com.google.common.base.Function; * * @author Adrian Cole */ -public class ParseContainerPropertiesFromHeaders implements - Function, InvocationContext { +public class ParseContainerPropertiesFromHeaders implements Function, + InvocationContext { private final DateService dateParser; private final String metadataPrefix; @@ -57,14 +57,14 @@ public class ParseContainerPropertiesFromHeaders implements @Inject public ParseContainerPropertiesFromHeaders(DateService dateParser, - @Named(BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { + @Named(BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { this.dateParser = dateParser; this.metadataPrefix = metadataPrefix; } public ContainerProperties apply(HttpResponse from) { MutableContainerPropertiesWithMetadata to = new MutableContainerPropertiesWithMetadataImpl(); - to.setName(request.getArgs()[0].toString()); + to.setName(request.getArgs().get(0).toString()); addUserMetadataTo(from, to); parseLastModifiedOrThrowException(from, to); addETagTo(from, to); @@ -76,23 +76,20 @@ public class ParseContainerPropertiesFromHeaders implements void addUserMetadataTo(HttpResponse from, MutableContainerPropertiesWithMetadata metadata) { for (Entry header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().startsWith(metadataPrefix)) - metadata.getMetadata().put( - (header.getKey().substring(metadataPrefix.length())).toLowerCase(), - header.getValue()); + metadata.getMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), + header.getValue()); } } @VisibleForTesting - void parseLastModifiedOrThrowException(HttpResponse from, - MutableContainerPropertiesWithMetadata metadata) throws HttpException { + void parseLastModifiedOrThrowException(HttpResponse from, MutableContainerPropertiesWithMetadata 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); + throw new HttpException(HttpHeaders.LAST_MODIFIED + " header not present in response: " + from); metadata.setLastModified(dateParser.rfc822DateParse(lastModified)); 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 @@ -105,8 +102,7 @@ public class ParseContainerPropertiesFromHeaders implements @Override public ParseContainerPropertiesFromHeaders 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/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ReturnFalseIfContainerAlreadyExists.java b/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ReturnFalseIfContainerAlreadyExists.java index 475512f31d..7006de1368 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ReturnFalseIfContainerAlreadyExists.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/functions/ReturnFalseIfContainerAlreadyExists.java @@ -19,7 +19,7 @@ package org.jclouds.azure.storage.blob.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import org.jclouds.azure.storage.AzureStorageResponseException; diff --git a/azure/src/main/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthentication.java b/azure/src/main/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthentication.java index 15dd9f3f33..ca84792dcf 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthentication.java +++ b/azure/src/main/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthentication.java @@ -21,7 +21,6 @@ package org.jclouds.azure.storage.filters; import static org.jclouds.util.Patterns.NEWLINE_PATTERN; -import java.util.Collections; import java.util.Set; import java.util.TreeSet; @@ -41,11 +40,15 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpUtils; import org.jclouds.http.internal.SignatureWire; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.io.InputSuppliers; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Multimaps; /** * Signs the Azure Storage request. @@ -71,8 +74,8 @@ public class SharedKeyLiteAuthentication implements HttpRequestFilter { @Inject public SharedKeyLiteAuthentication(SignatureWire signatureWire, @Named(Constants.PROPERTY_IDENTITY) String identity, - @Named(Constants.PROPERTY_CREDENTIAL) String encodedKey, @TimeStamp Provider timeStampProvider, - Crypto crypto, HttpUtils utils) { + @Named(Constants.PROPERTY_CREDENTIAL) String encodedKey, @TimeStamp Provider timeStampProvider, + Crypto crypto, HttpUtils utils) { this.crypto = crypto; this.utils = utils; this.signatureWire = signatureWire; @@ -81,11 +84,25 @@ public class SharedKeyLiteAuthentication implements HttpRequestFilter { this.timeStampProvider = timeStampProvider; } - public void filter(HttpRequest request) throws HttpException { - replaceDateHeader(request); - String toSign = createStringToSign(request); - calculateAndReplaceAuthHeader(request, toSign); + public HttpRequest filter(HttpRequest request) throws HttpException { + request = replaceDateHeader(request); + String signature = calculateSignature(createStringToSign(request)); + request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); + return request; + } + + HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) { + return ModifyRequest.replaceHeader(request, HttpHeaders.AUTHORIZATION, "SharedKeyLite " + identity + ":" + + signature); + } + + HttpRequest replaceDateHeader(HttpRequest request) { + Builder builder = ImmutableMap.builder(); + String date = timeStampProvider.get(); + builder.put(HttpHeaders.DATE, date); + request = ModifyRequest.replaceHeaders(request, Multimaps.forMap(builder.build())); + return request; } public String createStringToSign(HttpRequest request) { @@ -103,18 +120,19 @@ public class SharedKeyLiteAuthentication implements HttpRequestFilter { } private void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) { - buffer.append(utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata().getContentMD5())) - .append("\n"); - buffer.append(utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata().getContentType())) - .append("\n"); + buffer.append( + utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() + .getContentMD5())).append("\n"); + buffer.append( + utils.valueOrEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata() + .getContentType())).append("\n"); } - private void calculateAndReplaceAuthHeader(HttpRequest request, String toSign) throws HttpException { + private String calculateSignature(String toSign) throws HttpException { String signature = signString(toSign); if (signatureWire.enabled()) - signatureWire.input(Utils.toInputStream(signature)); - request.getHeaders().replaceValues(HttpHeaders.AUTHORIZATION, - Collections.singletonList("SharedKeyLite " + identity + ":" + signature)); + signatureWire.input(Strings2.toInputStream(signature)); + return signature; } public String signString(String toSign) { @@ -131,17 +149,13 @@ public class SharedKeyLiteAuthentication implements HttpRequestFilter { toSign.append(request.getMethod()).append("\n"); } - private void replaceDateHeader(HttpRequest request) { - request.getHeaders().replaceValues(HttpHeaders.DATE, Collections.singletonList(timeStampProvider.get())); - } - private void appendCanonicalizedHeaders(HttpRequest request, StringBuilder toSign) { Set headers = new TreeSet(request.getHeaders().keySet()); for (String header : headers) { if (header.startsWith("x-ms-")) { toSign.append(header.toLowerCase()).append(":"); for (String value : request.getHeaders().get(header)) { - toSign.append(Utils.replaceAll(value, NEWLINE_PATTERN, "")).append(","); + toSign.append(Strings2.replaceAll(value, NEWLINE_PATTERN, "")).append(","); } toSign.deleteCharAt(toSign.lastIndexOf(",")); toSign.append("\n"); diff --git a/azure/src/main/java/org/jclouds/azure/storage/handlers/ParseAzureStorageErrorFromXmlContent.java b/azure/src/main/java/org/jclouds/azure/storage/handlers/ParseAzureStorageErrorFromXmlContent.java index 91824eb1ae..9a665ab9fd 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/handlers/ParseAzureStorageErrorFromXmlContent.java +++ b/azure/src/main/java/org/jclouds/azure/storage/handlers/ParseAzureStorageErrorFromXmlContent.java @@ -39,7 +39,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * This will parse and set an appropriate exception on the command object. @@ -79,28 +79,28 @@ public class ParseAzureStorageErrorFromXmlContent implements HttpErrorHandler { } } catch (RuntimeException e) { try { - message = Utils.toStringAndClose(response.getPayload().getInput()); + message = Strings2.toStringAndClose(response.getPayload().getInput()); exception = new HttpResponseException(command, response, message); } catch (IOException e1) { } } } else { try { - message = Utils.toStringAndClose(response.getPayload().getInput()); + message = Strings2.toStringAndClose(response.getPayload().getInput()); exception = new HttpResponseException(command, response, message); } catch (IOException e) { } } } - message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(), + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String path = command.getRequest().getEndpoint().getPath(); + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = CONTAINER_PATH.matcher(path); if (matcher.find()) { exception = new ContainerNotFoundException(matcher.group(1), message); diff --git a/azure/src/main/java/org/jclouds/azure/storage/queue/binders/BindToXmlStringPayload.java b/azure/src/main/java/org/jclouds/azure/storage/queue/binders/BindToXmlStringPayload.java index 3fc1c66df6..f0049b15f3 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/queue/binders/BindToXmlStringPayload.java +++ b/azure/src/main/java/org/jclouds/azure/storage/queue/binders/BindToXmlStringPayload.java @@ -31,8 +31,9 @@ import org.jclouds.rest.binders.BindToStringPayload; */ @Singleton public class BindToXmlStringPayload extends BindToStringPayload { - public void bindToRequest(HttpRequest request, Object payload) { - super.bindToRequest(request, new StringBuilder().append("") - .append(payload).append("").toString()); + @Override + public R bindToRequest(R request, Object payload) { + return super.bindToRequest(request, new StringBuilder().append("").append(payload) + .append("").toString()); } } diff --git a/azure/src/main/java/org/jclouds/azure/storage/util/AzureStorageUtils.java b/azure/src/main/java/org/jclouds/azure/storage/util/AzureStorageUtils.java index 1def0ec9ab..3c186cc8c9 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/util/AzureStorageUtils.java +++ b/azure/src/main/java/org/jclouds/azure/storage/util/AzureStorageUtils.java @@ -55,7 +55,7 @@ public class AzureStorageUtils { AzureStorageError error = factory.create(errorHandlerProvider.get()).parse(content); error.setRequestId(response.getFirstHeaderOrNull(AzureStorageHeaders.REQUEST_ID)); if ("AuthenticationFailed".equals(error.getCode())) { - error.setStringSigned(signer.createStringToSign(command.getRequest())); + error.setStringSigned(signer.createStringToSign(command.getCurrentRequest())); error.setSignature(signer.signString(error.getStringSigned())); } return error; diff --git a/azure/src/test/java/org/jclouds/azure/storage/ProvidersInPropertiesTest.java b/azure/src/test/java/org/jclouds/azure/storage/ProvidersInPropertiesTest.java index 69b8a1a082..0f10801f21 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/ProvidersInPropertiesTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.azure.storage; import org.jclouds.blobstore.util.BlobStoreUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "azurequeue") : providers; assert Iterables.contains(providers, "azureblob") : providers; } 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 f708935c90..5859743041 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 @@ -61,7 +61,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azureblob.AzureBlobAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AzureBlobAsyncClientTest") public class AzureBlobAsyncClientTest extends RestClientTest { public void testListContainers() throws SecurityException, NoSuchMethodException, IOException { diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobClientLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobClientLiveTest.java index 551ed1fd90..0101e43e5b 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobClientLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/AzureBlobClientLiveTest.java @@ -50,7 +50,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.http.options.GetOptions; import org.jclouds.io.Payloads; import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @@ -65,7 +65,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "azureblob.AzureBlobClientLiveTest") +@Test(groups = "live", sequential = true) public class AzureBlobClientLiveTest { protected AzureBlobClient client; @@ -295,7 +295,7 @@ public class AzureBlobClientLiveTest { // Test GET of object (including updated metadata) AzureBlob getBlob = client.getBlob(privateContainer, object.getProperties().getName()); - assertEquals(Utils.toStringAndClose(getBlob.getPayload().getInput()), data); + assertEquals(Strings2.toStringAndClose(getBlob.getPayload().getInput()), data); // TODO assertEquals(getBlob.getName(), object.getProperties().getName()); assertEquals(getBlob.getPayload().getContentMetadata().getContentLength(), new Long(data.length())); assertEquals(getBlob.getProperties().getContentMetadata().getContentType(), "text/plain"); diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequestTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequestTest.java new file mode 100644 index 0000000000..446244a768 --- /dev/null +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobMetadataToRequestTest.java @@ -0,0 +1,154 @@ +/** + * + * 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.azure.storage.blob.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; +import java.util.Properties; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.azure.storage.blob.AzureBlobAsyncClient; +import org.jclouds.azure.storage.blob.domain.AzureBlob; +import org.jclouds.http.HttpRequest; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.rest.RestClientTest; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.rest.RestContextSpec; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; +import com.google.inject.TypeLiteral; + +/** + * Tests behavior of {@code BindAzureBlobMetadataToRequest} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindAzureBlobMetadataToRequestTest") +public class BindAzureBlobMetadataToRequestTest extends RestClientTest { + + @Test + public void testPassWithMinimumDetailsAndPayload64MB() { + AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(64 * 1024 * 1024l); + blob.setPayload(payload); + blob.getProperties().setName("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); + + assertEquals( + binder.bindToRequest(request, blob), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")) + .headers(ImmutableMultimap.of("x-ms-blob-type", "BlockBlob")).build()); + } + + @Test + public void testExtendedPropertiesBind() { + AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(64 * 1024 * 1024l); + blob.setPayload(payload); + blob.getProperties().setName("foo"); + blob.getProperties().setMetadata(ImmutableMap.of("foo", "bar")); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); + + assertEquals( + binder.bindToRequest(request, blob), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")) + .headers(ImmutableMultimap.of("x-ms-blob-type", "BlockBlob", "x-ms-meta-foo", "bar")).build()); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNoContentLengthIsBad() { + AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(null); + blob.setPayload(payload); + blob.getProperties().setName("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); + binder.bindToRequest(request, blob); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNoNameIsBad() { + AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5368709120000l); + blob.setPayload(payload); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); + binder.bindToRequest(request, blob); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testOver64MBIsBad() { + AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(64 * 1024 * 1024l + 1); + blob.setPayload(payload); + blob.getProperties().setName("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); + binder.bindToRequest(request, blob); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeAzureBlob() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + injector.getInstance(BindAzureBlobMetadataToRequest.class).bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } + + @Override + protected void checkFilters(HttpRequest request) { + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + public RestContextSpec createContextSpec() { + return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties()); + } +} \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayloadTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayloadTest.java deleted file mode 100644 index a3f9878bd5..0000000000 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/binders/BindAzureBlobToPayloadTest.java +++ /dev/null @@ -1,200 +0,0 @@ -/** - * - * 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.azure.storage.blob.binders; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import org.jclouds.azure.storage.blob.blobstore.functions.AzureBlobToBlob; -import org.jclouds.azure.storage.blob.domain.AzureBlob; -import org.jclouds.azure.storage.blob.domain.BlobType; -import org.jclouds.azure.storage.blob.domain.MutableBlobProperties; -import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.http.HttpRequest; -import org.jclouds.io.MutableContentMetadata; -import org.jclouds.io.Payload; -import org.testng.annotations.Test; - -import com.google.common.collect.Multimap; - -/** - * Tests behavior of {@code BindAzureBlobToPayload} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "azure.BindAzureBlobToPayloadTest") -public class BindAzureBlobToPayloadTest { - @SuppressWarnings("unchecked") - @Test - public void testPassBlockWithMinimumDetailsAndPayload64MB() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - AzureBlobToBlob object2Blob = createMock(AzureBlobToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - AzureBlob object = createMock(AzureBlob.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableBlobProperties md = createMock(MutableBlobProperties.class); - Multimap headers = createMock(Multimap.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(content.getContentLength()).andReturn(1024l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getProperties()).andReturn(md).atLeastOnce(); - expect(md.getType()).andReturn(BlobType.BLOCK_BLOB).atLeastOnce(); - expect(request.getHeaders()).andReturn(headers).atLeastOnce(); - expect(headers.put("x-ms-blob-type", "BlockBlob")).andReturn(true); - - replay(headers); - replay(content); - replay(payload); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindAzureBlobToPayload binder = new BindAzureBlobToPayload(object2Blob, mdBinder); - - binder.bindToRequest(request, object); - - verify(headers); - verify(content); - verify(payload); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } - - @SuppressWarnings("unchecked") - @Test - public void testBlockExtendedPropertiesBind() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - AzureBlobToBlob object2Blob = createMock(AzureBlobToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - AzureBlob object = createMock(AzureBlob.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableBlobProperties md = createMock(MutableBlobProperties.class); - Multimap headers = createMock(Multimap.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(content.getContentLength()).andReturn(1024l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getProperties()).andReturn(md).atLeastOnce(); - expect(md.getType()).andReturn(BlobType.BLOCK_BLOB).atLeastOnce(); - expect(request.getHeaders()).andReturn(headers).atLeastOnce(); - expect(headers.put("x-ms-blob-type", "BlockBlob")).andReturn(true); - - replay(headers); - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindAzureBlobToPayload binder = new BindAzureBlobToPayload(object2Blob, mdBinder); - - binder.bindToRequest(request, object); - - verify(headers); - verify(payload); - verify(content); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } - - @SuppressWarnings("unchecked") - @Test(expectedExceptions = IllegalArgumentException.class) - public void testBlockOver64MBIsBad() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - AzureBlobToBlob object2Blob = createMock(AzureBlobToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - AzureBlob object = createMock(AzureBlob.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableBlobProperties md = createMock(MutableBlobProperties.class); - Multimap headers = createMock(Multimap.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(content.getContentLength()).andReturn(5368709121l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getProperties()).andReturn(md).atLeastOnce(); - expect(md.getType()).andReturn(BlobType.BLOCK_BLOB).atLeastOnce(); - expect(request.getHeaders()).andReturn(headers).atLeastOnce(); - expect(headers.put("x-ms-blob-type", "BlockBlob")).andReturn(true); - - expect(content.getContentLanguage()).andReturn(null).atLeastOnce(); - expect(content.getContentEncoding()).andReturn(null).atLeastOnce(); - - replay(headers); - replay(payload); - replay(content); - - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindAzureBlobToPayload bindAzureBlobToPayload = new BindAzureBlobToPayload(object2Blob, mdBinder); - - bindAzureBlobToPayload.bindToRequest(request, object); - - verify(headers); - verify(content); - verify(payload); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } -} diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobRequestSignerTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobRequestSignerTest.java index 1fb4a52b13..b01037edc7 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobRequestSignerTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobRequestSignerTest.java @@ -44,7 +44,13 @@ import com.google.common.base.Supplier; import com.google.inject.Module; import com.google.inject.TypeLiteral; -@Test(groups = "unit", testName = "s3.AzureBlobBlobRequestSignerTest") +/** + * Tests behavior of {@code AzureBlobRequestSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AzureBlobRequestSignerTest") public class AzureBlobRequestSignerTest extends RestClientTest { private BlobRequestSigner signer; diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreModuleTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreModuleTest.java index 42499e49b0..1f6d6040dd 100755 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreModuleTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreModuleTest.java @@ -37,7 +37,7 @@ import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "azureblob.AzureBlobStoreModuleTest") +@Test(groups = "unit") public class AzureBlobStoreModuleTest { Injector createInjector() { diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerIntegrationLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerIntegrationLiveTest.java index 770c8ca61a..0829c516b3 100755 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerIntegrationLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerIntegrationLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = "live", testName = "azureblob.AzureBlobContainerIntegrationTest") +@Test(groups = "live") public class AzureBlobContainerIntegrationLiveTest extends BaseContainerIntegrationTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerLiveTest.java index 1dcaebb083..4a231aaf01 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobContainerLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "azureblob.AzureBlobContainerLiveTest") +@Test(groups = { "live" }) public class AzureBlobContainerLiveTest extends BaseContainerLiveTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobInputStreamMapIntegrationLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobInputStreamMapIntegrationLiveTest.java index c6df5b6c9e..995962ecbe 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobInputStreamMapIntegrationLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobInputStreamMapIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "azureblob.AzureBlobInputStreamMapIntegrationTest") +@Test(groups = "live") public class AzureBlobInputStreamMapIntegrationLiveTest extends BaseInputStreamMapIntegrationTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobIntegrationLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobIntegrationLiveTest.java index f304377f60..85395a5066 100755 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobIntegrationLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobIntegrationLiveTest.java @@ -31,7 +31,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", testName = "azureblob.AzureBlobIntegrationTest") +@Test(groups = "live") public class AzureBlobIntegrationLiveTest extends BaseBlobIntegrationTest { @Override diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobLiveTest.java index 2034ed70e0..50abcd9ab3 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "azureblob.AzureBlobLiveTest") +@Test(groups = { "live" }) public class AzureBlobLiveTest extends BaseBlobLiveTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobMapIntegrationLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobMapIntegrationLiveTest.java index 6beebe853b..b8019b518e 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobMapIntegrationLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobMapIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "azureblob.AzureBlobMapIntegrationTest") +@Test(groups = "live") public class AzureBlobMapIntegrationLiveTest extends BaseBlobMapIntegrationTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobServiceIntegrationLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobServiceIntegrationLiveTest.java index 84c1c54cdb..04da625660 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobServiceIntegrationLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobServiceIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "azureblob.AzureBlobServiceIntegrationTest") +@Test(groups = "live") public class AzureBlobServiceIntegrationLiveTest extends BaseServiceIntegrationTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobSignerLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobSignerLiveTest.java index 0990cd5b72..e630ca449a 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobSignerLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/blobstore/integration/AzureBlobSignerLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "azureblob.AzureBlobSignerLiveTest") +@Test(groups = { "live" }) public class AzureBlobSignerLiveTest extends BaseBlobSignerLiveTest { } \ No newline at end of file diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/options/CreateContainerOptionsTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/options/CreateContainerOptionsTest.java index def0a7854b..26c25fb80e 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/options/CreateContainerOptionsTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/options/CreateContainerOptionsTest.java @@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableMultimap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurestorage.CreateContainerOptionsTest") +@Test(groups = "unit") public class CreateContainerOptionsTest { public void testPublicAcl() { diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/options/ListBlobsOptionsTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/options/ListBlobsOptionsTest.java index a709816ee2..baca4f86fb 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/options/ListBlobsOptionsTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/options/ListBlobsOptionsTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurestorage.ListBlobsOptionsTest") +@Test(groups = "unit") public class ListBlobsOptionsTest { public void testDelimiter() { diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/xml/AccountNameEnumerationResultsHandlerTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/xml/AccountNameEnumerationResultsHandlerTest.java index 21f5a22a69..fb4fe15ecd 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/xml/AccountNameEnumerationResultsHandlerTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/xml/AccountNameEnumerationResultsHandlerTest.java @@ -38,11 +38,12 @@ import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** - * Tests behavior of {@code ParseFlavorListFromJsonResponseTest} + * Tests behavior of {@code AccountNameEnumerationResultsHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azureblob.AccountNameEnumerationResultsHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "blob.AccountNameEnumerationResultsHandlerTest") public class AccountNameEnumerationResultsHandlerTest extends BaseHandlerTest { private DateService dateService; diff --git a/azure/src/test/java/org/jclouds/azure/storage/blob/xml/ContainerNameEnumerationResultsHandlerTest.java b/azure/src/test/java/org/jclouds/azure/storage/blob/xml/ContainerNameEnumerationResultsHandlerTest.java index bcde1f9f98..aa0cef651b 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/blob/xml/ContainerNameEnumerationResultsHandlerTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/blob/xml/ContainerNameEnumerationResultsHandlerTest.java @@ -40,11 +40,12 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; /** - * Tests behavior of {@code ContainerNameEnumerationResultsHandlerTest} + * Tests behavior of {@code ContainerNameEnumerationResultsHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azureblob.ContainerNameEnumerationResultsHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ContainerNameEnumerationResultsHandlerTest") public class ContainerNameEnumerationResultsHandlerTest extends BaseHandlerTest { private DateService dateService; @@ -60,28 +61,25 @@ public class ContainerNameEnumerationResultsHandlerTest extends BaseHandlerTest InputStream is = getClass().getResourceAsStream("/blob/test_list_blobs.xml"); Set contents = Sets.newTreeSet(); contents.add(new BlobPropertiesImpl(BlobType.BLOCK_BLOB, "blob1.txt", URI - .create("http://myaccount.blob.core.windows.net/mycontainer/blob1.txt"), dateService - .rfc822DateParse("Thu, 18 Sep 2008 18:41:57 GMT"), "0x8CAE7D55D050B8B", 8, - "text/plain; charset=UTF-8", null, null, null, LeaseStatus.UNLOCKED, ImmutableMap - . of())); + .create("http://myaccount.blob.core.windows.net/mycontainer/blob1.txt"), dateService + .rfc822DateParse("Thu, 18 Sep 2008 18:41:57 GMT"), "0x8CAE7D55D050B8B", 8, "text/plain; charset=UTF-8", + null, null, null, LeaseStatus.UNLOCKED, ImmutableMap. of())); contents.add(new BlobPropertiesImpl(BlobType.BLOCK_BLOB, "blob2.txt", URI - .create("http://myaccount.blob.core.windows.net/mycontainer/blob2.txt"), dateService - .rfc822DateParse("Thu, 18 Sep 2008 18:41:57 GMT"), "0x8CAE7D55CF6C339", 14, - "text/plain; charset=UTF-8", null, null, null, LeaseStatus.UNLOCKED, ImmutableMap - . of())); + .create("http://myaccount.blob.core.windows.net/mycontainer/blob2.txt"), dateService + .rfc822DateParse("Thu, 18 Sep 2008 18:41:57 GMT"), "0x8CAE7D55CF6C339", 14, "text/plain; charset=UTF-8", + null, null, null, LeaseStatus.UNLOCKED, ImmutableMap. of())); contents.add(new BlobPropertiesImpl(BlobType.PAGE_BLOB, "newblob1.txt", URI - .create("http://myaccount.blob.core.windows.net/mycontainer/newblob1.txt"), - dateService.rfc822DateParse("Thu, 18 Sep 2008 18:41:57 GMT"), "0x8CAE7D55CF6C339", - 25, "text/plain; charset=UTF-8", null, null, null, LeaseStatus.UNLOCKED, - ImmutableMap. of())); + .create("http://myaccount.blob.core.windows.net/mycontainer/newblob1.txt"), dateService + .rfc822DateParse("Thu, 18 Sep 2008 18:41:57 GMT"), "0x8CAE7D55CF6C339", 25, "text/plain; charset=UTF-8", + null, null, null, LeaseStatus.UNLOCKED, ImmutableMap. of())); - ListBlobsResponse list = new HashSetListBlobsResponse(contents, URI - .create("http://myaccount.blob.core.windows.net/mycontainer"), + ListBlobsResponse list = new HashSetListBlobsResponse(contents, + URI.create("http://myaccount.blob.core.windows.net/mycontainer"), - "myfolder/", null, 4, "newblob2.txt", "/", Sets. newTreeSet()); + "myfolder/", null, 4, "newblob2.txt", "/", Sets. newTreeSet()); ListBlobsResponse result = (ListBlobsResponse) factory.create( - injector.getInstance(ContainerNameEnumerationResultsHandler.class)).parse(is); + injector.getInstance(ContainerNameEnumerationResultsHandler.class)).parse(is); assertEquals(result, list); } @@ -90,19 +88,18 @@ public class ContainerNameEnumerationResultsHandlerTest extends BaseHandlerTest InputStream is = getClass().getResourceAsStream("/blob/test_list_blobs_options.xml"); Set contents = Sets.newTreeSet(); contents.add(new BlobPropertiesImpl(BlobType.BLOCK_BLOB, "a", URI - .create("https://jclouds.blob.core.windows.net/adriancole-blobstore3/a"), - dateService.rfc822DateParse("Sat, 30 Jan 2010 17:46:15 GMT"), "0x8CC6FEB41736428", - 8, "application/octet-stream", null, null, null, LeaseStatus.UNLOCKED, ImmutableMap - . of())); + .create("https://jclouds.blob.core.windows.net/adriancole-blobstore3/a"), dateService + .rfc822DateParse("Sat, 30 Jan 2010 17:46:15 GMT"), "0x8CC6FEB41736428", 8, "application/octet-stream", + null, null, null, LeaseStatus.UNLOCKED, ImmutableMap. of())); - ListBlobsResponse list = new HashSetListBlobsResponse(contents, URI - .create("https://jclouds.blob.core.windows.net/adriancole-blobstore3"), + ListBlobsResponse list = new HashSetListBlobsResponse(contents, + URI.create("https://jclouds.blob.core.windows.net/adriancole-blobstore3"), - null, null, 1, "2!68!MDAwMDA2IWFwcGxlcyEwMDAwMjghOTk5OS0xMi0zMVQyMzo1OTo1OS45OTk5OTk5WiE-", - "/", Sets. newTreeSet()); + null, null, 1, "2!68!MDAwMDA2IWFwcGxlcyEwMDAwMjghOTk5OS0xMi0zMVQyMzo1OTo1OS45OTk5OTk5WiE-", "/", + Sets. newTreeSet()); ListBlobsResponse result = (ListBlobsResponse) factory.create( - injector.getInstance(ContainerNameEnumerationResultsHandler.class)).parse(is); + injector.getInstance(ContainerNameEnumerationResultsHandler.class)).parse(is); assertEquals(result, list); } diff --git a/azure/src/test/java/org/jclouds/azure/storage/config/AzureStorageRestClientModuleTest.java b/azure/src/test/java/org/jclouds/azure/storage/config/AzureStorageRestClientModuleTest.java index 6a70be4195..d43d46b333 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/config/AzureStorageRestClientModuleTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/config/AzureStorageRestClientModuleTest.java @@ -43,7 +43,7 @@ import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "azure.RestAzureStorageClientModuleTest") +@Test(groups = "unit") public class AzureStorageRestClientModuleTest { Injector createInjector() throws IOException { @@ -54,6 +54,7 @@ public class AzureStorageRestClientModuleTest { @SuppressWarnings("unchecked") @Test void testUpdatesOnlyOncePerSecond() throws NoSuchMethodException, InterruptedException { + @SuppressWarnings("rawtypes") AzureStorageRestClientModule module = new AzureBlobRestClientModule(); Supplier map = module.provideTimeStampCache(1, new SimpleDateFormatDateService()); diff --git a/azure/src/test/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthenticationTest.java b/azure/src/test/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthenticationTest.java index fe27c5ce15..d06379713e 100755 --- a/azure/src/test/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthenticationTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthenticationTest.java @@ -43,7 +43,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurestorage.SharedKeyLiteAuthenticationTest") +@Test(groups = "unit") public class SharedKeyLiteAuthenticationTest { private static final String KEY = Base64.encodeBytes("bar".getBytes()); @@ -54,16 +54,12 @@ public class SharedKeyLiteAuthenticationTest { @DataProvider(parallel = true) public Object[][] dataProvider() { return new Object[][] { - { new HttpRequest( - HttpMethod.PUT, - URI - .create("http://" - + ACCOUNT - + ".blob.core.windows.net/movies/MOV1.avi?comp=block&blockid=BlockId1&timeout=60")) }, - { new HttpRequest(HttpMethod.PUT, URI.create("http://" + ACCOUNT - + ".blob.core.windows.net/movies/MOV1.avi?comp=blocklist&timeout=120")) }, - { new HttpRequest(HttpMethod.GET, URI.create("http://" + ACCOUNT - + ".blob.core.windows.net/movies/MOV1.avi")) } }; + { new HttpRequest(HttpMethod.PUT, URI.create("http://" + ACCOUNT + + ".blob.core.windows.net/movies/MOV1.avi?comp=block&blockid=BlockId1&timeout=60")) }, + { new HttpRequest(HttpMethod.PUT, URI.create("http://" + ACCOUNT + + ".blob.core.windows.net/movies/MOV1.avi?comp=blocklist&timeout=120")) }, + { new HttpRequest(HttpMethod.GET, + URI.create("http://" + ACCOUNT + ".blob.core.windows.net/movies/MOV1.avi")) } }; } /** @@ -73,18 +69,18 @@ public class SharedKeyLiteAuthenticationTest { */ @Test(threadPoolSize = 3, dataProvider = "dataProvider", timeOut = 3000) void testIdempotent(HttpRequest request) { - filter.filter(request); + request = filter.filter(request); String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION); String date = request.getFirstHeaderOrNull(HttpHeaders.DATE); int iterations = 1; while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) { date = request.getFirstHeaderOrNull(HttpHeaders.DATE); - filter.filter(request); iterations++; assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)); + request = filter.filter(request); } - System.out.printf("%s: %d iterations before the timestamp updated %n", Thread.currentThread() - .getName(), iterations); + System.out.printf("%s: %d iterations before the timestamp updated %n", Thread.currentThread().getName(), + iterations); } @Test @@ -98,8 +94,7 @@ public class SharedKeyLiteAuthenticationTest { @Test void testAclQueryStringResTypeNotSignificant() { - URI host = URI.create("http://" + ACCOUNT - + ".blob.core.windows.net/mycontainer?restype=container"); + URI host = URI.create("http://" + ACCOUNT + ".blob.core.windows.net/mycontainer?restype=container"); HttpRequest request = new HttpRequest(HttpMethod.GET, host); StringBuilder builder = new StringBuilder(); filter.appendUriPath(request, builder); @@ -117,10 +112,8 @@ public class SharedKeyLiteAuthenticationTest { @Test void testAclQueryStringRelativeWithExtraJunk() { - URI host = URI - .create("http://" - + ACCOUNT - + ".blob.core.windows.net/mycontainer?comp=list&marker=marker&maxresults=1&prefix=prefix"); + URI host = URI.create("http://" + ACCOUNT + + ".blob.core.windows.net/mycontainer?comp=list&marker=marker&maxresults=1&prefix=prefix"); HttpRequest request = new HttpRequest(HttpMethod.GET, host); StringBuilder builder = new StringBuilder(); filter.appendUriPath(request, builder); @@ -129,13 +122,14 @@ public class SharedKeyLiteAuthenticationTest { /** * before class, as we need to ensure that the filter is threadsafe. - * @throws IOException + * + * @throws IOException * */ @BeforeClass protected void createFilter() throws IOException { injector = new RestContextFactory().createContextBuilder("azurequeue", ACCOUNT, KEY, - ImmutableSet. of(new Log4JLoggingModule())).buildInjector(); + ImmutableSet. of(new Log4JLoggingModule())).buildInjector(); filter = injector.getInstance(SharedKeyLiteAuthentication.class); } diff --git a/azure/src/test/java/org/jclouds/azure/storage/handlers/ParseAzureErrorFromXmlContentTest.java b/azure/src/test/java/org/jclouds/azure/storage/handlers/ParseAzureErrorFromXmlContentTest.java index 76df0346b2..052fab388e 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/handlers/ParseAzureErrorFromXmlContentTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/handlers/ParseAzureErrorFromXmlContentTest.java @@ -35,7 +35,7 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.config.SaxParserModule; import org.jclouds.io.Payloads; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.inject.AbstractModule; @@ -89,11 +89,11 @@ public class ParseAzureErrorFromXmlContentTest { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); - HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils + HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Strings2 .toInputStream(content))); response.getPayload().getContentMetadata().setContentType(contentType); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); diff --git a/azure/src/test/java/org/jclouds/azure/storage/options/CreateOptionsTest.java b/azure/src/test/java/org/jclouds/azure/storage/options/CreateOptionsTest.java index e53e46715d..21ab63f7cb 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/options/CreateOptionsTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/options/CreateOptionsTest.java @@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableMultimap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurequeue.CreateOptionsTest") +@Test(groups = "unit") public class CreateOptionsTest { public void testMetadata() { diff --git a/azure/src/test/java/org/jclouds/azure/storage/options/ListOptionsTest.java b/azure/src/test/java/org/jclouds/azure/storage/options/ListOptionsTest.java index b8f767e24b..b34b77382c 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/options/ListOptionsTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/options/ListOptionsTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurestorage.ListOptionsTest") +@Test(groups = "unit") public class ListOptionsTest { public void testIncludeMetadata() { ListOptions options = new ListOptions().includeMetadata(); 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 e396735aad..dcd8b907a8 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 @@ -54,7 +54,8 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurequeue.AzureQueueAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "AzureQueueAsyncClientTest") public class AzureQueueAsyncClientTest extends RestClientTest { public void testGetMessages() throws SecurityException, NoSuchMethodException, IOException { diff --git a/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueClientLiveTest.java b/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueClientLiveTest.java index bee64ac7de..08b039a19f 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueClientLiveTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/queue/AzureQueueClientLiveTest.java @@ -51,7 +51,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "azurequeue.AzureQueueClientLiveTest") +@Test(groups = "live", sequential = true) public class AzureQueueClientLiveTest { protected AzureQueueClient connection; diff --git a/azure/src/test/java/org/jclouds/azure/storage/queue/options/GetOptionsTest.java b/azure/src/test/java/org/jclouds/azure/storage/queue/options/GetOptionsTest.java index b890c22429..e27268be3b 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/queue/options/GetOptionsTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/queue/options/GetOptionsTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurequeue.GetOptionsTest") +@Test(groups = "unit") public class GetOptionsTest { public void testMaxMessages() { diff --git a/azure/src/test/java/org/jclouds/azure/storage/queue/xml/AccountNameEnumerationResultsHandlerTest.java b/azure/src/test/java/org/jclouds/azure/storage/queue/xml/AccountNameEnumerationResultsHandlerTest.java index a5edc9b234..a6b90f2132 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/queue/xml/AccountNameEnumerationResultsHandlerTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/queue/xml/AccountNameEnumerationResultsHandlerTest.java @@ -33,11 +33,12 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableSortedSet; /** - * Tests behavior of {@code ParseFlavorListFromGsonResponseTest} + * Tests behavior of {@code AccountNameEnumerationResultsHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurequeue.AccountNameEnumerationResultsHandlerTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "queue.AccountNameEnumerationResultsHandlerTest") public class AccountNameEnumerationResultsHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/azure/src/test/java/org/jclouds/azure/storage/queue/xml/QueueMessagesListHandlerTest.java b/azure/src/test/java/org/jclouds/azure/storage/queue/xml/QueueMessagesListHandlerTest.java index 062033090f..9f7647427e 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/queue/xml/QueueMessagesListHandlerTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/queue/xml/QueueMessagesListHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurequeue.QueueMessagesListHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "QueueMessagesListHandlerTest") public class QueueMessagesListHandlerTest extends BaseHandlerTest { private DateService dateService; diff --git a/azure/src/test/java/org/jclouds/azure/storage/xml/ErrorHandlerTest.java b/azure/src/test/java/org/jclouds/azure/storage/xml/ErrorHandlerTest.java index 846f98ab95..747f579af5 100644 --- a/azure/src/test/java/org/jclouds/azure/storage/xml/ErrorHandlerTest.java +++ b/azure/src/test/java/org/jclouds/azure/storage/xml/ErrorHandlerTest.java @@ -33,7 +33,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "azurestorage.ErrorHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ErrorHandlerTest") public class ErrorHandlerTest extends BaseHandlerTest { ParseSax createParser() { diff --git a/blobstore/src/main/java/org/jclouds/blobstore/BlobStoreContextFactory.java b/blobstore/src/main/java/org/jclouds/blobstore/BlobStoreContextFactory.java index ffbb4b4ddd..8bebaa2604 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/BlobStoreContextFactory.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/BlobStoreContextFactory.java @@ -20,7 +20,7 @@ package org.jclouds.blobstore; import static org.jclouds.rest.RestContextFactory.createContextBuilder; -import static org.jclouds.util.Utils.propagateAuthorizationOrOriginalException; +import static org.jclouds.util.Throwables2.propagateAuthorizationOrOriginalException; import java.util.Properties; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java index f308d57d18..62b0a4f54e 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java @@ -123,12 +123,11 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { @Inject protected TransientAsyncBlobStore(BlobStoreContext context, DateService dateService, Crypto crypto, - ConcurrentMap> containerToBlobs, - ConcurrentMap containerToLocation, - HttpGetOptionsListToGetOptions httpGetOptionsConverter, - IfDirectoryReturnNameStrategy ifDirectoryReturnName, Blob.Factory blobFactory, BlobUtils blobUtils, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - @Memoized Supplier> locations) { + ConcurrentMap> containerToBlobs, + ConcurrentMap containerToLocation, HttpGetOptionsListToGetOptions httpGetOptionsConverter, + IfDirectoryReturnNameStrategy ifDirectoryReturnName, Blob.Factory blobFactory, BlobUtils blobUtils, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, + @Memoized Supplier> locations) { super(context, blobUtils, service, defaultLocation, locations); this.blobFactory = blobFactory; this.dateService = dateService; @@ -152,21 +151,21 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { return immediateFailedFuture(cnfe(container)); SortedSet contents = newTreeSet(transform(realContents.keySet(), - new Function() { - public StorageMetadata apply(String key) { - Blob oldBlob = realContents.get(key); - checkState(oldBlob != null, "blob " + key + " is not present although it was in the list of " - + container); - checkState(oldBlob.getMetadata() != null, "blob " + container + "/" + key + " has no metadata"); - MutableBlobMetadata md = copy(oldBlob.getMetadata()); - String directoryName = ifDirectoryReturnName.execute(md); - if (directoryName != null) { - md.setName(directoryName); - md.setType(StorageType.RELATIVE_PATH); - } - return md; + new Function() { + public StorageMetadata apply(String key) { + Blob oldBlob = realContents.get(key); + checkState(oldBlob != null, "blob " + key + " is not present although it was in the list of " + + container); + checkState(oldBlob.getMetadata() != null, "blob " + container + "/" + key + " has no metadata"); + MutableBlobMetadata md = copy(oldBlob.getMetadata()); + String directoryName = ifDirectoryReturnName.execute(md); + if (directoryName != null) { + md.setName(directoryName); + md.setType(StorageType.RELATIVE_PATH); } - })); + return md; + } + })); if (options.getMarker() != null) { final String finalMarker = options.getMarker(); @@ -210,15 +209,15 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { contents = newTreeSet(filter(contents, new DelimiterFilter(prefix != null ? prefix : null, delimiter))); - Iterables. addAll(contents, transform(commonPrefixes, - new Function() { - public StorageMetadata apply(String o) { - MutableStorageMetadata md = new MutableStorageMetadataImpl(); - md.setType(StorageType.RELATIVE_PATH); - md.setName(o); - return md; - } - })); + Iterables. addAll(contents, + transform(commonPrefixes, new Function() { + public StorageMetadata apply(String o) { + MutableStorageMetadata md = new MutableStorageMetadataImpl(); + md.setType(StorageType.RELATIVE_PATH); + md.setName(o); + return md; + } + })); } // trim metadata, if the response isn't supposed to be detailed. @@ -229,13 +228,13 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { } return Futures.> immediateFuture(new PageSetImpl(contents, - marker)); + marker)); } private ContainerNotFoundException cnfe(final String name) { return new ContainerNotFoundException(name, String.format("container %s not in %s", name, getContainerToBlobs() - .keySet())); + .keySet())); } public static MutableBlobMetadata copy(MutableBlobMetadata in) { @@ -333,15 +332,15 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { @Override public ListenableFuture> list() { return Futures.> immediateFuture(new PageSetImpl(transform( - getContainerToBlobs().keySet(), new Function() { - public StorageMetadata apply(String name) { - MutableStorageMetadata cmd = create(); - cmd.setName(name); - cmd.setType(StorageType.CONTAINER); - cmd.setLocation(getContainerToLocation().get(name)); - return cmd; - } - }), null)); + getContainerToBlobs().keySet(), new Function() { + public StorageMetadata apply(String name) { + MutableStorageMetadata cmd = create(); + cmd.setName(name); + cmd.setType(StorageType.CONTAINER); + cmd.setLocation(getContainerToLocation().get(name)); + return cmd; + } + }), null)); } protected MutableStorageMetadata create() { @@ -365,7 +364,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { */ public ListenableFuture createContainerInLocationIfAbsent(final Location location, final String name) { ConcurrentMap container = getContainerToBlobs().putIfAbsent(name, - new ConcurrentHashMap()); + new ConcurrentHashMap()); if (container == null) { getContainerToLocation().put(name, location != null ? location : defaultLocation.get()); return immediateFuture((Void) null); @@ -463,7 +462,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { return 0; } - public HttpRequest getRequest() { + public HttpRequest getCurrentRequest() { return new HttpRequest("GET", URI.create("http://stub")); } @@ -475,6 +474,11 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { } + @Override + public void setCurrentRequest(HttpRequest request) { + + } + }, response); } @@ -510,11 +514,11 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { protected Blob createUpdatedCopyOfBlob(Blob in) { ByteArrayPayload payload = (in.getPayload() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(in - .getPayload()) : null; + .getPayload()) : null; if (payload == null) payload = (in.getPayload() instanceof DelegatingPayload) ? (DelegatingPayload.class.cast(in.getPayload()) - .getDelegate() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(DelegatingPayload.class - .cast(in.getPayload()).getDelegate()) : null : null; + .getDelegate() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(DelegatingPayload.class.cast( + in.getPayload()).getDelegate()) : null : null; try { if (payload == null || !(payload instanceof ByteArrayPayload)) { MutableContentMetadata oldMd = in.getPayload().getContentMetadata(); @@ -536,7 +540,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { blob.getMetadata().setETag(eTag); // Set HTTP headers to match metadata blob.getAllHeaders().replaceValues(HttpHeaders.LAST_MODIFIED, - Collections.singleton(dateService.rfc822DateFormat(blob.getMetadata().getLastModified()))); + Collections.singleton(dateService.rfc822DateFormat(blob.getMetadata().getLastModified()))); blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, Collections.singleton(eTag)); copyPayloadHeadersToBlob(payload, blob); blob.getAllHeaders().putAll(Multimaps.forMap(blob.getMetadata().getUserMetadata())); @@ -544,7 +548,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { } private void copyPayloadHeadersToBlob(Payload payload, Blob blob) { - HttpUtils.addContentHeadersFromMetadata(payload.getContentMetadata(), blob.getAllHeaders()); + blob.getAllHeaders().putAll(HttpUtils.getContentHeadersFromMetadata(payload.getContentMetadata())); } /** @@ -584,7 +588,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { if (object.getMetadata().getLastModified().before(modifiedSince)) { HttpResponse response = new HttpResponse(304, null, null); return immediateFailedFuture(new HttpResponseException(String.format("%1$s is before %2$s", object - .getMetadata().getLastModified(), modifiedSince), null, response)); + .getMetadata().getLastModified(), modifiedSince), null, response)); } } @@ -593,7 +597,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { if (object.getMetadata().getLastModified().after(unmodifiedSince)) { HttpResponse response = new HttpResponse(412, null, null); return immediateFailedFuture(new HttpResponseException(String.format("%1$s is after %2$s", object - .getMetadata().getLastModified(), unmodifiedSince), null, response)); + .getMetadata().getLastModified(), unmodifiedSince), null, response)); } } Blob returnVal = copyBlob(object); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java b/blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java index df2f6f0f98..52ebc4fcc0 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java @@ -48,26 +48,23 @@ public class TransientBlobRequestSigner implements BlobRequestSigner { @Override public HttpRequest signGetBlob(String container, String name) { HttpRequest request = new HttpRequest("GET", URI.create(String.format("http://localhost/%s/%s", container, name))); - basicAuth.filter(request); - return request; + return basicAuth.filter(request); } @Override public HttpRequest signPutBlob(String container, Blob blob) { - HttpRequest request = new HttpRequest("PUT", URI.create(String.format("http://localhost/%s/%s", container, blob - .getMetadata().getName()))); - HttpUtils.addContentHeadersFromMetadata(blob.getMetadata().getContentMetadata(), request.getHeaders()); - request.setPayload(blob.getPayload()); - basicAuth.filter(request); - return request; + HttpRequest request = HttpRequest.builder().method("PUT") + .endpoint(URI.create(String.format("http://localhost/%s/%s", container, blob.getMetadata().getName()))) + .payload(blob.getPayload()) + .headers(HttpUtils.getContentHeadersFromMetadata(blob.getMetadata().getContentMetadata())).build(); + return basicAuth.filter(request); } @Override public HttpRequest signRemoveBlob(String container, String name) { HttpRequest request = new HttpRequest("DELETE", URI.create(String.format("http://localhost/%s/%s", container, - name))); - basicAuth.filter(request); - return request; + name))); + return basicAuth.filter(request); } } \ No newline at end of file diff --git a/blobstore/src/main/java/org/jclouds/blobstore/binders/BindBlobToMultipartForm.java b/blobstore/src/main/java/org/jclouds/blobstore/binders/BindBlobToMultipartForm.java index d24d19f6f7..d3ff55cf57 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/binders/BindBlobToMultipartForm.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/binders/BindBlobToMultipartForm.java @@ -19,6 +19,9 @@ package org.jclouds.blobstore.binders; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Singleton; import org.jclouds.blobstore.domain.Blob; @@ -35,12 +38,16 @@ import org.jclouds.rest.Binder; @Singleton public class BindBlobToMultipartForm implements Binder { - public void bindToRequest(HttpRequest request, Object payload) { - Blob blob = (Blob) payload; + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof Blob, "this binder is only valid for Blobs!"); + checkNotNull(request, "request"); + Blob blob = Blob.class.cast(input); Part part = Part.create(blob.getMetadata().getName(), blob.getPayload(), - new PartOptions().contentType(blob.getMetadata().getContentMetadata().getContentType())); + new PartOptions().contentType(blob.getMetadata().getContentMetadata().getContentType())); request.setPayload(new MultipartForm(part)); + return request; } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefix.java b/blobstore/src/main/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefix.java index debd4c406d..fe94f26e3c 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefix.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefix.java @@ -19,17 +19,23 @@ package org.jclouds.blobstore.binders; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import java.util.Map; -import java.util.Map.Entry; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; +import org.jclouds.util.Maps2; + +import com.google.common.base.Function; +import com.google.common.collect.Multimaps; /** * @@ -37,24 +43,36 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindMapToHeadersWithPrefix implements Binder { - private final String metadataPrefix; + private final Function FN; @Inject - public BindMapToHeadersWithPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { - this.metadataPrefix = metadataPrefix; + public BindMapToHeadersWithPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) final String metadataPrefix) { + checkNotNull(metadataPrefix, PROPERTY_USER_METADATA_PREFIX); + FN = new Function() { + + @Override + public String apply(String arg0) { + String inLowercase = arg0.toLowerCase(); + return (inLowercase.startsWith(metadataPrefix)) ? inLowercase : metadataPrefix + inLowercase; + } + + @Override + public String toString() { + return "prefix: " + metadataPrefix; + } + + }; + } - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Object payload) { - Map userMetadata = (Map) payload; - for (Entry entry : userMetadata.entrySet()) { - if (entry.getKey().startsWith(metadataPrefix)) { - request.getHeaders().put(entry.getKey().toLowerCase(), entry.getValue()); - } else { - request.getHeaders().put((metadataPrefix + entry.getKey()).toLowerCase(), - entry.getValue()); - } - } + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Maps!"); + checkNotNull(request, "request"); + + @SuppressWarnings("unchecked") + Map userMetadata = Maps2.transformKeys((Map) input, FN); + return ModifyRequest.putHeaders(request, Multimaps.forMap(userMetadata)); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefix.java b/blobstore/src/main/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefix.java index 80f9cfa757..b87e5c4dd4 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefix.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefix.java @@ -19,10 +19,10 @@ package org.jclouds.blobstore.binders; -import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; -import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.blobstore.domain.Blob; @@ -35,20 +35,17 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindUserMetadataToHeadersWithPrefix implements Binder { - private final String metadataPrefix; + private final BindMapToHeadersWithPrefix metadataPrefixer; @Inject - public BindUserMetadataToHeadersWithPrefix( - @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { - this.metadataPrefix = metadataPrefix; + public BindUserMetadataToHeadersWithPrefix(BindMapToHeadersWithPrefix metadataPrefixer) { + this.metadataPrefixer = checkNotNull(metadataPrefixer, "metadataPrefixer"); } - public void bindToRequest(HttpRequest request, Object payload) { - Blob object = (Blob) payload; - - for (String key : object.getMetadata().getUserMetadata().keySet()) { - request.getHeaders().put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, - object.getMetadata().getUserMetadata().get(key)); - } + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof Blob, "this binder is only valid for Blobs!"); + checkNotNull(request, "request"); + return metadataPrefixer.bindToRequest(request, Blob.class.cast(input).getMetadata().getUserMetadata()); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java index 7a347eaf46..7fc17ca16f 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java @@ -45,10 +45,8 @@ public class StorageMetadataImpl extends ResourceMetadataImpl imple @Nullable private final String eTag; - @Nullable private final Date lastModified; - private final StorageType type; public StorageMetadataImpl(StorageType type, @Nullable String id, @Nullable String name, diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobName.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobName.java index 2f4e4d71d2..7da54ff2ad 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobName.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobName.java @@ -19,8 +19,11 @@ package org.jclouds.blobstore.functions; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import javax.inject.Singleton; + import org.jclouds.blobstore.domain.Blob; import com.google.common.base.Function; @@ -29,10 +32,13 @@ import com.google.common.base.Function; * * @author Adrian Cole */ +@Singleton public class BlobName implements Function { - public String apply(Object from) { - return checkNotNull(((Blob) from).getMetadata().getName(), "blobName"); + public String apply(Object input) { + checkArgument(checkNotNull(input, "input") instanceof Blob, "this function is only valid for Blobs!"); + + return checkNotNull(Blob.class.cast(input).getMetadata().getName(), "blobName"); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobToHttpGetOptions.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobToHttpGetOptions.java index 2872151443..3c75da3175 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobToHttpGetOptions.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/BlobToHttpGetOptions.java @@ -19,6 +19,8 @@ package org.jclouds.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Singleton; import org.jclouds.http.options.GetOptions; @@ -29,33 +31,34 @@ import com.google.common.base.Function; * @author Adrian Cole */ @Singleton -public class BlobToHttpGetOptions implements - Function { +public class BlobToHttpGetOptions implements Function { + @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { + checkNotNull(from, "options"); + if (from == org.jclouds.blobstore.options.GetOptions.NONE) + return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); - if (from != null && from != org.jclouds.blobstore.options.GetOptions.NONE) { - if (from.getIfMatch() != null) { - httpOptions.ifETagMatches(from.getIfMatch()); - } - if (from.getIfModifiedSince() != null) { - httpOptions.ifModifiedSince(from.getIfModifiedSince()); - } - if (from.getIfNoneMatch() != null) { - httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); - } - if (from.getIfUnmodifiedSince() != null) { - httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); - } - for (String range : from.getRanges()) { - String[] firstLast = range.split("\\-"); - if (firstLast.length == 2) - httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); - else if (range.startsWith("-")) - httpOptions.tail(Long.parseLong(firstLast[0])); - else - httpOptions.startAt(Long.parseLong(firstLast[0])); - } + if (from.getIfMatch() != null) { + httpOptions.ifETagMatches(from.getIfMatch()); + } + if (from.getIfModifiedSince() != null) { + httpOptions.ifModifiedSince(from.getIfModifiedSince()); + } + if (from.getIfNoneMatch() != null) { + httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); + } + if (from.getIfUnmodifiedSince() != null) { + httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); + } + for (String range : from.getRanges()) { + String[] firstLast = range.split("\\-"); + if (firstLast.length == 2) + httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); + else if (range.startsWith("-")) + httpOptions.tail(Long.parseLong(firstLast[0])); + else + httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ClearAndDeleteIfNotEmpty.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ClearAndDeleteIfNotEmpty.java deleted file mode 100644 index 4c579c7720..0000000000 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ClearAndDeleteIfNotEmpty.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * - * 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.blobstore.functions; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.jclouds.util.Utils.propagateOrNull; - -import org.jclouds.blobstore.BlobStore; -import org.jclouds.blobstore.internal.BlobRuntimeException; -import org.jclouds.blobstore.strategy.ClearContainerStrategy; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpResponseException; -import org.jclouds.rest.InvocationContext; -import org.jclouds.rest.internal.GeneratedHttpRequest; - -import com.google.common.base.Function; -import com.google.common.base.Throwables; -import com.google.inject.Inject; - -public class ClearAndDeleteIfNotEmpty implements Function, InvocationContext { - - private final ClearContainerStrategy clear; - private final BlobStore connection; - - private GeneratedHttpRequest request; - - @Inject - protected ClearAndDeleteIfNotEmpty(ClearContainerStrategy clear, BlobStore connection) { - this.clear = clear; - this.connection = connection; - } - - public Void apply(Exception from) { - if (from instanceof HttpResponseException) { - HttpResponseException responseException = (HttpResponseException) from; - if (responseException.getResponse().getStatusCode() == 404) { - return null; - } else if (responseException.getResponse().getStatusCode() == 409) { - clear.execute(request.getArgs()[0].toString()); - try { - connection.deleteContainer(request.getArgs()[0].toString()); - return null; - } catch (Exception e) { - Throwables.propagateIfPossible(e, BlobRuntimeException.class); - throw new BlobRuntimeException("Error deleting container: " - + request.getArgs()[0].toString(), e); - } - } - } - return Void.class.cast(propagateOrNull(from)); - } - - @Override - public ClearAndDeleteIfNotEmpty setContext(HttpRequest request) { - checkArgument(request instanceof GeneratedHttpRequest, - "note this handler requires a GeneratedHttpRequest"); - this.request = (GeneratedHttpRequest) request; - return this; - } - -} diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/HttpGetOptionsListToGetOptions.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/HttpGetOptionsListToGetOptions.java index 08c0824207..e31204ef8a 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/HttpGetOptionsListToGetOptions.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/HttpGetOptionsListToGetOptions.java @@ -17,39 +17,68 @@ * ==================================================================== */ +/** + * + * 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.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Date; import javax.inject.Inject; +import javax.inject.Singleton; import org.jclouds.blobstore.options.GetOptions; import org.jclouds.date.DateService; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; +/** + * + * @author Adrian Cole + */ +@Singleton public class HttpGetOptionsListToGetOptions implements - Function { + Function { private final DateService dateService; @Inject HttpGetOptionsListToGetOptions(DateService dateService) { - this.dateService = dateService; + this.dateService = checkNotNull(dateService, "dateService"); } public GetOptions apply(org.jclouds.http.options.GetOptions[] from) { + checkNotNull(from, "options"); + org.jclouds.blobstore.options.GetOptions to = new org.jclouds.blobstore.options.GetOptions(); if (from.length != 0) { if (from[0].getIfMatch() != null) { - to.ifETagMatches(Utils.replaceAll(from[0].getIfMatch(), '"', "")); + to.ifETagMatches(Strings2.replaceAll(from[0].getIfMatch(), '"', "")); } if (from[0].getIfModifiedSince() != null) { Date time = dateService.rfc822DateParse(from[0].getIfModifiedSince()); to.ifModifiedSince(time); } if (from[0].getIfNoneMatch() != null) { - to.ifETagDoesntMatch(Utils.replaceAll(from[0].getIfNoneMatch(), '"', "")); + to.ifETagDoesntMatch(Strings2.replaceAll(from[0].getIfNoneMatch(), '"', "")); } if (from[0].getIfUnmodifiedSince() != null) { Date time = dateService.rfc822DateParse(from[0].getIfUnmodifiedSince()); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ObjectMD5.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ObjectMD5.java index a88b208057..a0f6c99df3 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ObjectMD5.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ObjectMD5.java @@ -19,43 +19,50 @@ package org.jclouds.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import java.io.IOException; import javax.inject.Inject; +import javax.inject.Singleton; -import org.jclouds.blobstore.domain.Blob; import org.jclouds.crypto.Crypto; +import org.jclouds.http.HttpMessage; +import org.jclouds.io.PayloadEnclosing; import org.jclouds.io.Payloads; import com.google.common.base.Function; import com.google.common.base.Throwables; +/** + * + * @author Adrian Cole + */ +@Singleton public class ObjectMD5 implements Function { - protected final Blob.Factory blobFactory; protected final Crypto crypto; @Inject - ObjectMD5(Crypto crypto, Blob.Factory blobFactory) { - this.blobFactory = blobFactory; - this.crypto = crypto; + ObjectMD5(Crypto crypto) { + this.crypto = checkNotNull(crypto, "crypto"); } public byte[] apply(Object from) { - Blob object; - if (from instanceof Blob) { - object = (Blob) from; + checkNotNull(from, "thing to md5"); + PayloadEnclosing payloadEnclosing; + if (from instanceof PayloadEnclosing) { + payloadEnclosing = (PayloadEnclosing) from; } else { - object = blobFactory.create(null); - object.setPayload(Payloads.newPayload(from)); + payloadEnclosing = HttpMessage.builder().payload(Payloads.newPayload(from)).build(); } - if (object.getMetadata().getContentMetadata().getContentMD5() == null) + if (payloadEnclosing.getPayload().getContentMetadata().getContentMD5() == null) try { - Payloads.calculateMD5(object, crypto.md5()); + Payloads.calculateMD5(payloadEnclosing, crypto.md5()); } catch (IOException e) { Throwables.propagate(e); } - return object.getPayload().getContentMetadata().getContentMD5(); + return payloadEnclosing.getPayload().getContentMetadata().getContentMD5(); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContent.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContent.java index 9a4395a62b..016d92ef34 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContent.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContent.java @@ -19,6 +19,8 @@ package org.jclouds.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Inject; import org.jclouds.blobstore.domain.Blob; @@ -36,23 +38,24 @@ import com.google.common.base.Function; * @author Adrian Cole */ public class ParseBlobFromHeadersAndHttpContent implements Function, - InvocationContext { + InvocationContext { private final ParseSystemAndUserMetadataFromHeaders metadataParser; private final Blob.Factory blobFactory; @Inject public ParseBlobFromHeadersAndHttpContent(ParseSystemAndUserMetadataFromHeaders metadataParser, - Blob.Factory blobFactory) { - this.metadataParser = metadataParser; - this.blobFactory = blobFactory; + Blob.Factory blobFactory) { + this.metadataParser = checkNotNull(metadataParser, "metadataParser"); + this.blobFactory = checkNotNull(blobFactory, "blobFactory"); } public Blob apply(HttpResponse from) { + checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); - Blob object = blobFactory.create(metadata); - object.getAllHeaders().putAll(from.getHeaders()); - object.setPayload(from.getPayload()); - return object; + Blob blob = blobFactory.create(metadata); + blob.getAllHeaders().putAll(from.getHeaders()); + blob.setPayload(from.getPayload()); + return blob; } @Override 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 9af2635e36..c4e8d68e0a 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java @@ -20,9 +20,11 @@ package org.jclouds.blobstore.functions; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; -import static org.jclouds.blobstore.util.BlobStoreUtils.getKeyFor; +import static org.jclouds.blobstore.util.BlobStoreUtils.getNameFor; import java.util.Map.Entry; @@ -47,27 +49,29 @@ import com.google.common.base.Function; * @author Adrian Cole */ public class ParseSystemAndUserMetadataFromHeaders implements Function, - InvocationContext { + InvocationContext { private final String metadataPrefix; private final DateService dateParser; private final Provider metadataFactory; private final String apiVersion; - private GeneratedHttpRequest request; + private String key; @Inject 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; - this.apiVersion = apiVersion; + @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix, @Named(PROPERTY_API_VERSION) String apiVersion) { + this.metadataFactory = checkNotNull(metadataFactory, "metadataFactory"); + this.dateParser = checkNotNull(dateParser, "dateParser"); + this.metadataPrefix = checkNotNull(metadataPrefix, "metadataPrefix"); + this.apiVersion = checkNotNull(metadataPrefix, "metadataPrefix"); } public MutableBlobMetadata apply(HttpResponse from) { - String objectKey = getKeyFor(request, from); + checkNotNull(from, "request"); + checkState(key != null, "key must be initialized by now"); + MutableBlobMetadata to = metadataFactory.get(); - to.setName(objectKey); + to.setName(key); HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); @@ -80,7 +84,7 @@ public class ParseSystemAndUserMetadataFromHeaders implements Function header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), - header.getValue()); + header.getValue()); } } @@ -90,7 +94,8 @@ public class ParseSystemAndUserMetadataFromHeaders implements Function, "note this handler requires a GeneratedHttpRequest"); - this.request = (GeneratedHttpRequest) request; + setName(getNameFor(GeneratedHttpRequest.class.cast(request))); return this; } + + @VisibleForTesting + void setName(String key) { + this.key = checkNotNull(key, "key"); + } } \ No newline at end of file diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/PrefixToResourceMetadata.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/PrefixToResourceMetadata.java index 14214a528b..d897882c87 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/PrefixToResourceMetadata.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/PrefixToResourceMetadata.java @@ -19,6 +19,8 @@ package org.jclouds.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Singleton; import org.jclouds.blobstore.domain.MutableStorageMetadata; @@ -35,6 +37,7 @@ import com.google.common.base.Function; public class PrefixToResourceMetadata implements Function { public StorageMetadata apply(String from) { + checkNotNull(from, "prefix"); MutableStorageMetadata returnVal = new MutableStorageMetadataImpl(); returnVal.setType(StorageType.RELATIVE_PATH); returnVal.setName(from); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadata.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadata.java index e1d23b0707..4ab213ca63 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadata.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadata.java @@ -19,6 +19,8 @@ package org.jclouds.blobstore.functions; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Singleton; import org.jclouds.blobstore.domain.StorageMetadata; @@ -28,17 +30,21 @@ import org.jclouds.blobstore.reference.BlobStoreConstants; import com.google.common.base.Function; +/** + * @author Adrian Cole + */ @Singleton public class ResourceMetadataToRelativePathResourceMetadata implements Function { public StorageMetadata apply(StorageMetadata md) { - String name = md.getName(); + checkNotNull(md, "metadata"); + String name = checkNotNull(md.getName(), "metadata.name"); for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) { if (name.endsWith(suffix)) name = name.substring(0, name.length() - suffix.length()); } return new StorageMetadataImpl(StorageType.RELATIVE_PATH, md.getProviderId(), name, md.getLocation(), - md.getUri(), md.getETag(), md.getLastModified(), md.getUserMetadata()); + md.getUri(), md.getETag(), md.getLastModified(), md.getUserMetadata()); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFound.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFound.java index 8241d5ca08..286a1c2264 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFound.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFound.java @@ -19,7 +19,8 @@ package org.jclouds.blobstore.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; @@ -35,7 +36,7 @@ import com.google.common.base.Function; public class ReturnFalseOnContainerNotFound implements Function { public Boolean apply(Exception from) { - if (from instanceof ContainerNotFoundException) { + if (checkNotNull(from, "exception") instanceof ContainerNotFoundException) { return false; } return Boolean.class.cast(propagateOrNull(from)); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFound.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFound.java index de16dc2904..1b70e10f49 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFound.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFound.java @@ -19,7 +19,7 @@ package org.jclouds.blobstore.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFound.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFound.java index cd377ca156..e4cb769ffe 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFound.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFound.java @@ -19,7 +19,7 @@ package org.jclouds.blobstore.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFound.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFound.java index a369c7101e..88851838b5 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFound.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFound.java @@ -19,7 +19,7 @@ package org.jclouds.blobstore.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404.java index 81e2da38bf..bd0081e5d9 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404.java @@ -19,7 +19,7 @@ package org.jclouds.blobstore.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import org.jclouds.blobstore.ContainerNotFoundException; import org.jclouds.http.HttpResponseException; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404.java index 84db36b155..4631af772c 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404.java @@ -19,7 +19,7 @@ package org.jclouds.blobstore.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import org.jclouds.blobstore.KeyNotFoundException; import org.jclouds.http.HttpResponseException; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java index 7f9cea4159..cd2abe904c 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java @@ -41,7 +41,7 @@ import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.blobstore.util.internal.BlobUtilsImpl; import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; -import org.jclouds.util.Utils; +import org.jclouds.util.Assertions; import com.google.common.base.Supplier; import com.google.common.util.concurrent.Futures; @@ -243,7 +243,7 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore { protected void deleteAndEnsurePathGone(final String container) { try { - if (!Utils.eventuallyTrue(new Supplier() { + if (!Assertions.eventuallyTrue(new Supplier() { public Boolean get() { try { clearContainer(container, recursive()); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java index 736b8c56f9..3ca6a77004 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java @@ -37,7 +37,7 @@ import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.blobstore.util.internal.BlobUtilsImpl; import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; -import org.jclouds.util.Utils; +import org.jclouds.util.Assertions; import com.google.common.base.Supplier; @@ -196,7 +196,7 @@ public abstract class BaseBlobStore implements BlobStore { protected void clearAndDeleteContainer(final String container) { try { - if (!Utils.eventuallyTrue(new Supplier() { + if (!Assertions.eventuallyTrue(new Supplier() { public Boolean get() { try { clearContainer(container, recursive()); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/internal/BlobStoreContextImpl.java b/blobstore/src/main/java/org/jclouds/blobstore/internal/BlobStoreContextImpl.java index 080e810535..c275702596 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/internal/BlobStoreContextImpl.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/internal/BlobStoreContextImpl.java @@ -53,7 +53,7 @@ public class BlobStoreContextImpl implements BlobStoreContext { @Inject public BlobStoreContextImpl(BlobMap.Factory blobMapFactory, Utils utils, ConsistencyModel consistencyModel, InputStreamMap.Factory inputStreamMapFactory, AsyncBlobStore ablobStore, BlobStore blobStore, - RestContext providerSpecificContext, BlobRequestSigner blobRequestSigner) { + @SuppressWarnings("rawtypes") RestContext providerSpecificContext, BlobRequestSigner blobRequestSigner) { // unravel guice and avoid passing in a million type args by not injecting generic types for // rest context this.providerSpecificContext = checkNotNull(providerSpecificContext, "providerSpecificContext"); diff --git a/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java b/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java index ba55361485..9ad8067d59 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java @@ -79,10 +79,8 @@ public class GetOptions { * Not compatible with {@link #ifETagMatches(String)} or {@link #ifUnmodifiedSince(Date)} */ public GetOptions ifModifiedSince(Date ifModifiedSince) { - checkArgument(getIfMatch() == null, - "ifETagMatches() is not compatible with ifModifiedSince()"); - checkArgument(getIfUnmodifiedSince() == null, - "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); + checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifModifiedSince()"); + checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); this.ifModifiedSince = checkNotNull(ifModifiedSince, "ifModifiedSince"); return this; } @@ -105,10 +103,8 @@ public class GetOptions { * Not compatible with {@link #ifETagDoesntMatch(String)} or {@link #ifModifiedSince(Date)} */ public GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince) { - checkArgument(getIfNoneMatch() == null, - "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); - checkArgument(getIfModifiedSince() == null, - "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); + checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); + checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); this.ifUnmodifiedSince = checkNotNull(ifUnmodifiedSince, "ifUnmodifiedSince"); return this; } @@ -135,10 +131,8 @@ public class GetOptions { * hash representing the payload */ public GetOptions ifETagMatches(String eTag) { - checkArgument(getIfNoneMatch() == null, - "ifETagDoesntMatch() is not compatible with ifETagMatches()"); - checkArgument(getIfModifiedSince() == null, - "ifModifiedSince() is not compatible with ifETagMatches()"); + checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); + checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.ifMatch = checkNotNull(eTag, "eTag"); return this; } @@ -164,10 +158,8 @@ public class GetOptions { * hash representing the payload */ public GetOptions ifETagDoesntMatch(String eTag) { - checkArgument(getIfMatch() == null, - "ifETagMatches() is not compatible with ifETagDoesntMatch()"); - checkArgument(getIfUnmodifiedSince() == null, - "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); + checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); + checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.ifNoneMatch = checkNotNull(eTag, "eTag"); return this; } @@ -231,4 +223,60 @@ public class GetOptions { } } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((ifMatch == null) ? 0 : ifMatch.hashCode()); + result = prime * result + ((ifModifiedSince == null) ? 0 : ifModifiedSince.hashCode()); + result = prime * result + ((ifNoneMatch == null) ? 0 : ifNoneMatch.hashCode()); + result = prime * result + ((ifUnmodifiedSince == null) ? 0 : ifUnmodifiedSince.hashCode()); + result = prime * result + ((ranges == null) ? 0 : ranges.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; + GetOptions other = (GetOptions) obj; + if (ifMatch == null) { + if (other.ifMatch != null) + return false; + } else if (!ifMatch.equals(other.ifMatch)) + return false; + if (ifModifiedSince == null) { + if (other.ifModifiedSince != null) + return false; + } else if (!ifModifiedSince.equals(other.ifModifiedSince)) + return false; + if (ifNoneMatch == null) { + if (other.ifNoneMatch != null) + return false; + } else if (!ifNoneMatch.equals(other.ifNoneMatch)) + return false; + if (ifUnmodifiedSince == null) { + if (other.ifUnmodifiedSince != null) + return false; + } else if (!ifUnmodifiedSince.equals(other.ifUnmodifiedSince)) + return false; + if (ranges == null) { + if (other.ranges != null) + return false; + } else if (!ranges.equals(other.ranges)) + return false; + return true; + } + + @Override + public String toString() { + return "[ranges=" + ranges + ", ifModifiedSince=" + ifModifiedSince + ", ifUnmodifiedSince=" + + ifUnmodifiedSince + ", ifMatch=" + ifMatch + ", ifNoneMatch=" + ifNoneMatch + "]"; + } + } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkersIfDirectoryReturnNameStrategy.java b/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkersIfDirectoryReturnNameStrategy.java index cd1340ffc1..bb4a99b11a 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkersIfDirectoryReturnNameStrategy.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkersIfDirectoryReturnNameStrategy.java @@ -32,25 +32,25 @@ import org.jclouds.blobstore.strategy.IfDirectoryReturnNameStrategy; */ @Singleton public class MarkersIfDirectoryReturnNameStrategy implements IfDirectoryReturnNameStrategy { - + @Override public String execute(StorageMetadata metadata) { switch (metadata.getType()) { - case CONTAINER: - case FOLDER: - case RELATIVE_PATH: - return metadata.getName(); - case BLOB: - BlobMetadata blobMd = (BlobMetadata) metadata; - for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) { - if (metadata.getName().endsWith(suffix)) { - return metadata.getName().substring(0, metadata.getName().lastIndexOf(suffix)); - } + case CONTAINER: + case FOLDER: + case RELATIVE_PATH: + return metadata.getName(); + case BLOB: + BlobMetadata blobMd = (BlobMetadata) metadata; + for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) { + if (metadata.getName().endsWith(suffix)) { + return metadata.getName().substring(0, metadata.getName().lastIndexOf(suffix)); } - // It is important that this is last, in case there is a file with a known directory - // suffix who also has content type set to application/directory - if (blobMd.getContentMetadata().getContentType() != null - && blobMd.getContentMetadata().getContentType().equals("application/directory")) - return metadata.getName(); + } + // It is important that this is last, in case there is a file with a known directory + // suffix who also has content type set to application/directory + if (blobMd.getContentMetadata().getContentType() != null + && blobMd.getContentMetadata().getContentType().equals("application/directory")) + return metadata.getName(); } return null; } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/util/BlobStoreUtils.java b/blobstore/src/main/java/org/jclouds/blobstore/util/BlobStoreUtils.java index a81bd44cad..8372e1a896 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/util/BlobStoreUtils.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/util/BlobStoreUtils.java @@ -20,8 +20,6 @@ package org.jclouds.blobstore.util; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.getSupportedProvidersOfType; -import static org.jclouds.util.Utils.toStringAndClose; import java.io.IOException; import java.io.InputStream; @@ -36,36 +34,40 @@ import org.jclouds.blobstore.KeyNotFoundException; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.StorageMetadata; +import org.jclouds.blobstore.functions.BlobName; import org.jclouds.functions.ExceptionToValueOrPropagate; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; -import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpUtils; +import org.jclouds.rest.Providers; import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.util.Strings2; import com.google.common.collect.ImmutableMultimap; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; /** * * @author Adrian Cole */ public class BlobStoreUtils { - public static HttpRequest cleanRequest(GeneratedHttpRequest returnVal) { + public static HttpRequest cleanRequest(HttpRequest returnVal) { + checkNotNull(returnVal, "http request"); for (HttpRequestFilter filter : returnVal.getFilters()) - filter.filter(returnVal); - HttpRequest toReturn = new HttpRequest(returnVal.getMethod(), returnVal.getEndpoint(), ImmutableMultimap - .copyOf(returnVal.getHeaders())); + returnVal = filter.filter(returnVal); + HttpRequest toReturn = new HttpRequest(returnVal.getMethod(), returnVal.getEndpoint(), + ImmutableMultimap.copyOf(returnVal.getHeaders())); if (returnVal.getPayload() != null) toReturn.setPayload(returnVal.getPayload()); return toReturn; } - @SuppressWarnings("unchecked") - public static final ExceptionToValueOrPropagate keyNotFoundToNullOrPropagate = new ExceptionToValueOrPropagate( - KeyNotFoundException.class, null); - @SuppressWarnings("unchecked") - public static final ExceptionToValueOrPropagate containerNotFoundToNullOrPropagate = new ExceptionToValueOrPropagate( - ContainerNotFoundException.class, null); + public static final ExceptionToValueOrPropagate keyNotFoundToNullOrPropagate = new ExceptionToValueOrPropagate( + KeyNotFoundException.class, null); + + public static final ExceptionToValueOrPropagate containerNotFoundToNullOrPropagate = new ExceptionToValueOrPropagate( + ContainerNotFoundException.class, null); @SuppressWarnings("unchecked") public static T keyNotFoundToNullOrPropagate(Exception e) { @@ -78,7 +80,7 @@ public class BlobStoreUtils { } public static Blob newBlob(BlobStore blobStore, StorageMetadata blobMeta) { - Blob blob = blobStore.newBlob(blobMeta.getName()); + Blob blob = checkNotNull(blobStore, "blobStore").newBlob(checkNotNull(blobMeta, "blobMeta").getName()); if (blobMeta instanceof BlobMetadata) { HttpUtils.copy(((BlobMetadata) blobMeta).getContentMetadata(), blob.getMetadata().getContentMetadata()); } @@ -92,7 +94,7 @@ public class BlobStoreUtils { } public static String parseContainerFromPath(String path) { - String container = path; + String container = checkNotNull(path, "path"); if (path.indexOf('/') != -1) container = path.substring(0, path.indexOf('/')); return container; @@ -100,26 +102,25 @@ public class BlobStoreUtils { public static String parsePrefixFromPath(String path) { String prefix = null; - if (path.indexOf('/') != -1) + if (checkNotNull(path, "path").indexOf('/') != -1) prefix = path.substring(path.indexOf('/') + 1); return "".equals(prefix) ? null : prefix; } public static String parseDirectoryFromPath(String path) { - return path.substring(0, path.lastIndexOf('/')); + return checkNotNull(path, "path").substring(0, path.lastIndexOf('/')); } private static Pattern keyFromContainer = Pattern.compile("/?[^/]+/(.*)"); - public static String getKeyFor(GeneratedHttpRequest request, HttpResponse from) { + public static String getNameFor(GeneratedHttpRequest request) { checkNotNull(request, "request"); - checkNotNull(from, "from"); // assume first params are container and key - if (request.getArgs().length >= 2 && request.getArgs()[0] instanceof String - && request.getArgs()[1] instanceof String) { - return request.getArgs()[1].toString(); - } else if (request.getArgs().length >= 1 && request.getArgs()[0] instanceof String) { - Matcher matcher = keyFromContainer.matcher(request.getArgs()[0].toString()); + if (request.getArgs().size() >= 2 && request.getArgs().get(0) instanceof String + && request.getArgs().get(1) instanceof String) { + return request.getArgs().get(1).toString(); + } else if (request.getArgs().size() >= 1 && request.getArgs().get(0) instanceof String) { + Matcher matcher = keyFromContainer.matcher(request.getArgs().get(0).toString()); if (matcher.find()) return matcher.group(1); } @@ -138,20 +139,28 @@ public class BlobStoreUtils { return null; Object o = blob.getPayload().getInput(); if (o instanceof InputStream) { - return toStringAndClose((InputStream) o); + return Strings2.toStringAndClose((InputStream) o); } else { throw new IllegalArgumentException("Object type not supported: " + o.getClass().getName()); } } - public static void createParentIfNeededAsync(AsyncBlobStore asyncBlobStore, String container, Blob blob) { - String name = blob.getMetadata().getName(); + private static final BlobName blobName = new BlobName(); + + public static ListenableFuture createParentIfNeededAsync(AsyncBlobStore asyncBlobStore, String container, + Blob blob) { + checkNotNull(asyncBlobStore, "asyncBlobStore"); + checkNotNull(container, "container"); + + String name = blobName.apply(blob); if (name.indexOf('/') > 0) { - asyncBlobStore.createDirectory(container, parseDirectoryFromPath(name)); + return asyncBlobStore.createDirectory(container, parseDirectoryFromPath(name)); + } else { + return Futures.immediateFuture(null); } } public static Iterable getSupportedProviders() { - return getSupportedProvidersOfType(BlobStoreContextBuilder.class); + return Providers.getSupportedProvidersOfType(BlobStoreContextBuilder.class); } } \ No newline at end of file diff --git a/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj b/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj index 2b1ec948f9..8ab2988eb1 100644 --- a/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj +++ b/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj @@ -22,7 +22,7 @@ (:use [clojure.test]) (:import [org.jclouds.blobstore BlobStoreContextFactory] [java.io ByteArrayOutputStream] - [org.jclouds.util Utils])) + [org.jclouds.util Strings2])) (defn clean-stub-fixture "This should allow basic tests to easily be run with another service." @@ -80,7 +80,7 @@ (is (create-container "blob")) (is (upload-blob "blob" "blob1" "blob1")) (is (upload-blob "blob" "blob2" "blob2")) - (is (= "blob2" (Utils/toStringAndClose (get-blob-stream "blob" "blob2"))))) + (is (= "blob2" (Strings2/toStringAndClose (get-blob-stream "blob" "blob2"))))) (deftest download-blob-test (let [name "test" diff --git a/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java b/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java index 940b52f1c6..3c6df510f9 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java @@ -37,7 +37,13 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; -@Test(groups = "unit", testName = "jclouds.TransientBlobRequestSignerTest") +/** + * Tests behavior of {@code TransientBlobRequestSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TransientBlobRequestSignerTest") public class TransientBlobRequestSignerTest extends RestClientTest { private BlobRequestSigner signer; diff --git a/blobstore/src/test/java/org/jclouds/blobstore/binders/BindBlobToMultipartFormTest.java b/blobstore/src/test/java/org/jclouds/blobstore/binders/BindBlobToMultipartFormTest.java index 14ee275594..c30e036717 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/binders/BindBlobToMultipartFormTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/binders/BindBlobToMultipartFormTest.java @@ -20,18 +20,20 @@ package org.jclouds.blobstore.binders; import static org.jclouds.io.payloads.MultipartForm.BOUNDARY; -import static org.jclouds.util.Utils.toStringAndClose; import static org.testng.Assert.assertEquals; +import java.io.File; import java.io.IOException; import java.net.URI; +import javax.ws.rs.HttpMethod; import javax.ws.rs.core.MediaType; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob.Factory; import org.jclouds.http.HttpRequest; import org.jclouds.rest.RestContextFactory; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; /** @@ -47,7 +49,7 @@ public class BindBlobToMultipartFormTest { static { blobProvider = new RestContextFactory().createContextBuilder("transient", "identity", "credential") - .buildInjector().getInstance(Blob.Factory.class); + .buildInjector().getInstance(Blob.Factory.class); StringBuilder builder = new StringBuilder("--"); addData(BOUNDARY, "hello", builder); builder.append("--").append(BOUNDARY).append("--").append("\r\n"); @@ -67,11 +69,11 @@ public class BindBlobToMultipartFormTest { HttpRequest request = new HttpRequest("GET", URI.create("http://localhost:8001")); binder.bindToRequest(request, TEST_BLOB); - assertEquals(toStringAndClose(request.getPayload().getInput()), EXPECTS); + assertEquals(Strings2.toStringAndClose(request.getPayload().getInput()), EXPECTS); assertEquals(request.getPayload().getContentMetadata().getContentLength(), new Long(113)); assertEquals(request.getPayload().getContentMetadata().getContentType(), "multipart/form-data; boundary=" - + BOUNDARY); + + BOUNDARY); } private static void addData(String boundary, String data, StringBuilder builder) { @@ -82,4 +84,17 @@ public class BindBlobToMultipartFormTest { builder.append(data).append("\r\n"); } + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeBlob() { + BindBlobToMultipartForm binder = new BindBlobToMultipartForm(); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + BindBlobToMultipartForm binder = new BindBlobToMultipartForm(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefixTest.java b/blobstore/src/test/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefixTest.java new file mode 100644 index 0000000000..2e54afaf22 --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefixTest.java @@ -0,0 +1,68 @@ +/** + * + * 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.blobstore.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindMapToHeadersWithPrefixTest { + + @Test + public void testCorrect() throws SecurityException, NoSuchMethodException { + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); + + assertEquals( + binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")), + HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")) + .headers(ImmutableMultimap.of("prefix:imagename", "foo", "prefix:serverid", "2")).build()); + + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeMap() { + BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefixTest.java b/blobstore/src/test/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefixTest.java new file mode 100644 index 0000000000..a254fa872c --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefixTest.java @@ -0,0 +1,76 @@ +/** + * + * 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.blobstore.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.blobstore.domain.Blob; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.RestContextFactory; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BindUserMetadataToHeadersWithPrefixTest { + + @Test + public void testCorrect() throws SecurityException, NoSuchMethodException { + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + BindUserMetadataToHeadersWithPrefix binder = new BindUserMetadataToHeadersWithPrefix( + new BindMapToHeadersWithPrefix("prefix:")); + + Blob blob = new RestContextFactory().createContextBuilder("transient", "identity", "credential").buildInjector() + .getInstance(Blob.Factory.class).create(null); + blob.getMetadata().setUserMetadata(ImmutableMap.of("imageName", "foo", "serverId", "2")); + + assertEquals( + binder.bindToRequest(request, blob), + HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")) + .headers(ImmutableMultimap.of("prefix:imagename", "foo", "prefix:serverid", "2")).build()); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeBlob() { + BindUserMetadataToHeadersWithPrefix binder = new BindUserMetadataToHeadersWithPrefix( + new BindMapToHeadersWithPrefix("prefix:")); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + binder.bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + BindUserMetadataToHeadersWithPrefix binder = new BindUserMetadataToHeadersWithPrefix( + new BindMapToHeadersWithPrefix("prefix:")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobNameTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobNameTest.java new file mode 100644 index 0000000000..df731b8c1e --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobNameTest.java @@ -0,0 +1,59 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import java.io.File; + +import org.jclouds.blobstore.domain.Blob; +import org.jclouds.blobstore.domain.Blob.Factory; +import org.jclouds.rest.RestContextFactory; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BlobNameTest { + BlobName fn = new BlobName(); + private static final Factory BLOB_FACTORY = new RestContextFactory() + .createContextBuilder("transient", "identity", "credential").buildInjector().getInstance(Blob.Factory.class); + + @Test + public void testCorrect() throws SecurityException, NoSuchMethodException { + + Blob blob = BLOB_FACTORY.create(null); + blob.getMetadata().setName("foo"); + + assertEquals(fn.apply(blob), "foo"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeBlob() { + fn.apply(new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobToHttpGetOptionsTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobToHttpGetOptionsTest.java new file mode 100644 index 0000000000..9b54bd74fa --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobToHttpGetOptionsTest.java @@ -0,0 +1,112 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import java.util.Date; + +import org.jclouds.http.options.GetOptions; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class BlobToHttpGetOptionsTest { + BlobToHttpGetOptions fn = new BlobToHttpGetOptions(); + + @Test + public void testNoneReturnsNone() { + assertEquals(fn.apply(org.jclouds.blobstore.options.GetOptions.NONE), GetOptions.NONE); + } + + @Test + public void testIfUnmodifiedSince() { + + Date ifUnmodifiedSince = new Date(999999l); + + org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); + in.ifUnmodifiedSince(ifUnmodifiedSince); + GetOptions expected = new GetOptions(); + expected.ifUnmodifiedSince(ifUnmodifiedSince); + + assertEquals(fn.apply(in), expected); + } + + @Test + public void testIfModifiedSince() { + + Date ifModifiedSince = new Date(999999l); + + org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); + in.ifModifiedSince(ifModifiedSince); + GetOptions expected = new GetOptions(); + expected.ifModifiedSince(ifModifiedSince); + + assertEquals(fn.apply(in), expected); + } + + public void testIfUnmatch() { + + String ifUnmatch = "foo"; + + org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); + in.ifETagDoesntMatch(ifUnmatch); + GetOptions expected = new GetOptions(); + expected.ifETagDoesntMatch(ifUnmatch); + + assertEquals(fn.apply(in), expected); + } + + @Test + public void testIfMatch() { + + String ifMatch = "foo"; + + org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); + in.ifETagMatches(ifMatch); + + GetOptions expected = new GetOptions(); + expected.ifETagMatches(ifMatch); + + assertEquals(fn.apply(in), expected); + } + + @Test + public void testRanges(){ + org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); + in.range(0,1024); + in.startAt(2048); + + GetOptions expected = new GetOptions(); + expected.range(0,1024); + expected.startAt(2048); + + assertEquals(fn.apply(in), expected); + + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ObjectMD5Test.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ObjectMD5Test.java new file mode 100644 index 0000000000..46d68cb064 --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ObjectMD5Test.java @@ -0,0 +1,75 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.encryption.internal.JCECrypto; +import org.jclouds.http.HttpMessage; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ObjectMD5Test { + private ObjectMD5 fn; + + public ObjectMD5Test() throws NoSuchAlgorithmException, CertificateException { + fn = new ObjectMD5(new JCECrypto()); + } + + @Test + public void testAlreadyHasMD5() { + Payload payload = Payloads.newPayload("foo"); + payload.getContentMetadata().setContentMD5(new byte[] {}); + + HttpMessage payloadEnclosing = HttpMessage.builder().payload(payload).build(); + + assertEquals(fn.apply(payloadEnclosing), new byte[] {}); + } + + @Test + public void testMD5PayloadEnclosing() throws IOException { + Payload payload = Payloads.newPayload("foo"); + + HttpMessage payloadEnclosing = HttpMessage.builder().payload(payload).build(); + + assertEquals(fn.apply(payloadEnclosing), CryptoStreams.md5("foo".getBytes())); + } + + @Test + public void testMD5String() throws IOException { + assertEquals(fn.apply("foo"), CryptoStreams.md5("foo".getBytes())); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java index 72197a6f43..4d3bab11e2 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java @@ -39,6 +39,7 @@ import org.jclouds.io.Payloads; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableMultimap; import com.google.inject.Guice; /** @@ -48,18 +49,14 @@ public class ParseBlobFromHeadersAndHttpContentTest { @BeforeTest void setUp() { - - blobProvider = Guice.createInjector(new BlobStoreObjectModule()).getInstance( - Blob.Factory.class); + blobProvider = Guice.createInjector(new BlobStoreObjectModule()).getInstance(Blob.Factory.class); } @Test(expectedExceptions = NullPointerException.class) public void testCall() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); - ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent( - metadataParser, blobProvider); - HttpResponse response = new HttpResponse(200, null, null); - response.getHeaders().put("Content-Range", null); + ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); + HttpResponse response = new HttpResponse(200, null, null, ImmutableMultimap.of("Content-Range", (String) null)); callable.apply(response); } @@ -75,13 +72,12 @@ public class ParseBlobFromHeadersAndHttpContentTest { @Test public void testParseContentLengthWhenContentRangeSet() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); - ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent( - metadataParser, blobProvider); + ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); - HttpResponse response = new HttpResponse(200, "ok", Payloads.newStringPayload("")); + HttpResponse response = new HttpResponse(200, "ok", Payloads.newStringPayload(""), ImmutableMultimap.of( + "Content-Range", "0-10485759/20232760")); response.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); response.getPayload().getContentMetadata().setContentLength(10485760l); - response.getHeaders().put("Content-Range", "0-10485759/20232760"); MutableBlobMetadata meta = blobMetadataProvider.get(); expect(metadataParser.apply(response)).andReturn(meta); @@ -89,8 +85,7 @@ public class ParseBlobFromHeadersAndHttpContentTest { Blob object = callable.apply(response); assertEquals(object.getPayload().getContentMetadata().getContentLength(), new Long(10485760)); - assertEquals(object.getAllHeaders().get("Content-Range"), Collections - .singletonList("0-10485759/20232760")); + assertEquals(object.getAllHeaders().get("Content-Range"), Collections.singletonList("0-10485759/20232760")); } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java index 73759d7421..442e1dec96 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java @@ -19,13 +19,8 @@ package org.jclouds.blobstore.functions; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; import static org.testng.Assert.assertEquals; -import java.net.URI; - import javax.inject.Provider; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; @@ -37,12 +32,10 @@ import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.http.HttpException; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; /** * @author Adrian Cole @@ -61,22 +54,16 @@ public class ParseSystemAndUserMetadataFromHeadersTest { @BeforeTest void setUp() { - parser = new ParseSystemAndUserMetadataFromHeaders(blobMetadataProvider, new SimpleDateFormatDateService(), - "prefix", "default"); - - GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { "container/key" }).anyTimes(); - replay(request); - parser.setContext(request); + "prefix", "default"); + parser.setName("key"); } @Test - public void testApplySetsKey() { - HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload("")); + public void testApplySetsName() { + HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload(""), ImmutableMultimap.of( + HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT")); from.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); - from.getHeaders().put(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT"); from.getPayload().getContentMetadata().setContentLength(100l); BlobMetadata metadata = parser.apply(from); assertEquals(metadata.getName(), "key"); @@ -84,19 +71,19 @@ public class ParseSystemAndUserMetadataFromHeadersTest { @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"); + HttpResponse from = new HttpResponse(204, "ok", Payloads.newStringPayload(""), ImmutableMultimap.of( + HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT")); parser.apply(from); } @Test public void testSetLastModified() { - HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload("")); - from.getHeaders().put(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT"); + HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload(""), ImmutableMultimap.of( + HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT")); MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.parseLastModifiedOrThrowException(from, metadata); - assertEquals(metadata.getLastModified(), new SimpleDateFormatDateService() - .rfc822DateParse("Wed, 09 Sep 2009 19:50:23 GMT")); + assertEquals(metadata.getLastModified(), + new SimpleDateFormatDateService().rfc822DateParse("Wed, 09 Sep 2009 19:50:23 GMT")); } @Test(expectedExceptions = HttpException.class) @@ -108,8 +95,8 @@ public class ParseSystemAndUserMetadataFromHeadersTest { @Test public void testAddETagTo() { - HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload("")); - from.getHeaders().put(HttpHeaders.ETAG, "0xfeb"); + HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload(""), ImmutableMultimap.of( + HttpHeaders.ETAG, "0xfeb")); MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.addETagTo(from, metadata); assertEquals(metadata.getETag(), "0xfeb"); @@ -117,9 +104,8 @@ public class ParseSystemAndUserMetadataFromHeadersTest { @Test public void testAddUserMetadataTo() { - Multimap allHeaders = ImmutableMultimap.of("prefix" + "key", "value"); - HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload("")); - from.getHeaders().putAll(allHeaders); + HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload(""), ImmutableMultimap.of("prefix" + + "key", "value")); MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.addUserMetadataTo(from, metadata); assertEquals(metadata.getUserMetadata().get("key"), "value"); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/PrefixToResourceMetadataTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/PrefixToResourceMetadataTest.java new file mode 100644 index 0000000000..abdd101974 --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/PrefixToResourceMetadataTest.java @@ -0,0 +1,49 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.blobstore.domain.MutableStorageMetadata; +import org.jclouds.blobstore.domain.StorageType; +import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class PrefixToResourceMetadataTest { + PrefixToResourceMetadata fn = new PrefixToResourceMetadata(); + + @Test + public void testCorrect() throws SecurityException, NoSuchMethodException { + MutableStorageMetadata expected = new MutableStorageMetadataImpl(); + expected.setType(StorageType.RELATIVE_PATH); + expected.setName("foo"); + assertEquals(fn.apply("foo"), expected); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobMetadataToRelativePathResourceMetadataTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadataTest.java similarity index 95% rename from blobstore/src/test/java/org/jclouds/blobstore/functions/BlobMetadataToRelativePathResourceMetadataTest.java rename to blobstore/src/test/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadataTest.java index b71c19b8df..e4448822bb 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/functions/BlobMetadataToRelativePathResourceMetadataTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadataTest.java @@ -29,7 +29,12 @@ import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl; import org.testng.annotations.Test; -public class BlobMetadataToRelativePathResourceMetadataTest { +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ResourceMetadataToRelativePathResourceMetadataTest { private ResourceMetadataToRelativePathResourceMetadata parser = new ResourceMetadataToRelativePathResourceMetadata(); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFoundTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFoundTest.java new file mode 100644 index 0000000000..a8b859001c --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnContainerNotFoundTest.java @@ -0,0 +1,49 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.blobstore.ContainerNotFoundException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ReturnFalseOnContainerNotFoundTest { + ReturnFalseOnContainerNotFound fn = new ReturnFalseOnContainerNotFound(); + + @Test + public void testFoundIsFalse() throws SecurityException, NoSuchMethodException { + assertEquals(fn.apply(new ContainerNotFoundException()), new Boolean(false)); + } + + @Test(expectedExceptions = { RuntimeException.class }) + public void testNotFoundPropagates() throws SecurityException, NoSuchMethodException { + fn.apply(new RuntimeException()); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFoundTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFoundTest.java new file mode 100644 index 0000000000..f85c3bf3fb --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnFalseOnKeyNotFoundTest.java @@ -0,0 +1,49 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.blobstore.KeyNotFoundException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ReturnFalseOnKeyNotFoundTest { + ReturnFalseOnKeyNotFound fn = new ReturnFalseOnKeyNotFound(); + + @Test + public void testFoundIsFalse() throws SecurityException, NoSuchMethodException { + assertEquals(fn.apply(new KeyNotFoundException()), new Boolean(false)); + } + + @Test(expectedExceptions = { RuntimeException.class }) + public void testNotFoundPropagates() throws SecurityException, NoSuchMethodException { + fn.apply(new RuntimeException()); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFoundTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFoundTest.java new file mode 100644 index 0000000000..3d72cb78f2 --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnContainerNotFoundTest.java @@ -0,0 +1,49 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.blobstore.ContainerNotFoundException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ReturnNullOnContainerNotFoundTest { + ReturnNullOnContainerNotFound fn = new ReturnNullOnContainerNotFound(); + + @Test + public void testFoundIsNull() throws SecurityException, NoSuchMethodException { + assertEquals(fn.apply(new ContainerNotFoundException()), null); + } + + @Test(expectedExceptions = RuntimeException.class) + public void testPropagates() throws SecurityException, NoSuchMethodException { + fn.apply(new RuntimeException()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFoundTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFoundTest.java new file mode 100644 index 0000000000..b0e186a0e3 --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ReturnNullOnKeyNotFoundTest.java @@ -0,0 +1,49 @@ +/** + * + * 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.blobstore.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.blobstore.KeyNotFoundException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ReturnNullOnKeyNotFoundTest { + ReturnNullOnKeyNotFound fn = new ReturnNullOnKeyNotFound(); + + @Test + public void testFoundIsNull() throws SecurityException, NoSuchMethodException { + assertEquals(fn.apply(new KeyNotFoundException()), null); + } + + @Test(expectedExceptions = { RuntimeException.class }) + public void testNotFoundPropagates() throws SecurityException, NoSuchMethodException { + fn.apply(new RuntimeException()); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404Test.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404Test.java new file mode 100644 index 0000000000..43872b025c --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowContainerNotFoundOn404Test.java @@ -0,0 +1,58 @@ +/** + * + * 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.blobstore.functions; + +import org.jclouds.blobstore.ContainerNotFoundException; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ThrowContainerNotFoundOn404Test { + ThrowContainerNotFoundOn404 fn = new ThrowContainerNotFoundOn404(); + + @Test(expectedExceptions = { ContainerNotFoundException.class }) + public void testFound404ThrowsContainerNotFound() throws SecurityException, NoSuchMethodException { + HttpResponse response = new HttpResponse(404, null, null); + HttpResponseException exception = new HttpResponseException(null, null, response); + fn.apply(exception); + } + + @Test(expectedExceptions = { HttpResponseException.class }) + public void testNotFound404PropagatesHttpResponseException() throws SecurityException, NoSuchMethodException { + HttpResponse response = new HttpResponse(409, null, null); + HttpResponseException exception = new HttpResponseException(null, null, response); + fn.apply(exception); + } + + @Test(expectedExceptions = { RuntimeException.class }) + public void testNotFoundPropagates() throws SecurityException, NoSuchMethodException { + fn.apply(new RuntimeException()); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404Test.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404Test.java new file mode 100644 index 0000000000..40bcad725c --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ThrowKeyNotFoundOn404Test.java @@ -0,0 +1,58 @@ +/** + * + * 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.blobstore.functions; + +import org.jclouds.blobstore.KeyNotFoundException; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ThrowKeyNotFoundOn404Test { + ThrowKeyNotFoundOn404 fn = new ThrowKeyNotFoundOn404(); + + @Test(expectedExceptions = { KeyNotFoundException.class }) + public void testFound404ThrowsKeyNotFound() throws SecurityException, NoSuchMethodException { + HttpResponse response = new HttpResponse(404, null, null); + HttpResponseException exception = new HttpResponseException(null, null, response); + fn.apply(exception); + } + + @Test(expectedExceptions = { HttpResponseException.class }) + public void testNotFound404PropagatesHttpResponseException() throws SecurityException, NoSuchMethodException { + HttpResponse response = new HttpResponse(409, null, null); + HttpResponseException exception = new HttpResponseException(null, null, response); + fn.apply(exception); + } + + @Test(expectedExceptions = { RuntimeException.class }) + public void testNotFoundPropagates() throws SecurityException, NoSuchMethodException { + fn.apply(new RuntimeException()); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + fn.apply(null); + } +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobIntegrationTest.java index aaab318db6..233cfce361 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobIntegrationTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "integration" }, testName = "blobstore.TransientBlobIntegrationTest") +@Test(groups = { "integration" }) public class TransientBlobIntegrationTest extends BaseBlobIntegrationTest { } \ No newline at end of file diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobMapIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobMapIntegrationTest.java index 2b8a8e8dcf..fdcb4771cd 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobMapIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobMapIntegrationTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "blobstore.TransientBlobMapIntegrationTest") +@Test(groups = { "integration", "live" }) public class TransientBlobMapIntegrationTest extends BaseBlobMapIntegrationTest { } \ No newline at end of file diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientContainerIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientContainerIntegrationTest.java index 203e148c6a..a3c6f9f4e6 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientContainerIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientContainerIntegrationTest.java @@ -37,7 +37,7 @@ import com.google.common.collect.Iterables; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "blobstore.TransientContainerIntegrationTest") +@Test(groups = { "integration", "live" }) public class TransientContainerIntegrationTest extends BaseContainerIntegrationTest { @Test(groups = { "integration", "live" }) diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientInputStreamMapIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientInputStreamMapIntegrationTest.java index fea903a8ec..2061818da2 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientInputStreamMapIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientInputStreamMapIntegrationTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "blobstore.TransientInputStreamMapIntegrationTest") +@Test(groups = { "integration", "live" }) public class TransientInputStreamMapIntegrationTest extends BaseInputStreamMapIntegrationTest { } \ No newline at end of file diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientServiceIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientServiceIntegrationTest.java index 36d44edf93..027494e460 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientServiceIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/TransientServiceIntegrationTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "blobstore.TransientServiceIntegrationTest") +@Test(groups = { "integration", "live" }) public class TransientServiceIntegrationTest extends BaseServiceIntegrationTest { } \ No newline at end of file diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java index 31aeb4628f..c0166ad187 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java @@ -64,7 +64,7 @@ import org.jclouds.io.Payloads; import org.jclouds.io.WriteTo; import org.jclouds.io.payloads.StreamingPayload; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -411,7 +411,7 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { @DataProvider(name = "putTests") public Object[][] createData1() throws IOException { - String realObject = Utils.toStringAndClose(new FileInputStream("pom.xml")); + String realObject = Strings2.toStringAndClose(new FileInputStream("pom.xml")); return new Object[][] { { "file", "text/xml", new File("pom.xml"), realObject }, { "string", "text/xml", realObject, realObject }, diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobLiveTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobLiveTest.java index 108d5fbfd8..140a838d46 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobLiveTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobLiveTest.java @@ -39,7 +39,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "blobstore.BlobLiveTest") +@Test(groups = { "live" }) public class BaseBlobLiveTest extends BaseBlobStoreIntegrationTest { private static final String sysHttpStreamUrl = System.getProperty("jclouds.blobstore.httpstream.url"); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobMapIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobMapIntegrationTest.java index 1750074d06..980f7bda4f 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobMapIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobMapIntegrationTest.java @@ -38,7 +38,7 @@ import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.io.Payloads; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Throwables; @@ -175,11 +175,11 @@ public abstract class BaseBlobMapIntegrationTest extends BaseMapIntegrationTest< try { Map map = createMap(context, bucketName); Blob blob = context.getBlobStore().newBlob("one"); - blob.setPayload(Utils.toInputStream("apple")); + blob.setPayload(Strings2.toInputStream("apple")); Payloads.calculateMD5(blob); Blob old = map.put(blob.getMetadata().getName(), blob); getOneReturnsAppleAndOldValueIsNull(map, old); - blob.setPayload(Utils.toInputStream("bear")); + blob.setPayload(Strings2.toInputStream("bear")); Payloads.calculateMD5(blob); Blob apple = map.put(blob.getMetadata().getName(), blob); getOneReturnsBearAndOldValueIsApple(map, apple); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java index c2c01556ce..20550732ce 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java @@ -23,7 +23,7 @@ import static org.testng.Assert.assertEquals; import org.jclouds.blobstore.domain.Blob; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; /** @@ -33,7 +33,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "blobstore.BlobLiveTest") +@Test(groups = { "live" }) public class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest { @Test @@ -69,7 +69,7 @@ public class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest { context.getBlobStore().putBlob(container, blob); HttpRequest request = context.getSigner().signGetBlob(container, name); assertEquals(request.getFilters().size(), 0); - assertEquals(Utils.toStringAndClose(context.utils().http().invoke(request)), text); + assertEquals(Strings2.toStringAndClose(context.utils().http().invoke(request).getPayload().getInput()), text); } finally { returnContainer(container); } @@ -87,7 +87,7 @@ public class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest { try { HttpRequest request = context.getSigner().signPutBlob(container, blob); assertEquals(request.getFilters().size(), 0); - Utils.toStringAndClose(context.utils().http().invoke(request)); + Strings2.toStringAndClose(context.utils().http().invoke(request).getPayload().getInput()); assert context.getBlobStore().blobExists(container, name); } finally { returnContainer(container); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseInputStreamMapIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseInputStreamMapIntegrationTest.java index 5b1ffa26e0..fd0f7bd15f 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseInputStreamMapIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseInputStreamMapIntegrationTest.java @@ -37,7 +37,7 @@ import java.util.concurrent.TimeoutException; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.InputStreamMap; import org.jclouds.blobstore.options.ListContainerOptions; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.Sets; @@ -62,7 +62,7 @@ public abstract class BaseInputStreamMapIntegrationTest extends BaseMapIntegrati assertEquals(values.size(), 5); Set valuesAsString = new HashSet(); for (InputStream stream : values) { - valuesAsString.add(Utils.toStringAndClose(stream)); + valuesAsString.add(Strings2.toStringAndClose(stream)); } valuesAsString.removeAll(fiveStrings.values()); assert valuesAsString.size() == 0 : valuesAsString.size() + ": " + values + ": " @@ -106,7 +106,7 @@ public abstract class BaseInputStreamMapIntegrationTest extends BaseMapIntegrati Map map = createMap(context, containerName); putStringWithMD5(map, "one", "two"); InputStream old = map.remove("one"); - assertEquals(Utils.toStringAndClose(old), "two"); + assertEquals(Strings2.toStringAndClose(old), "two"); assertConsistencyAwareKeySize(map, 0); old = map.remove("one"); assert old == null; @@ -130,12 +130,12 @@ public abstract class BaseInputStreamMapIntegrationTest extends BaseMapIntegrati Set> entries = map.entrySet(); assertEquals(entries.size(), 5); for (Entry entry : entries) { - assertEquals(fiveStrings.get(entry.getKey()), Utils.toStringAndClose(entry.getValue())); - entry.setValue(Utils.toInputStream("")); + assertEquals(fiveStrings.get(entry.getKey()), Strings2.toStringAndClose(entry.getValue())); + entry.setValue(Strings2.toInputStream("")); } assertConsistencyAwareMapSize(map, 5); for (InputStream value : map.values()) { - assertEquals(Utils.toStringAndClose(value), ""); + assertEquals(Strings2.toStringAndClose(value), ""); } } finally { returnContainer(containerName); @@ -272,15 +272,15 @@ public abstract class BaseInputStreamMapIntegrationTest extends BaseMapIntegrati void getOneReturnsAppleAndOldValueIsNull(Map map, InputStream old) throws IOException, InterruptedException { assert old == null; - assertEquals(Utils.toStringAndClose(map.get("one")), String + assertEquals(Strings2.toStringAndClose(map.get("one")), String .format(XML_STRING_FORMAT, "apple")); assertConsistencyAwareMapSize(map, 1); } void getOneReturnsBearAndOldValueIsApple(Map map, InputStream oldValue) throws IOException, InterruptedException { - assertEquals(Utils.toStringAndClose(map.get("one")), String.format(XML_STRING_FORMAT, "bear")); - assertEquals(Utils.toStringAndClose(oldValue), String.format(XML_STRING_FORMAT, "apple")); + assertEquals(Strings2.toStringAndClose(map.get("one")), String.format(XML_STRING_FORMAT, "bear")); + assertEquals(Strings2.toStringAndClose(oldValue), String.format(XML_STRING_FORMAT, "apple")); assertConsistencyAwareMapSize(map, 1); } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java index dc635aa3f7..c0cbf9b6b2 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java @@ -40,7 +40,7 @@ import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.ListableMap; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.options.ListContainerOptions; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Optional; @@ -76,7 +76,7 @@ public abstract class BaseMapIntegrationTest extends BaseBlobStoreIntegration protected void setUpInputStreams() { fiveInputs = Maps.transformValues(fiveStrings, new Function() { public InputStream apply(String from) { - return Utils.toInputStream(from); + return Strings2.toInputStream(from); } }); } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobMapTest.java b/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobMapTest.java index cbb11cdfbc..27d0c4a9b0 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobMapTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobMapTest.java @@ -38,7 +38,7 @@ import com.google.inject.util.Types; * * @author Adrian Cole */ -@Test(groups = { "unit" }, testName = "blobstore.BaseBlobMapTest") +@Test(groups = { "unit" }) public class BaseBlobMapTest { BlobStoreContext context; @@ -51,12 +51,12 @@ public class BaseBlobMapTest { map = (InputStreamMapImpl) context.createInputStreamMap("test"); } - @SuppressWarnings("unchecked") public void testTypes() { - TypeLiteral type0 = new TypeLiteral>>() { + TypeLiteral>> type0 = new TypeLiteral>>() { }; - TypeLiteral type1 = TypeLiteral.get(Types.newParameterizedType(Map.class, String.class, Types - .newParameterizedType(Map.class, String.class, Blob.class))); + @SuppressWarnings("rawtypes") + TypeLiteral type1 = TypeLiteral.get(Types.newParameterizedType(Map.class, String.class, + Types.newParameterizedType(Map.class, String.class, Blob.class))); assertEquals(type0, type1); } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java b/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java index 787f4fd536..91c5b80798 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java @@ -40,7 +40,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "blobstore.GetOptionsTest") +@Test(groups = "unit") public class GetOptionsTest { private String etag; diff --git a/blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/BiggerThanPageSizeTest.java b/blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/BiggerThanPageSizeTest.java new file mode 100644 index 0000000000..5f91aae19d --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/BiggerThanPageSizeTest.java @@ -0,0 +1,75 @@ +/** + * + * 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.blobstore.strategy.internal; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; + +import org.jclouds.blobstore.BlobStore; +import org.jclouds.blobstore.BlobStoreContextFactory; +import org.jclouds.blobstore.domain.Blob; +import org.jclouds.blobstore.options.ListContainerOptions; +import org.jclouds.blobstore.strategy.internal.ConcatenateContainerLists; +import org.jclouds.blobstore.strategy.internal.ListContainerAndRecurseThroughFolders; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test +public class BiggerThanPageSizeTest { + private BlobStore blobstore; + + @BeforeTest + void setupBlobStore() { + blobstore = new BlobStoreContextFactory().createContext("transient", "foo", "bar").getBlobStore(); + } + + public void test() throws IOException { + blobstore.createContainerInLocation(null, "goodies"); + for (int i = 0; i < 1001; i++) { + Blob blob = blobstore.newBlob(i + ""); + blob.setPayload(i + ""); + blobstore.putBlob("goodies", blob); + } + assertEquals(blobstore.countBlobs("goodies"), 1001); + blobstore.clearContainer("goodies"); + assertEquals(blobstore.countBlobs("goodies"), 0); + } + + public void testStrategies() throws IOException { + blobstore.createContainerInLocation(null, "poo"); + for (int i = 0; i < 1001; i++) { + Blob blob = blobstore.newBlob(i + ""); + blob.setPayload(i + ""); + blobstore.putBlob("poo", blob); + } + + ListContainerAndRecurseThroughFolders lister = new ListContainerAndRecurseThroughFolders( + new ConcatenateContainerLists(blobstore)); + assertEquals(lister.execute("poo", ListContainerOptions.NONE).size(), 1001); + blobstore.clearContainer("poo"); + assertEquals(lister.execute("poo", ListContainerOptions.NONE).size(), 0); + } + +} diff --git a/blobstore/src/test/java/org/jclouds/blobstore/util/BlobStoreUtilsTest.java b/blobstore/src/test/java/org/jclouds/blobstore/util/BlobStoreUtilsTest.java index 173fd81bed..3a990fa60e 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/util/BlobStoreUtilsTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/util/BlobStoreUtilsTest.java @@ -24,7 +24,7 @@ import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; import static org.jclouds.blobstore.util.BlobStoreUtils.createParentIfNeededAsync; -import static org.jclouds.blobstore.util.BlobStoreUtils.getKeyFor; +import static org.jclouds.blobstore.util.BlobStoreUtils.getNameFor; import static org.jclouds.blobstore.util.BlobStoreUtils.parseContainerFromPath; import static org.jclouds.blobstore.util.BlobStoreUtils.parsePrefixFromPath; import static org.testng.Assert.assertEquals; @@ -34,11 +34,11 @@ import java.net.URI; import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.MutableBlobMetadata; -import org.jclouds.http.HttpResponse; +import org.jclouds.rest.Providers; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; /** @@ -46,7 +46,7 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "blobstore.BlobStoreUtilsTest") +@Test(groups = "unit") public class BlobStoreUtilsTest { @Test @@ -54,10 +54,10 @@ public class BlobStoreUtilsTest { Iterable providers = BlobStoreUtils.getSupportedProviders(); assert Iterables.contains(providers, "transient") : providers; } - + @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "transient") : providers; } @@ -127,34 +127,27 @@ public class BlobStoreUtilsTest { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - HttpResponse from = createMock(HttpResponse.class); expect(request.getEndpoint()).andReturn( - URI.create("https://jclouds.blob.core.windows.net/adriancole-blobstore0/five")); - expect(request.getArgs()).andReturn(new Object[] { "adriancole-blobstore0", "five" }) - .atLeastOnce(); + URI.create("https://jclouds.blob.core.windows.net/adriancole-blobstore0/five")); + expect(request.getArgs()).andReturn(ImmutableList. of("adriancole-blobstore0", "five")).atLeastOnce(); replay(request); - replay(from); - assertEquals(getKeyFor(request, from), "five"); + assertEquals(getNameFor(request), "five"); } public void testGetKeyForAtmos() { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - HttpResponse from = createMock(HttpResponse.class); expect(request.getEndpoint()) - .andReturn( - URI - .create("https://storage4.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22/adriancole-blobstore0/four")); - expect(request.getArgs()).andReturn(new Object[] { "adriancole-blobstore0/four" }) - .atLeastOnce(); + .andReturn( + URI.create("https://storage4.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22/adriancole-blobstore0/four")); + expect(request.getArgs()).andReturn(ImmutableList. of("adriancole-blobstore0/four")).atLeastOnce(); replay(request); - replay(from); - assertEquals(getKeyFor(request, from), "four"); + assertEquals(getNameFor(request), "four"); } public void testGetContainer() { diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextString.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextString.java index c0e26d0a88..bbd81f50d1 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextString.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextString.java @@ -54,7 +54,7 @@ public class BindCloneDriveOptionsToPlainTextString implements MapBinder { } @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, "this binder is only valid for GeneratedHttpRequests!"); @SuppressWarnings("unchecked") @@ -68,7 +68,7 @@ public class BindCloneDriveOptionsToPlainTextString implements MapBinder { request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(postParams))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - + return request; } static CloneDriveOptions findOptionsInArgsOrNull(GeneratedHttpRequest gRequest) { @@ -84,7 +84,7 @@ public class BindCloneDriveOptionsToPlainTextString implements MapBinder { } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { throw new UnsupportedOperationException(); } diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextString.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextString.java index 9f86bfcceb..c66289be6a 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextString.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextString.java @@ -50,12 +50,13 @@ public class BindDriveDataToPlainTextString implements Binder { this.createDriveRequestToMap = createDriveRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(payload instanceof DriveData, "this binder is only valid for DriveData!"); DriveData create = DriveData.class.cast(payload); Map map = createDriveRequestToMap.apply(create); request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + return request; } } diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextString.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextString.java index 71d5627b1a..a7ece69a03 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextString.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextString.java @@ -50,12 +50,13 @@ public class BindDriveToPlainTextString implements Binder { this.createDriveRequestToMap = createDriveRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(payload instanceof Drive, "this binder is only valid for Drive!"); Drive create = Drive.class.cast(payload); Map map = createDriveRequestToMap.apply(create); request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + return request; } } diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextString.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextString.java index 371b1858db..2fc87e409b 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextString.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextString.java @@ -50,12 +50,13 @@ public class BindServerToPlainTextString implements Binder { this.createServerRequestToMap = createServerRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(payload instanceof Server, "this binder is only valid for Server!"); Server create = Server.class.cast(payload); Map map = createServerRequestToMap.apply(create); request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + return request; } } diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/config/CloudSigmaComputeServiceContextModule.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/config/CloudSigmaComputeServiceContextModule.java index 055c85fa6b..d0daf5e0e9 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/config/CloudSigmaComputeServiceContextModule.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/config/CloudSigmaComputeServiceContextModule.java @@ -43,7 +43,6 @@ import org.jclouds.cloudsigma.domain.ServerInfo; import org.jclouds.cloudsigma.predicates.DriveClaimed; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.config.ComputeServiceAdapterContextModule; -import org.jclouds.compute.config.JCloudsNativeComputeServiceAdapterContextModule.IdentityFunction; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; @@ -53,6 +52,7 @@ import org.jclouds.compute.domain.os.OsFamilyVersion64Bit; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.suppliers.DefaultLocationSupplier; import org.jclouds.domain.Location; +import org.jclouds.functions.IdentityFunction; import org.jclouds.predicates.RetryablePredicate; import com.google.common.base.Function; diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java index f3ae1ae6c5..8f2762ac49 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java @@ -19,7 +19,7 @@ package org.jclouds.cloudsigma.functions; -import static org.jclouds.util.Utils.renameKey; +import static org.jclouds.util.Maps2.renameKey; import java.util.Map; diff --git a/cloudsigma/src/main/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandler.java b/cloudsigma/src/main/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandler.java index 7c4f3dfc83..99c499a204 100644 --- a/cloudsigma/src/main/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandler.java +++ b/cloudsigma/src/main/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandler.java @@ -31,7 +31,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Throwables; import com.google.common.io.Closeables; @@ -57,11 +57,11 @@ public class CloudSigmaErrorHandler implements HttpErrorHandler { Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try { - message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(), + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: - if ((command.getRequest().getEndpoint().getPath().endsWith("/info")) + if ((command.getCurrentRequest().getEndpoint().getPath().endsWith("/info")) || (message != null && message.indexOf("could not be found") != -1)) exception = new ResourceNotFoundException(message, exception); else @@ -71,7 +71,7 @@ public class CloudSigmaErrorHandler implements HttpErrorHandler { exception = new AuthorizationException(message, exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; @@ -93,7 +93,7 @@ public class CloudSigmaErrorHandler implements HttpErrorHandler { if (response.getPayload() == null) return null; try { - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } catch (IOException e) { throw new RuntimeException(e); } finally { diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java index d4c89f84f5..4dd7a32bb8 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java @@ -45,7 +45,6 @@ import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -54,16 +53,17 @@ import com.google.common.collect.Iterables; import com.google.inject.TypeLiteral; /** - * Tests annotation parsing of {@code CloudSigmaAsyncClient} + * Tests behavior of {@code CloudSigmaAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudsigma.CloudSigmaAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CloudSigmaAsyncClientTest") public class CloudSigmaAsyncClientTest extends RestClientTest { public void testListStandardDrives() throws SecurityException, NoSuchMethodException, IOException { Method method = CloudSigmaAsyncClient.class.getMethod("listStandardDrives"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/standard/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -78,7 +78,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/standard/cd/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -93,7 +93,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/standard/img/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -108,7 +108,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -123,7 +123,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/uuid/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -139,7 +139,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, new CreateDriveRequest.Builder().name("foo").use(ImmutableList.of("production", "candy")).size(10000l) .build()); @@ -158,7 +158,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "sourceid", "newname"); + HttpRequest httpRequest = processor.createRequest(method, "sourceid", "newname"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/drives/sourceid/clone HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -175,7 +175,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "sourceid", "newname", + HttpRequest httpRequest = processor.createRequest(method, "sourceid", "newname", new CloneDriveOptions().size(1024l)); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/drives/sourceid/clone HTTP/1.1"); @@ -192,7 +192,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + HttpRequest httpRequest = processor.createRequest(method, "100", new DriveData.Builder().name("foo").size(10000l).use(ImmutableList.of("production", "candy")).build()); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/drives/100/set HTTP/1.1"); @@ -209,15 +209,15 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/servers/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/servers/list HTTP/1.1"); // for example, using basic authentication, we should get "only one" @@ -236,7 +236,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/servers/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -251,7 +251,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/servers/uuid/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -267,7 +267,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, BindServerToPlainTextStringTest.SERVER); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/create HTTP/1.1"); @@ -284,7 +284,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + HttpRequest httpRequest = processor.createRequest(method, "100", BindServerToPlainTextStringTest.SERVER); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/100/set HTTP/1.1"); @@ -301,7 +301,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/uuid/destroy HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -317,7 +317,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/uuid/start HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -333,7 +333,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/uuid/stop HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -349,7 +349,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/uuid/shutdown HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -365,7 +365,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/servers/uuid/reset HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -381,15 +381,15 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/list HTTP/1.1"); // for example, using basic authentication, we should get "only one" @@ -408,7 +408,7 @@ public class CloudSigmaAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/drives/uuid/destroy HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java index 997fce89e8..ae43c864bc 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java @@ -71,7 +71,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudsigma.CloudSigmaClientLiveTest") +@Test(groups = "live") public class CloudSigmaClientLiveTest { protected long driveSize = 8 * 1024 * 1024 * 1024l; protected int maxDriveImageTime = 300; diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java index 6e9d0a1af3..f082ee7690 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java @@ -19,7 +19,7 @@ package org.jclouds.cloudsigma; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -34,7 +34,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "cloudsigma") : providers; } // diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextStringTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextStringTest.java index 8f9d0a5769..1d4a88c0dc 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextStringTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindCloneDriveOptionsToPlainTextStringTest.java @@ -25,6 +25,7 @@ import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; import java.io.IOException; +import java.util.List; import org.jclouds.cloudsigma.options.CloneDriveOptions; import org.jclouds.io.MutableContentMetadata; @@ -32,6 +33,7 @@ import org.jclouds.io.Payload; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.inject.Guice; @@ -46,15 +48,17 @@ public class BindCloneDriveOptionsToPlainTextStringTest { BindCloneDriveOptionsToPlainTextString.class); public void testDefault() throws IOException { - assertInputAndArgsCreatesPayload(ImmutableMap.of("name", "newdrive"), new Object[] {}, "name newdrive"); + assertInputAndArgsCreatesPayload(ImmutableMap.of("name", "newdrive"), ImmutableList. of(), + "name newdrive"); } public void testWithSize() throws IOException { assertInputAndArgsCreatesPayload(ImmutableMap.of("name", "newdrive"), - new Object[] { new CloneDriveOptions().size(1024) }, "name newdrive\nsize 1024"); + ImmutableList. of(new CloneDriveOptions().size(1024)), "name newdrive\nsize 1024"); } - protected void assertInputAndArgsCreatesPayload(ImmutableMap inputMap, Object[] args, String expected) { + protected void assertInputAndArgsCreatesPayload(ImmutableMap inputMap, List args, + String expected) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getArgs()).andReturn(args).atLeastOnce(); request.setPayload(expected); diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextStringTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextStringTest.java index fbd187970a..2f89f160d2 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextStringTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveDataToPlainTextStringTest.java @@ -33,7 +33,7 @@ import org.jclouds.cloudsigma.domain.DriveData; import org.jclouds.cloudsigma.functions.BaseDriveToMap; import org.jclouds.cloudsigma.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -81,7 +81,7 @@ public class BindDriveDataToPlainTextStringTest { FN.bindToRequest(request, input); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); assertEquals(request.getPayload().getRawContent(), - Utils.toStringAndClose(BindDriveDataToPlainTextStringTest.class.getResourceAsStream("/drive_data.txt"))); + Strings2.toStringAndClose(BindDriveDataToPlainTextStringTest.class.getResourceAsStream("/drive_data.txt"))); } } \ No newline at end of file diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextStringTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextStringTest.java index ce81c41a37..5d534f5b50 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextStringTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindDriveToPlainTextStringTest.java @@ -34,7 +34,7 @@ import org.jclouds.cloudsigma.domain.DriveData; import org.jclouds.cloudsigma.functions.BaseDriveToMap; import org.jclouds.cloudsigma.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -83,7 +83,7 @@ public class BindDriveToPlainTextStringTest { FN.bindToRequest(request, input); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); assertEquals(request.getPayload().getRawContent(), - Utils.toStringAndClose(BindDriveToPlainTextStringTest.class + Strings2.toStringAndClose(BindDriveToPlainTextStringTest.class .getResourceAsStream("/create_drive.txt"))); } diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextStringTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextStringTest.java index 548c7a251f..640cbb0432 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextStringTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/binders/BindServerToPlainTextStringTest.java @@ -34,7 +34,7 @@ import org.jclouds.cloudsigma.domain.Server; import org.jclouds.cloudsigma.domain.VNC; import org.jclouds.cloudsigma.functions.ServerToMap; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -54,7 +54,7 @@ public class BindServerToPlainTextStringTest { public static String CREATED_SERVER; static { try { - CREATED_SERVER = Utils.toStringAndClose(BindServerToPlainTextStringTest.class + CREATED_SERVER = Strings2.toStringAndClose(BindServerToPlainTextStringTest.class .getResourceAsStream("/create_server.txt")); } catch (IOException e) { CREATED_SERVER = null; diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java index f3ca0396d6..d5f4af5bc7 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java @@ -30,7 +30,7 @@ import org.jclouds.cloudsigma.domain.DriveInfo; import org.jclouds.cloudsigma.domain.DriveMetrics; import org.jclouds.cloudsigma.domain.DriveStatus; import org.jclouds.cloudsigma.domain.DriveType; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; @@ -88,7 +88,7 @@ public class MapToDriveInfoTest { public void testComplete() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/drive.txt"))).get(0); + Strings2.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/drive.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), ONE); diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToServerInfoTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToServerInfoTest.java index d7fe5a6ae8..9516bc183f 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToServerInfoTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToServerInfoTest.java @@ -35,7 +35,7 @@ import org.jclouds.cloudsigma.domain.ServerMetrics; import org.jclouds.cloudsigma.domain.ServerStatus; import org.jclouds.cloudsigma.domain.VNC; import org.jclouds.cloudsigma.functions.MapToDevices.DeviceToId; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; @@ -119,7 +119,7 @@ public class MapToServerInfoTest { public void testComplete() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/servers.txt"))).get(0); + Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/servers.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), ONE); @@ -154,7 +154,7 @@ public class MapToServerInfoTest { public void testNew() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/new_server.txt"))).get(0); + Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/new_server.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), NEW); diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ParseOsFamilyVersion64BitFromImageNameTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ParseOsFamilyVersion64BitFromImageNameTest.java index d31e5129df..ee320568db 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ParseOsFamilyVersion64BitFromImageNameTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ParseOsFamilyVersion64BitFromImageNameTest.java @@ -32,7 +32,7 @@ import org.jclouds.cloudsigma.compute.functions.ParseOsFamilyVersion64BitFromIma import org.jclouds.compute.domain.os.OsFamilyVersion64Bit; import org.jclouds.json.Json; import org.jclouds.json.internal.GsonWrapper; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -51,7 +51,7 @@ public class ParseOsFamilyVersion64BitFromImageNameTest { @DataProvider(name = "data") public Object[][] createData() throws IOException { InputStream is = ParseOsFamilyVersion64BitFromImageNameTest.class.getResourceAsStream("/osmatches.json"); - Map values = json.fromJson(Utils.toStringAndClose(is), + Map values = json.fromJson(Strings2.toStringAndClose(is), new TypeLiteral>() { }.getType()); diff --git a/cloudsigma/src/test/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandlerTest.java b/cloudsigma/src/test/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandlerTest.java index d613f4532f..f67099296f 100644 --- a/cloudsigma/src/test/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandlerTest.java +++ b/cloudsigma/src/test/java/org/jclouds/cloudsigma/handlers/CloudSigmaErrorHandlerTest.java @@ -34,7 +34,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.inject.Guice; @@ -105,11 +105,11 @@ public class CloudSigmaErrorHandlerTest { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); - HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils + HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Strings2 .toInputStream(content))); response.getPayload().getContentMetadata().setContentType(contentType); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); diff --git a/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java b/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java index 61280f4d14..c5ca88dbee 100644 --- a/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java +++ b/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java @@ -20,7 +20,7 @@ package org.jclouds.compute; import static org.jclouds.rest.RestContextFactory.createContextBuilder; -import static org.jclouds.util.Utils.propagateAuthorizationOrOriginalException; +import static org.jclouds.util.Throwables2.propagateAuthorizationOrOriginalException; import java.util.Properties; diff --git a/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeComputeServiceAdapterContextModule.java b/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeComputeServiceAdapterContextModule.java index 507f03c248..45e9f6cf67 100644 --- a/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeComputeServiceAdapterContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeComputeServiceAdapterContextModule.java @@ -19,11 +19,13 @@ package org.jclouds.compute.config; + import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.domain.Location; +import org.jclouds.functions.IdentityFunction; import com.google.common.base.Function; import com.google.inject.TypeLiteral; @@ -63,18 +65,4 @@ public class JCloudsNativeComputeServiceAdapterContextModule extends super.configure(); } - // enum singleton pattern - public static enum IdentityFunction implements Function { - INSTANCE; - - public Object apply(Object o) { - return o; - } - - @Override - public String toString() { - return "identity"; - } - } - } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java index 41e8a56da7..f51537a688 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java @@ -26,7 +26,6 @@ import static com.google.common.collect.Lists.newArrayList; import static org.jclouds.compute.util.ComputeServiceUtils.getCores; import static org.jclouds.compute.util.ComputeServiceUtils.getCoresAndSpeed; import static org.jclouds.compute.util.ComputeServiceUtils.getSpace; -import static org.jclouds.util.Utils.multiMax; import java.util.Arrays; import java.util.List; @@ -50,6 +49,7 @@ 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.Lists2; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; @@ -617,7 +617,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { Iterable matchingImages = filter(supportedImages, imagePredicate); if (logger.isTraceEnabled()) logger.trace("<< matched images(%s)", matchingImages); - List maxImages = multiMax(DEFAULT_IMAGE_ORDERING, matchingImages); + List maxImages = Lists2.multiMax(DEFAULT_IMAGE_ORDERING, matchingImages); if (logger.isTraceEnabled()) logger.trace("<< best images(%s)", maxImages); return maxImages.get(maxImages.size() - 1); diff --git a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java index c36e6c97af..eea930bddd 100755 --- a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java +++ b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java @@ -85,7 +85,7 @@ import org.jclouds.logging.Logger; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.ssh.ExecResponse; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; import com.google.common.base.Predicate; @@ -458,7 +458,7 @@ public class BaseComputeService implements ComputeService { @Override public Void call() throws Exception { try { - ExecResponse response = utils.runScriptOnNode(node, Statements.exec(Utils.toStringAndClose(runScript + ExecResponse response = utils.runScriptOnNode(node, Statements.exec(Strings2.toStringAndClose(runScript .getInput())), options); if (response != null) execs.put(node, response); diff --git a/compute/src/main/java/org/jclouds/compute/internal/BaseLoadBalancerService.java b/compute/src/main/java/org/jclouds/compute/internal/BaseLoadBalancerService.java index 33e300ed4d..b0db166241 100644 --- a/compute/src/main/java/org/jclouds/compute/internal/BaseLoadBalancerService.java +++ b/compute/src/main/java/org/jclouds/compute/internal/BaseLoadBalancerService.java @@ -22,7 +22,6 @@ package org.jclouds.compute.internal; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Map; import java.util.Set; import javax.annotation.Resource; @@ -42,10 +41,8 @@ import org.jclouds.logging.Logger; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; -import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; diff --git a/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java b/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java index aa53efc78f..27bc6ca8f1 100644 --- a/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java +++ b/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java @@ -48,7 +48,8 @@ public class ComputeServiceContextImpl implements ComputeServiceContext { @SuppressWarnings({ "unchecked" }) @Inject public ComputeServiceContextImpl(ComputeService computeService, Map credentialStore, - Utils utils, @Nullable LoadBalancerService loadBalancerService, RestContext providerSpecificContext) { + Utils utils, @Nullable LoadBalancerService loadBalancerService, + @SuppressWarnings("rawtypes") RestContext providerSpecificContext) { this.credentialStore = credentialStore; this.utils = utils; this.providerSpecificContext = providerSpecificContext; diff --git a/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java b/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java index 78d02af5d5..5f0d4c7d49 100644 --- a/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java +++ b/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java @@ -29,7 +29,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.io.Payload; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statements; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Throwables; @@ -193,7 +193,7 @@ public class TemplateOptions extends RunScriptOptions { */ public TemplateOptions runScript(Payload script) { try { - return runScript(Statements.exec(Utils.toStringAndClose(checkNotNull(script, "script").getInput()))); + return runScript(Statements.exec(Strings2.toStringAndClose(checkNotNull(script, "script").getInput()))); } catch (IOException e) { Throwables.propagate(e); return this; @@ -225,7 +225,7 @@ public class TemplateOptions extends RunScriptOptions { @Deprecated public TemplateOptions installPrivateKey(Payload privateKey) { try { - return installPrivateKey(Utils.toStringAndClose(checkNotNull(privateKey, "privateKey").getInput())); + return installPrivateKey(Strings2.toStringAndClose(checkNotNull(privateKey, "privateKey").getInput())); } catch (IOException e) { Throwables.propagate(e); return this; @@ -256,7 +256,7 @@ public class TemplateOptions extends RunScriptOptions { @Deprecated public TemplateOptions authorizePublicKey(Payload publicKey) { try { - return authorizePublicKey(Utils.toStringAndClose(checkNotNull(publicKey, "publicKey").getInput())); + return authorizePublicKey(Strings2.toStringAndClose(checkNotNull(publicKey, "publicKey").getInput())); } catch (IOException e) { Throwables.propagate(e); return this; diff --git a/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java b/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java index cee5b63dfd..e13fba7fc0 100644 --- a/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java +++ b/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java @@ -20,13 +20,13 @@ package org.jclouds.compute.predicates; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.checkNotEmpty; import java.util.Set; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeState; +import org.jclouds.util.Preconditions2; import com.google.common.base.Predicate; import com.google.common.base.Predicates; @@ -195,7 +195,7 @@ public class NodePredicates { * @return predicate */ public static Predicate withTag(final String tag) { - checkNotEmpty(tag, "Tag must be defined"); + Preconditions2.checkNotEmpty(tag, "Tag must be defined"); return new Predicate() { @Override public boolean apply(NodeMetadata nodeMetadata) { @@ -217,7 +217,7 @@ public class NodePredicates { * @return predicate */ public static Predicate runningWithTag(final String tag) { - checkNotEmpty(tag, "Tag must be defined"); + Preconditions2.checkNotEmpty(tag, "Tag must be defined"); return new Predicate() { @Override public boolean apply(NodeMetadata nodeMetadata) { diff --git a/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java b/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java index 87982f5960..3ddedefe95 100644 --- a/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java +++ b/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java @@ -27,7 +27,6 @@ import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.size; import static com.google.common.collect.Iterables.transform; import static org.jclouds.scriptbuilder.domain.Statements.pipeHttpResponseToBash; -import static org.jclouds.util.Utils.getSupportedProvidersOfType; import java.net.URI; import java.util.Formatter; @@ -49,6 +48,7 @@ import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen; import org.jclouds.http.HttpRequest; import org.jclouds.logging.Logger; import org.jclouds.net.IPSocket; +import org.jclouds.rest.Providers; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.ssh.SshClient; @@ -180,7 +180,7 @@ public class ComputeServiceUtils { } public static Iterable getSupportedProviders() { - return getSupportedProvidersOfType(ComputeServiceContextBuilder.class); + return Providers.getSupportedProvidersOfType(ComputeServiceContextBuilder.class); } public static IPSocket findReachableSocketOnNode(RetryIfSocketNotYetOpen socketTester, final NodeMetadata node, diff --git a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java index 8a84eb71f9..cd274ecf7a 100755 --- a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java @@ -94,7 +94,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, sequential = true, testName = "compute.ComputeServiceLiveTest") +@Test(groups = { "integration", "live" }, sequential = true) public abstract class BaseComputeServiceLiveTest { public void setServiceDefaults() { diff --git a/compute/src/test/java/org/jclouds/compute/BaseLoadBalancerServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseLoadBalancerServiceLiveTest.java index d2c24162b1..ee829f28f2 100644 --- a/compute/src/test/java/org/jclouds/compute/BaseLoadBalancerServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseLoadBalancerServiceLiveTest.java @@ -56,7 +56,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "compute.BaseLoadBalancerServiceTest") +@Test(groups = "live", sequential = true) public abstract class BaseLoadBalancerServiceLiveTest { @BeforeClass abstract public void setServiceDefaults(); diff --git a/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java index a40c075c42..3da0c3d7ed 100644 --- a/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java @@ -57,7 +57,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "integration,live", testName = "compute.BaseTemplateBuilderLiveTest") +@Test(groups = "integration,live") public abstract class BaseTemplateBuilderLiveTest { protected String provider; diff --git a/compute/src/test/java/org/jclouds/compute/ComputeTestUtils.java b/compute/src/test/java/org/jclouds/compute/ComputeTestUtils.java index bb8463df8f..cfd3314c73 100644 --- a/compute/src/test/java/org/jclouds/compute/ComputeTestUtils.java +++ b/compute/src/test/java/org/jclouds/compute/ComputeTestUtils.java @@ -21,7 +21,6 @@ package org.jclouds.compute; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.get; -import static org.jclouds.util.Utils.checkNotEmpty; import static org.testng.Assert.assertEquals; import java.io.File; @@ -36,6 +35,7 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.rest.HttpClient; import org.jclouds.scriptbuilder.domain.Statement; +import org.jclouds.util.Preconditions2; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; @@ -66,7 +66,7 @@ public class ComputeTestUtils { } public static void checkSecretKeyFile(String secretKeyFile) throws FileNotFoundException { - checkNotEmpty(secretKeyFile, "System property: [test.ssh.keyfile] set to an empty string"); + Preconditions2.checkNotEmpty(secretKeyFile, "System property: [test.ssh.keyfile] set to an empty string"); if (!new File(secretKeyFile).exists()) { throw new FileNotFoundException("secretKeyFile not found at: " + secretKeyFile); } diff --git a/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java b/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java index 0c1d8437b3..c52d1d51f2 100644 --- a/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java +++ b/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java @@ -46,7 +46,7 @@ import org.jclouds.rest.RestContext; import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Throwables; @@ -59,7 +59,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", testName = "stub.StubComputeServiceIntegrationTest") +@Test(groups = "live") public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTest { private static final ExecResponse EXEC_GOOD = new ExecResponse("", "", 0); @@ -115,7 +115,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes new SshException("Auth fail")); client2.connect(); try { - runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class + runScript(client2, "runScriptWithCreds", Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class .getResourceAsStream("/runscript.sh")), 2); } catch (IOException e) { Throwables.propagate(e); @@ -168,7 +168,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes client.connect(); try { - runScript(client, "jboss", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class + runScript(client, "jboss", Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class .getResourceAsStream("/initscript_with_jboss.sh")), nodeId); } catch (IOException e) { Throwables.propagate(e); @@ -182,7 +182,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes client.connect(); try { - runScript(client, scriptName, Utils.toStringAndClose(StubComputeServiceIntegrationTest.class + runScript(client, scriptName, Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class .getResourceAsStream("/initscript_with_java.sh")), nodeId); } catch (IOException e) { Throwables.propagate(e); @@ -254,7 +254,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes return actual == null; } try { - String real = Utils.toStringAndClose(((Payload) actual).getInput()); + String real = Strings2.toStringAndClose(((Payload) actual).getInput()); assertEquals(real, expected); return true; } catch (IOException e) { diff --git a/compute/src/test/java/org/jclouds/compute/StubTemplateBuilderIntegrationTest.java b/compute/src/test/java/org/jclouds/compute/StubTemplateBuilderIntegrationTest.java index 1c84ef7259..2ae0e58692 100644 --- a/compute/src/test/java/org/jclouds/compute/StubTemplateBuilderIntegrationTest.java +++ b/compute/src/test/java/org/jclouds/compute/StubTemplateBuilderIntegrationTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "integration", "live" }, testName = "stub.StubTemplateBuilderIntegrationTest") +@Test(groups = { "integration", "live" }) public class StubTemplateBuilderIntegrationTest extends BaseTemplateBuilderLiveTest { public StubTemplateBuilderIntegrationTest() { diff --git a/core/src/main/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplier.java b/core/src/main/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplier.java index 6c6bbed488..9eb68c676a 100644 --- a/core/src/main/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplier.java +++ b/core/src/main/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplier.java @@ -20,10 +20,11 @@ package org.jclouds.concurrent; import static com.google.common.base.Throwables.propagate; -import static org.jclouds.util.Utils.getFirstThrowableOfType; import java.util.concurrent.TimeoutException; +import org.jclouds.util.Throwables2; + import com.google.common.base.Supplier; /** * @@ -44,7 +45,7 @@ public class RetryOnTimeOutExceptionSupplier implements Supplier { ex = null; return delegate.get(); } catch (Exception e) { - if ((ex = getFirstThrowableOfType(e, TimeoutException.class)) != null) + if ((ex = Throwables2.getFirstThrowableOfType(e, TimeoutException.class)) != null) continue; propagate(e); assert false; diff --git a/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java b/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java index 741c4b01be..045fbc45d0 100644 --- a/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java +++ b/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java @@ -37,7 +37,7 @@ import javax.inject.Named; import org.jclouds.concurrent.Timeout; import org.jclouds.internal.ClassMethodArgs; import org.jclouds.rest.annotations.Delegate; -import org.jclouds.util.Utils; +import org.jclouds.util.Throwables2; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; @@ -131,11 +131,11 @@ public class SyncProxy implements InvocationHandler { return ((ListenableFuture) methodMap.get(method).invoke(delegate, args)).get(timeoutMap.get(method), TimeUnit.NANOSECONDS); } catch (ProvisionException e) { - throw Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(method.getExceptionTypes(), e); + throw Throwables2.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(method.getExceptionTypes(), e); } catch (ExecutionException e) { - throw Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(method.getExceptionTypes(), e); + throw Throwables2.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(method.getExceptionTypes(), e); } catch (Exception e) { - throw Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(method.getExceptionTypes(), e); + throw Throwables2.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(method.getExceptionTypes(), e); } } } diff --git a/core/src/main/java/org/jclouds/domain/Credentials.java b/core/src/main/java/org/jclouds/domain/Credentials.java index 23eacb0764..886928ada0 100644 --- a/core/src/main/java/org/jclouds/domain/Credentials.java +++ b/core/src/main/java/org/jclouds/domain/Credentials.java @@ -24,7 +24,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; import java.util.List; -import org.jclouds.http.HttpUtils; +import org.jclouds.util.Strings2; import com.google.common.base.Splitter; import com.google.common.collect.Lists; @@ -47,12 +47,12 @@ public class Credentials { List userInfo = Lists.newArrayList(Splitter.on(':').split( checkNotNull(uri.getUserInfo(), "no userInfo in " + uri))); String identity = checkNotNull(userInfo.get(0), "no username in " + uri.getUserInfo()); - if (HttpUtils.isUrlEncoded(identity)) { - identity = HttpUtils.urlDecode(identity); + if (Strings2.isUrlEncoded(identity)) { + identity = Strings2.urlDecode(identity); } String credential = userInfo.size() > 1 ? userInfo.get(1) : null; - if (credential != null && HttpUtils.isUrlEncoded(credential)) { - credential = HttpUtils.urlDecode(credential); + if (credential != null && Strings2.isUrlEncoded(credential)) { + credential = Strings2.urlDecode(credential); } return new Credentials(identity, credential); } diff --git a/core/src/main/java/org/jclouds/functions/ExceptionToValueOrPropagate.java b/core/src/main/java/org/jclouds/functions/ExceptionToValueOrPropagate.java index 575cb22dc1..3961bb01ca 100644 --- a/core/src/main/java/org/jclouds/functions/ExceptionToValueOrPropagate.java +++ b/core/src/main/java/org/jclouds/functions/ExceptionToValueOrPropagate.java @@ -19,12 +19,14 @@ package org.jclouds.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import javax.annotation.Nullable; +import org.jclouds.util.Throwables2; + import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; @@ -39,18 +41,19 @@ public class ExceptionToValueOrPropagate implements Func private final T value; public ExceptionToValueOrPropagate(Class matchingClass, @Nullable T value) { - this.matchingClass = matchingClass; + this.matchingClass = checkNotNull(matchingClass, "matchingClass"); this.value = value; } @SuppressWarnings("unchecked") @Override public T apply(Exception from) { + checkNotNull(from, "exception"); List throwables = Throwables.getCausalChain(from); Iterable matchingThrowables = Iterables.filter(throwables, matchingClass); if (Iterables.size(matchingThrowables) >= 1) return value; - return (T) propagateOrNull(from); + return (T) Throwables2.propagateOrNull(from); } } diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedHashSet.java b/core/src/main/java/org/jclouds/functions/IdentityFunction.java similarity index 59% rename from atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedHashSet.java rename to core/src/main/java/org/jclouds/functions/IdentityFunction.java index 4261a4a688..63e3fb520c 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/internal/BoundedHashSet.java +++ b/core/src/main/java/org/jclouds/functions/IdentityFunction.java @@ -17,32 +17,27 @@ * ==================================================================== */ -package org.jclouds.atmosonline.saas.domain.internal; +package org.jclouds.functions; -import java.util.HashSet; +import javax.inject.Singleton; -import org.jclouds.atmosonline.saas.domain.BoundedSet; - -import com.google.common.collect.Iterables; +import com.google.common.base.Function; /** * * @author Adrian Cole * */ -public class BoundedHashSet extends HashSet implements BoundedSet { +@Singleton +public enum IdentityFunction implements Function { + INSTANCE; - /** The serialVersionUID */ - private static final long serialVersionUID = -7133632087734650835L; - protected final String token; - - public BoundedHashSet(Iterable contents, String token) { - Iterables.addAll(this, contents); - this.token = token; + public Object apply(Object o) { + return o; } - public String getToken() { - return token; + @Override + public String toString() { + return "identity"; } - } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/http/HttpCommand.java b/core/src/main/java/org/jclouds/http/HttpCommand.java index 0f663395c5..d11eccdfd4 100644 --- a/core/src/main/java/org/jclouds/http/HttpCommand.java +++ b/core/src/main/java/org/jclouds/http/HttpCommand.java @@ -63,7 +63,12 @@ public interface HttpCommand { /** * The request associated with this command. */ - HttpRequest getRequest(); + HttpRequest getCurrentRequest(); + + /** + * The request associated with this command. + */ + void setCurrentRequest(HttpRequest request); /** * Used to prevent a command from being re-executed, or having its response parsed. diff --git a/core/src/main/java/org/jclouds/http/HttpCommandRendezvous.java b/core/src/main/java/org/jclouds/http/HttpCommandRendezvous.java index 764fa665d3..d3f0eee246 100644 --- a/core/src/main/java/org/jclouds/http/HttpCommandRendezvous.java +++ b/core/src/main/java/org/jclouds/http/HttpCommandRendezvous.java @@ -19,25 +19,23 @@ package org.jclouds.http; -import java.util.concurrent.SynchronousQueue; - import java.util.concurrent.Future; +import java.util.concurrent.SynchronousQueue; /** * Used for passing objects for response processing * * @author Adrian Cole */ -public class HttpCommandRendezvous { +public class HttpCommandRendezvous { private final HttpCommand command; - @SuppressWarnings("unchecked") + @SuppressWarnings("rawtypes") private final SynchronousQueue rendezvous; private final Future future; - @SuppressWarnings("unchecked") - public HttpCommandRendezvous(HttpCommand command, SynchronousQueue rendezvous, - Future future) { + public HttpCommandRendezvous(HttpCommand command, @SuppressWarnings("rawtypes") SynchronousQueue rendezvous, + Future future) { this.command = command; this.rendezvous = rendezvous; this.future = future; diff --git a/core/src/main/java/org/jclouds/http/HttpErrorHandler.java b/core/src/main/java/org/jclouds/http/HttpErrorHandler.java index c6bc062d5e..96f7c79638 100644 --- a/core/src/main/java/org/jclouds/http/HttpErrorHandler.java +++ b/core/src/main/java/org/jclouds/http/HttpErrorHandler.java @@ -19,7 +19,6 @@ package org.jclouds.http; - /** * Responsible for setting an exception on the command relevant to the unrecoverable error in the * HttpResponse. @@ -32,6 +31,10 @@ public interface HttpErrorHandler { if (response.getPayload() != null) response.getPayload().release(); } + + public String toString() { + return "NOOP"; + } }; void handleError(HttpCommand command, HttpResponse response); diff --git a/core/src/main/java/org/jclouds/http/HttpMessage.java b/core/src/main/java/org/jclouds/http/HttpMessage.java index 59a7afe9b5..157f2d8bd9 100644 --- a/core/src/main/java/org/jclouds/http/HttpMessage.java +++ b/core/src/main/java/org/jclouds/http/HttpMessage.java @@ -19,6 +19,8 @@ package org.jclouds.http; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Collection; import javax.annotation.Nullable; @@ -26,9 +28,8 @@ import javax.annotation.Nullable; import org.jclouds.http.internal.PayloadEnclosingImpl; import org.jclouds.io.Payload; -import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; /** * Represents a request that can be executed within {@link HttpCommandExecutorService} @@ -36,25 +37,45 @@ import com.google.common.collect.Multimaps; * @author Adrian Cole */ public class HttpMessage extends PayloadEnclosingImpl { + public static Builder builder() { + return new Builder(); + } - /** - * synchronized as there is no concurrent version. Headers may change in flight due to redirects. - */ - protected Multimap headers = Multimaps.synchronizedMultimap(LinkedHashMultimap - . create()); + public static class Builder { + protected Payload payload; + protected Multimap headers = ImmutableMultimap.of(); + + public Builder payload(Payload payload) { + this.payload = payload; + return this; + } + + public Builder headers(Multimap headers) { + this.headers = ImmutableMultimap.copyOf(checkNotNull(headers, "headers")); + return this; + } + + @SuppressWarnings("unchecked") + public T build() { + return (T) new HttpMessage(payload, headers); + } + + public static Builder from(X input) { + return new Builder().payload(input.getPayload()).headers(input.getHeaders()); + } + } + + protected final Multimap headers; + + public HttpMessage(@Nullable Payload payload, Multimap headers) { + super(payload); + this.headers = ImmutableMultimap.copyOf(checkNotNull(headers, "headers")); + } public Multimap getHeaders() { return headers; } - public HttpMessage() { - this(null); - } - - public HttpMessage(@Nullable Payload payload) { - super(payload); - } - /** * try to get the value, then try as lowercase. */ @@ -65,6 +86,10 @@ public class HttpMessage extends PayloadEnclosingImpl { return (values.size() >= 1) ? values.iterator().next() : null; } + public Builder toBuilder() { + return Builder.from(this); + } + @Override public int hashCode() { final int prime = 31; diff --git a/core/src/main/java/org/jclouds/http/HttpRequest.java b/core/src/main/java/org/jclouds/http/HttpRequest.java index 026f96e06c..fb83dde8b5 100644 --- a/core/src/main/java/org/jclouds/http/HttpRequest.java +++ b/core/src/main/java/org/jclouds/http/HttpRequest.java @@ -21,7 +21,6 @@ package org.jclouds.http; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Lists.newArrayList; import java.net.URI; import java.util.Arrays; @@ -31,20 +30,75 @@ import javax.annotation.Nullable; import org.jclouds.io.Payload; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; /** - * Represents a request that can be executed within - * {@link HttpCommandExecutorService} + * Represents a request that can be executed within {@link HttpCommandExecutorService} * * @author Adrian Cole */ public class HttpRequest extends HttpMessage { + public static Builder builder() { + return new Builder(); + } - private List requestFilters = newArrayList(); - private String method; - private URI endpoint; - private char[] skips; + public static class Builder extends HttpMessage.Builder { + protected String method; + protected URI endpoint; + protected char[] skips = new char[] {}; + protected List requestFilters = ImmutableList.of(); + + public Builder filters(List requestFilters) { + this.requestFilters = ImmutableList.copyOf(checkNotNull(requestFilters, "requestFilters")); + return this; + } + + public Builder method(String method) { + this.method = checkNotNull(method, "method"); + return this; + } + + public Builder endpoint(URI endpoint) { + this.endpoint = checkNotNull(endpoint, "endpoint"); + return this; + } + + public Builder skips(char[] skips) { + char[] retval = new char[checkNotNull(skips, "skips").length]; + System.arraycopy(skips, 0, retval, 0, skips.length); + this.skips = retval; + return this; + } + + @Override + public Builder payload(Payload payload) { + return (Builder) super.payload(payload); + } + + @Override + public Builder headers(Multimap headers) { + return (Builder) super.headers(headers); + } + + @Override + @SuppressWarnings("unchecked") + public T build() { + return (T) new HttpRequest(method, endpoint, skips, requestFilters, payload, headers); + } + + public static Builder from(X input) { + return new Builder().method(input.getMethod()).endpoint(input.getEndpoint()).skips(input.getSkips()) + .filters(input.getFilters()).payload(input.getPayload()).headers(input.getHeaders()); + } + + } + + private final List requestFilters; + private final String method; + private final URI endpoint; + private final char[] skips; /** * @@ -58,10 +112,16 @@ public class HttpRequest extends HttpMessage { } public HttpRequest(String method, URI endpoint, char[] skips) { - this.setMethod(checkNotNull(method, "method")); - this.setEndpoint(checkNotNull(endpoint, "endpoint")); - checkArgument(endpoint.getHost() != null, String.format("endpoint.getHost() is null for %s", endpoint)); - this.skips = skips; + this(method, endpoint, skips, ImmutableList. of()); + } + + public HttpRequest(String method, URI endpoint, char[] skips, List requestFilters) { + this(method, endpoint, skips, requestFilters, null); + } + + public HttpRequest(String method, URI endpoint, char[] skips, List requestFilters, + @Nullable Payload payload) { + this(method, endpoint, skips, requestFilters, payload, ImmutableMultimap. of()); } /** @@ -72,8 +132,17 @@ public class HttpRequest extends HttpMessage { * If the request is HEAD, this may change to GET due to redirects */ public HttpRequest(String method, URI endpoint, Multimap headers) { - this(method, endpoint); - getHeaders().putAll(checkNotNull(headers, "headers")); + this(method, endpoint, new char[] {}, ImmutableList. of(), null, headers); + } + + public HttpRequest(String method, URI endpoint, char[] skips, List requestFilters, + @Nullable Payload payload, Multimap headers) { + super(payload, headers); + this.method = checkNotNull(method, "method"); + this.endpoint = checkNotNull(endpoint, "endpoint"); + checkArgument(endpoint.getHost() != null, String.format("endpoint.getHost() is null for %s", endpoint)); + this.skips = checkNotNull(skips, "skips"); + this.requestFilters = ImmutableList. copyOf(checkNotNull(requestFilters, "requestFilters")); } /** @@ -84,9 +153,7 @@ public class HttpRequest extends HttpMessage { * If the request is HEAD, this may change to GET due to redirects */ protected HttpRequest(String method, URI endpoint, Multimap headers, @Nullable Payload payload) { - this(method, endpoint); - getHeaders().putAll(checkNotNull(headers, "headers")); - setPayload(payload); + this(method, endpoint, new char[] {}, ImmutableList. of(), payload, headers); } public String getRequestLine() { @@ -94,12 +161,10 @@ public class HttpRequest extends HttpMessage { } /** - * We cannot return an enum, as per specification custom methods are allowed. - * Enums are not extensible. + * We cannot return an enum, as per specification custom methods are allowed. Enums are not + * extensible. * - * @see rfc2616 + * @see rfc2616 */ public String getMethod() { return method; @@ -112,10 +177,6 @@ public class HttpRequest extends HttpMessage { return skips; } - public void setSkips(char[] skips) { - this.skips = skips; - } - public URI getEndpoint() { return endpoint; } @@ -128,12 +189,9 @@ public class HttpRequest extends HttpMessage { return requestFilters; } - public void setMethod(String method) { - this.method = method; - } - - public void setEndpoint(URI endpoint) { - this.endpoint = endpoint; + @Override + public Builder toBuilder() { + return Builder.from(this); } @Override diff --git a/core/src/main/java/org/jclouds/http/HttpRequestFilter.java b/core/src/main/java/org/jclouds/http/HttpRequestFilter.java index 876893e423..af639b8fc9 100644 --- a/core/src/main/java/org/jclouds/http/HttpRequestFilter.java +++ b/core/src/main/java/org/jclouds/http/HttpRequestFilter.java @@ -21,16 +21,16 @@ package org.jclouds.http; /** * // TODO: Adrian: Document this! - * - * NOTE: {@link #filter} must be idempotent in a sense that - * multiple calls to it with the same request yield in the - * same output. - * Example: this is required for request retrial - * ({@link org.jclouds.http.internal.BaseHttpCommandExecutorService}, - * so that signatures can be updated. - * + * + * NOTE: {@link #filter} must be idempotent in a sense that multiple calls to it with the same + * request yield in the same output. Example: this is required for request retrial ( + * {@link org.jclouds.http.internal.BaseHttpCommandExecutorService}, so that signatures can be + * updated. + * * @author Adrian Cole */ public interface HttpRequestFilter { - void filter(HttpRequest request) throws HttpException; + // note this is not generic typed, as http implementations do not care + // about subclasses. + HttpRequest filter(HttpRequest request) throws HttpException; } diff --git a/core/src/main/java/org/jclouds/http/HttpResponse.java b/core/src/main/java/org/jclouds/http/HttpResponse.java index a39cdeb995..43349259b3 100644 --- a/core/src/main/java/org/jclouds/http/HttpResponse.java +++ b/core/src/main/java/org/jclouds/http/HttpResponse.java @@ -11,7 +11,7 @@ * * 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. + * WIHttpResponseHOUHttpResponse WARRANHttpResponseIES OR CONDIHttpResponseIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== @@ -34,6 +34,44 @@ import com.google.common.collect.Multimap; * @author Adrian Cole */ public class HttpResponse extends HttpMessage { + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends HttpMessage.Builder { + private int statusCode; + private String message; + + public Builder message(String message) { + this.message = checkNotNull(message, "message"); + return this; + } + + public Builder statusCode(int statusCode) { + this.statusCode = statusCode; + return this; + } + + @Override + public Builder payload(Payload payload) { + return (Builder) super.payload(payload); + } + + @Override + public Builder headers(Multimap headers) { + return (Builder) super.headers(headers); + } + + public HttpResponse build() { + return new HttpResponse(statusCode, message, payload, headers); + } + + public static Builder from(HttpResponse input) { + return new Builder().message(input.getMessage()).statusCode(input.getStatusCode()).payload(input.getPayload()) + .headers(input.getHeaders()); + } + + } private final int statusCode; private final String message; @@ -43,10 +81,9 @@ public class HttpResponse extends HttpMessage { } public HttpResponse(int statusCode, String message, @Nullable Payload payload, Multimap headers) { - super(payload); + super(payload, headers); this.statusCode = statusCode; this.message = message; - this.headers.putAll(checkNotNull(headers)); } public int getStatusCode() { @@ -67,6 +104,11 @@ public class HttpResponse extends HttpMessage { return String.format("HTTP/1.1 %d %s", getStatusCode(), getMessage()); } + @Override + public Builder toBuilder() { + return Builder.from(this); + } + @Override public int hashCode() { final int prime = 31; diff --git a/core/src/main/java/org/jclouds/http/HttpResponseException.java b/core/src/main/java/org/jclouds/http/HttpResponseException.java index d938a8e2a9..9fe9bbddfb 100644 --- a/core/src/main/java/org/jclouds/http/HttpResponseException.java +++ b/core/src/main/java/org/jclouds/http/HttpResponseException.java @@ -24,7 +24,7 @@ import java.io.IOException; import javax.annotation.Nullable; import org.jclouds.io.payloads.StringPayload; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * Represents an error obtained from an HttpResponse. @@ -45,8 +45,8 @@ public class HttpResponseException extends RuntimeException { this.response = response; } - public HttpResponseException(String message, HttpCommand command, @Nullable HttpResponse response, String content, - Throwable cause) { + public HttpResponseException(String message, HttpCommand command, @Nullable HttpResponse response, + String content, Throwable cause) { super(message, cause); this.command = command; this.response = response; @@ -54,12 +54,12 @@ public class HttpResponseException extends RuntimeException { } public HttpResponseException(HttpCommand command, HttpResponse response, Throwable cause) { - this(String.format("command: %1$s failed with response: %2$s", command.getRequest().getRequestLine(), + this(String.format("command: %1$s failed with response: %2$s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()), command, response, cause); } public HttpResponseException(HttpCommand command, HttpResponse response, String content, Throwable cause) { - this(String.format("command: %1$s failed with response: %2$s; content: [%3$s]", command.getRequest() + this(String.format("command: %1$s failed with response: %2$s; content: [%3$s]", command.getCurrentRequest() .getRequestLine(), response.getStatusLine()), command, response, content, cause); } @@ -77,9 +77,9 @@ public class HttpResponseException extends RuntimeException { } public HttpResponseException(HttpCommand command, HttpResponse response) { - this(String.format("request: %s %sfailed with response: %s", command.getRequest().getRequestLine(), - requestPayloadIfStringOrFormIfNotReturnEmptyString(command.getRequest()), response.getStatusLine()), - command, response); + this(String.format("request: %s %sfailed with response: %s", command.getCurrentRequest().getRequestLine(), + requestPayloadIfStringOrFormIfNotReturnEmptyString((HttpRequest) command.getCurrentRequest()), + response.getStatusLine()), command, response); } static String requestPayloadIfStringOrFormIfNotReturnEmptyString(HttpRequest request) { @@ -90,7 +90,7 @@ public class HttpResponseException extends RuntimeException { && request.getPayload().getContentMetadata().getContentLength() < 1024) { try { return String.format(" [%s] ", request.getPayload() instanceof StringPayload ? request.getPayload() - .getRawContent() : Utils.toStringAndClose(request.getPayload().getInput())); + .getRawContent() : Strings2.toStringAndClose(request.getPayload().getInput())); } catch (IOException e) { } } @@ -98,8 +98,8 @@ public class HttpResponseException extends RuntimeException { } public HttpResponseException(HttpCommand command, HttpResponse response, String content) { - this(String.format("command: %s failed with response: %s; content: [%s]", command.getRequest().getRequestLine(), - response.getStatusLine(), content), command, response, content); + this(String.format("command: %s failed with response: %s; content: [%s]", command.getCurrentRequest() + .getRequestLine(), response.getStatusLine(), content), command, response, content); } public HttpCommand getCommand() { diff --git a/core/src/main/java/org/jclouds/http/HttpRetryHandler.java b/core/src/main/java/org/jclouds/http/HttpRetryHandler.java index f6eff126e3..822b5f95ad 100644 --- a/core/src/main/java/org/jclouds/http/HttpRetryHandler.java +++ b/core/src/main/java/org/jclouds/http/HttpRetryHandler.java @@ -30,12 +30,22 @@ public interface HttpRetryHandler { public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { return true; } + + @Override + public String toString() { + return "ALWAYS_RETRY"; + } }; public static final HttpRetryHandler NEVER_RETRY = new HttpRetryHandler() { public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { return false; } + + @Override + public String toString() { + return "NEVER_RETRY"; + } }; /** diff --git a/core/src/main/java/org/jclouds/http/HttpUtils.java b/core/src/main/java/org/jclouds/http/HttpUtils.java index d103067e0a..561460a316 100644 --- a/core/src/main/java/org/jclouds/http/HttpUtils.java +++ b/core/src/main/java/org/jclouds/http/HttpUtils.java @@ -23,52 +23,30 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.getCausalChain; import static com.google.common.base.Throwables.propagate; -import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.size; import static com.google.common.collect.Lists.newArrayList; -import static com.google.common.collect.Sets.newTreeSet; import static com.google.common.io.ByteStreams.toByteArray; import static com.google.common.io.Closeables.closeQuietly; -import static java.util.Collections.singletonList; import static javax.ws.rs.core.HttpHeaders.CONTENT_ENCODING; import static javax.ws.rs.core.HttpHeaders.CONTENT_LANGUAGE; import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH; import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; -import static javax.ws.rs.core.HttpHeaders.HOST; -import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; -import static org.jclouds.util.Patterns.CHAR_TO_ENCODED_PATTERN; import static org.jclouds.util.Patterns.PATTERN_THAT_BREAKS_URI; -import static org.jclouds.util.Patterns.PLUS_PATTERN; -import static org.jclouds.util.Patterns.STAR_PATTERN; import static org.jclouds.util.Patterns.URI_PATTERN; -import static org.jclouds.util.Patterns.URL_ENCODED_PATTERN; -import static org.jclouds.util.Patterns._7E_PATTERN; -import static org.jclouds.util.Utils.replaceAll; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.URI; -import java.net.URLDecoder; -import java.net.URLEncoder; import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; import java.util.List; -import java.util.Map; -import java.util.SortedSet; import java.util.Map.Entry; import java.util.regex.Matcher; -import javax.annotation.Nullable; import javax.inject.Named; import javax.inject.Singleton; -import javax.ws.rs.HttpMethod; import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriBuilder; import org.jclouds.Constants; import org.jclouds.crypto.CryptoStreams; @@ -80,12 +58,13 @@ import org.jclouds.io.PayloadEnclosing; import org.jclouds.io.Payloads; import org.jclouds.logging.Logger; import org.jclouds.logging.internal.Wire; +import org.jclouds.util.Strings2; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; import com.google.common.collect.Multimap; import com.google.common.collect.SortedSetMultimap; import com.google.common.collect.TreeMultimap; @@ -104,7 +83,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; @@ -128,9 +107,9 @@ public class HttpUtils { @Inject public HttpUtils(@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_SO_TIMEOUT) int soTimeout, + @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT) int globalMaxConnections, + @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST) int globalMaxConnectionsPerHost) { this.soTimeout = soTimeout; this.connectionTimeout = connectionTimeout; this.globalMaxConnections = globalMaxConnections; @@ -205,51 +184,21 @@ public class HttpUtils { } } - public static void addContentHeadersFromMetadata(ContentMetadata md, Multimap allHeaders) { + public static Multimap getContentHeadersFromMetadata(ContentMetadata md) { + Builder builder = ImmutableMultimap.builder(); if (md.getContentType() != null) - allHeaders.replaceValues(HttpHeaders.CONTENT_TYPE, Collections.singleton(md.getContentType())); + builder.put(HttpHeaders.CONTENT_TYPE, md.getContentType()); if (md.getContentDisposition() != null) - allHeaders.replaceValues("Content-Disposition", Collections.singleton(md.getContentDisposition())); + builder.put("Content-Disposition", md.getContentDisposition()); if (md.getContentEncoding() != null) - allHeaders.replaceValues(HttpHeaders.CONTENT_ENCODING, Collections.singleton(md.getContentEncoding())); - if (md.getContentEncoding() != null) - allHeaders.replaceValues(HttpHeaders.CONTENT_LANGUAGE, Collections.singleton(md.getContentLanguage())); + builder.put(HttpHeaders.CONTENT_ENCODING, md.getContentEncoding()); + if (md.getContentLanguage() != null) + builder.put(HttpHeaders.CONTENT_LANGUAGE, md.getContentLanguage()); if (md.getContentLength() != null) - allHeaders.replaceValues(HttpHeaders.CONTENT_LENGTH, Collections.singleton(md.getContentLength() + "")); + builder.put(HttpHeaders.CONTENT_LENGTH, md.getContentLength() + ""); if (md.getContentMD5() != null) - allHeaders.replaceValues("Content-MD5", Collections.singleton(CryptoStreams.base64(md.getContentMD5()))); - } - - /** - * 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)) - return in; - try { - String returnVal = URLEncoder.encode(in, "UTF-8"); - returnVal = replaceAll(returnVal, '+', PLUS_PATTERN, "%20"); - returnVal = replaceAll(returnVal, '*', STAR_PATTERN, "%2A"); - returnVal = replaceAll(returnVal, _7E_PATTERN, "~"); - for (char c : skipEncode) { - returnVal = replaceAll(returnVal, CHAR_TO_ENCODED_PATTERN.get(c), c + ""); - } - return returnVal; - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("Bad encoding on input: " + in, e); - } - } - - public static boolean isUrlEncoded(String in) { - return URL_ENCODED_PATTERN.matcher(in).matches(); - } - - public static String urlDecode(String in) { - try { - return URLDecoder.decode(in, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("Bad encoding on input: " + in, e); - } + builder.put("Content-MD5", CryptoStreams.base64(md.getContentMD5())); + return builder.build(); } public static byte[] toByteArrayOrNull(PayloadEnclosing response) { @@ -296,12 +245,12 @@ public class HttpUtils { URI redirectURI = URI.create(hostHeader); String scheme = redirectURI.getScheme(); - checkState(redirectURI.getScheme().startsWith("http"), String.format( - "header %s didn't parse an http scheme: [%s]", hostHeader, scheme)); + 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; 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; } @@ -320,21 +269,21 @@ public class HttpUtils { public static URI createUri(String uriPath) { List onQuery = newArrayList(Splitter.on('?').split(uriPath)); if (onQuery.size() == 2) { - onQuery.add(urlEncode(onQuery.remove(1), '=', '&')); + onQuery.add(Strings2.urlEncode(onQuery.remove(1), '=', '&')); uriPath = Joiner.on('?').join(onQuery); } if (uriPath.indexOf('@') != 1) { List parts = newArrayList(Splitter.on('@').split(uriPath)); String path = parts.remove(parts.size() - 1); if (parts.size() > 1) { - parts = newArrayList(urlEncode(Joiner.on('@').join(parts), '/', ':')); + parts = newArrayList(Strings2.urlEncode(Joiner.on('@').join(parts), '/', ':')); } - parts.add(urlEncode(path, '/', ':')); + parts.add(Strings2.urlEncode(path, '/', ':')); uriPath = Joiner.on('@').join(parts); } else { List parts = newArrayList(Splitter.on('/').split(uriPath)); String path = parts.remove(parts.size() - 1); - parts.add(urlEncode(path, ':')); + parts.add(Strings2.urlEncode(path, ':')); uriPath = Joiner.on('/').join(parts); } @@ -346,7 +295,8 @@ 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, Strings2.urlEncode(identity), + Strings2.urlEncode(key), rest)); } else { throw new IllegalArgumentException("bad syntax"); } @@ -372,23 +322,27 @@ public class HttpUtils { logger.debug("%s %s: %s", prefix, CONTENT_TYPE, message.getPayload().getContentMetadata().getContentType()); if (message.getPayload().getContentMetadata().getContentLength() != null) logger.debug("%s %s: %s", prefix, CONTENT_LENGTH, message.getPayload().getContentMetadata() - .getContentLength()); + .getContentLength()); if (message.getPayload().getContentMetadata().getContentMD5() != null) try { - logger.debug("%s %s: %s", prefix, "Content-MD5", CryptoStreams.base64Encode(InputSuppliers.of(message - .getPayload().getContentMetadata().getContentMD5()))); + logger.debug( + "%s %s: %s", + prefix, + "Content-MD5", + CryptoStreams.base64Encode(InputSuppliers.of(message.getPayload().getContentMetadata() + .getContentMD5()))); } catch (IOException e) { logger.warn(e, " error getting md5 for %s", message); } if (message.getPayload().getContentMetadata().getContentDisposition() != null) logger.debug("%s %s: %s", prefix, "Content-Disposition", message.getPayload().getContentMetadata() - .getContentDisposition()); + .getContentDisposition()); if (message.getPayload().getContentMetadata().getContentEncoding() != null) logger.debug("%s %s: %s", prefix, CONTENT_ENCODING, message.getPayload().getContentMetadata() - .getContentEncoding()); + .getContentEncoding()); if (message.getPayload().getContentMetadata().getContentLanguage() != null) logger.debug("%s %s: %s", prefix, CONTENT_LANGUAGE, message.getPayload().getContentMetadata() - .getContentLanguage()); + .getContentLanguage()); } } @@ -410,195 +364,38 @@ public class HttpUtils { return buffer.toString(); } - /** - * 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) { - builder.uri(request.getEndpoint()); - builder.scheme(scheme); - builder.host(host); - builder.port(port); - request.setEndpoint(builder.build()); - request.getHeaders().replaceValues(HOST, singletonList(host)); - } - - /** - * change the path of the service. typically used in handling redirects. - */ - public static void changePathTo(HttpRequest request, String newPath, UriBuilder builder) { - builder.uri(request.getEndpoint()); - builder.replacePath(newPath); - request.setEndpoint(builder.build()); - } - - /** - * change method from GET to HEAD. typically used in handling redirects. - */ - public static void changeToGETRequest(HttpRequest request) { - request.setMethod(HttpMethod.GET); - } - - 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) { - addQueryParamTo(request, key, values, builder, request.getSkips()); - } - - 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) - map.put(key, o.toString()); - builder.replaceQuery(makeQueryLine(map, null, skips)); - request.setEndpoint(builder.build()); - } - - 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) { - builder.uri(request.getEndpoint()); - builder.replaceMatrixParam(name, values); - request.setEndpoint(builder.build()); - } - - public static void addFormParamTo(HttpRequest request, String key, String value) { - addFormParamTo(request, key, ImmutableSet. of(value)); - } - - public static void addFormParamTo(HttpRequest request, String key, Iterable values) { - Multimap map; - map = parseQueryToMap(request.getPayload().getRawContent().toString()); - for (Object o : values) - map.put(key, o.toString()); - request.setPayload(newUrlEncodedFormPayload(map)); - } - - public static Multimap parseQueryToMap(String in) { - Multimap map = LinkedListMultimap.create(); - if (in == null) { - } else if (in.indexOf('&') == -1) { - if (in.contains("=")) - parseKeyValueFromStringToMap(in, map); - else - map.put(in, null); - } else { - String[] parts = urlDecode(in).split("&"); - for (String part : parts) { - parseKeyValueFromStringToMap(part, map); - } - } - return 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); - map.put(key, value); - } - - 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(); - StringBuilder formBuilder = new StringBuilder(); - while (pairs.hasNext()) { - Map.Entry pair = pairs.next(); - formBuilder.append(urlEncode(pair.getKey(), skips)); - if (pair.getValue() != null && !pair.getValue().equals("")) { - formBuilder.append("="); - formBuilder.append(urlEncode(pair.getValue(), skips)); - } - if (pairs.hasNext()) - formBuilder.append("&"); - } - return formBuilder.toString(); - } - - public void setPayloadPropertiesFromHeaders(Multimap headers, HttpMessage message) { - Payload payload = message.getPayload(); - boolean chunked = any(headers.entries(), new Predicate>() { - @Override - public boolean apply(Entry input) { - return "Transfer-Encoding".equalsIgnoreCase(input.getKey()) && "chunked".equalsIgnoreCase(input.getValue()); - } - }); - - for (Entry header : headers.entries()) { - if (!chunked && CONTENT_LENGTH.equalsIgnoreCase(header.getKey())) { - if (payload != null) - payload.getContentMetadata().setContentLength(new Long(header.getValue())); - } else if ("Content-MD5".equalsIgnoreCase(header.getKey())) { - if (payload != null) - payload.getContentMetadata().setContentMD5(CryptoStreams.base64(header.getValue())); - } else if (CONTENT_TYPE.equalsIgnoreCase(header.getKey())) { - if (payload != null) - payload.getContentMetadata().setContentType(header.getValue()); - } else if ("Content-Disposition".equalsIgnoreCase(header.getKey())) { - if (payload != null) - payload.getContentMetadata().setContentDisposition(header.getValue()); - } else if ("Content-Encoding".equalsIgnoreCase(header.getKey())) { - if (payload != null) - payload.getContentMetadata().setContentEncoding(header.getValue()); - } else if ("Content-Language".equalsIgnoreCase(header.getKey())) { - if (payload != null) - payload.getContentMetadata().setContentLanguage(header.getValue()); - } else { - message.getHeaders().put(header.getKey(), header.getValue()); - } - } - - if (message instanceof HttpRequest) { - checkArgument( - message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_TYPE) == null, - "configuration error please use request.getPayload().getContentMetadata().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().getContentMetadata().setContentLength(value) as opposed to adding a content length header: " - + message); - checkArgument(message.getPayload() == null - || message.getPayload().getContentMetadata().getContentLength() != null + public void checkRequestHasRequiredProperties(HttpRequest message) { + checkArgument( + message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_TYPE) == null, + "configuration error please use request.getPayload().getContentMetadata().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().getContentMetadata().setContentLength(value) as opposed to adding a content length header: " + + message); + checkArgument( + message.getPayload() == null || message.getPayload().getContentMetadata().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().getContentMetadata().setContentMD5(value) as opposed to adding a content md5 header: " - + message); - checkArgument( - message.getPayload() == null || message.getFirstHeaderOrNull("Content-Disposition") == null, - "configuration error please use request.getPayload().getContentMetadata().setContentDisposition(value) as opposed to adding a content disposition header: " - + message); - checkArgument( - message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_ENCODING) == null, - "configuration error please use request.getPayload().getContentMetadata().setContentEncoding(value) as opposed to adding a content encoding header: " - + message); - checkArgument( - message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_LANGUAGE) == null, - "configuration error please use request.getPayload().getContentMetadata().setContentLanguage(value) as opposed to adding a content language header: " - + message); - - } + "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().getContentMetadata().setContentMD5(value) as opposed to adding a content md5 header: " + + message); + checkArgument( + message.getPayload() == null || message.getFirstHeaderOrNull("Content-Disposition") == null, + "configuration error please use request.getPayload().getContentMetadata().setContentDisposition(value) as opposed to adding a content disposition header: " + + message); + checkArgument( + message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_ENCODING) == null, + "configuration error please use request.getPayload().getContentMetadata().setContentEncoding(value) as opposed to adding a content encoding header: " + + message); + checkArgument( + message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_LANGUAGE) == null, + "configuration error please use request.getPayload().getContentMetadata().setContentLanguage(value) as opposed to adding a content language header: " + + message); } - public static void releasePayload(HttpResponse from) { + public static void releasePayload(HttpMessage from) { if (from.getPayload() != null) from.getPayload().release(); } @@ -615,7 +412,7 @@ public class HttpUtils { return (collection != null && collection.size() >= 1) ? collection.iterator().next() : ""; } - public static Long attemptToParseSizeAndRangeFromHeaders(HttpResponse from) throws HttpException { + public static Long attemptToParseSizeAndRangeFromHeaders(HttpMessage from) throws HttpException { String contentRange = from.getFirstHeaderOrNull("Content-Range"); if (contentRange == null && from.getPayload() != null) { return from.getPayload().getContentMetadata().getContentLength(); @@ -625,24 +422,24 @@ public class HttpUtils { return null; } - public static void checkRequestHasContentLengthOrChunkedEncoding(HttpRequest request, String message) { + public static void checkRequestHasContentLengthOrChunkedEncoding(HttpMessage request, String message) { boolean chunked = "chunked".equals(request.getFirstHeaderOrNull("Transfer-Encoding")); checkArgument(request.getPayload() == null || chunked - || request.getPayload().getContentMetadata().getContentLength() != null, message); + || request.getPayload().getContentMetadata().getContentLength() != null, message); } - public static void wirePayloadIfEnabled(Wire wire, HttpRequest request) { + public static void wirePayloadIfEnabled(Wire wire, HttpMessage request) { if (request.getPayload() != null && wire.enabled()) { wire.output(request); checkRequestHasContentLengthOrChunkedEncoding(request, - "After wiring, the request has neither chunked encoding nor content length: " + request); + "After wiring, the request has neither chunked encoding nor content length: " + request); } } public static T returnValueOnCodeOrNull(Exception from, T value, Predicate codePredicate) { Iterable throwables = filter(getCausalChain(from), HttpResponseException.class); if (size(throwables) >= 1 && get(throwables, 0).getResponse() != null - && codePredicate.apply(get(throwables, 0).getResponse().getStatusCode())) { + && codePredicate.apply(get(throwables, 0).getResponse().getStatusCode())) { return value; } return null; diff --git a/core/src/main/java/org/jclouds/http/IOExceptionRetryHandler.java b/core/src/main/java/org/jclouds/http/IOExceptionRetryHandler.java index 3e1c7a2383..f5dbd7df4d 100644 --- a/core/src/main/java/org/jclouds/http/IOExceptionRetryHandler.java +++ b/core/src/main/java/org/jclouds/http/IOExceptionRetryHandler.java @@ -36,12 +36,22 @@ public interface IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException response) { return true; } + + @Override + public String toString() { + return "ALWAYS_RETRY"; + } }; public static final IOExceptionRetryHandler NEVER_RETRY = new IOExceptionRetryHandler() { public boolean shouldRetryRequest(HttpCommand command, IOException response) { return false; } + + @Override + public String toString() { + return "NEVER_RETRY"; + } }; boolean shouldRetryRequest(HttpCommand command, IOException error); diff --git a/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorService.java b/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorService.java index 0c4dd9b218..6c75f1462f 100644 --- a/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorService.java +++ b/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorService.java @@ -43,6 +43,7 @@ public interface TransformingHttpCommandExecutorService { * how to transform the response from the above command * @return value of the intended response. */ - public ListenableFuture submit(HttpCommand command, Function responseTransformer); + public ListenableFuture submit(HttpCommand command, + Function responseTransformer); } diff --git a/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorServiceImpl.java b/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorServiceImpl.java index 89806667ae..2afa723b32 100644 --- a/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorServiceImpl.java +++ b/core/src/main/java/org/jclouds/http/TransformingHttpCommandExecutorServiceImpl.java @@ -42,7 +42,7 @@ public class TransformingHttpCommandExecutorServiceImpl implements TransformingH @Inject public TransformingHttpCommandExecutorServiceImpl(HttpCommandExecutorService client, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads) { + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads) { this.client = client; this.userThreads = userThreads; } @@ -50,7 +50,8 @@ public class TransformingHttpCommandExecutorServiceImpl implements TransformingH /** * {@inheritDoc} */ - public ListenableFuture submit(HttpCommand command, Function responseTransformer) { + public ListenableFuture submit(HttpCommand command, + Function responseTransformer) { return Futures.compose(client.submit(command), responseTransformer, userThreads); } diff --git a/core/src/main/java/org/jclouds/http/TransformingHttpCommandImpl.java b/core/src/main/java/org/jclouds/http/TransformingHttpCommandImpl.java index 5cf1ebc40d..8cf5cc3465 100644 --- a/core/src/main/java/org/jclouds/http/TransformingHttpCommandImpl.java +++ b/core/src/main/java/org/jclouds/http/TransformingHttpCommandImpl.java @@ -19,6 +19,8 @@ package org.jclouds.http; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.concurrent.ExecutionException; import javax.annotation.Resource; @@ -39,65 +41,109 @@ import com.google.common.util.concurrent.ListenableFuture; */ public class TransformingHttpCommandImpl implements TransformingHttpCommand { - private final TransformingHttpCommandExecutorService executorService; - private final Function transformer; + protected final TransformingHttpCommandExecutorService executorService; + protected final Function transformer; - private HttpRequest request; - private volatile int failureCount; + protected volatile HttpRequest request; + protected volatile int failureCount; + protected volatile int redirectCount; + protected volatile Exception exception; @Resource protected Logger logger = Logger.NULL; - private volatile int redirectCount; - protected volatile Exception exception; - @Inject - public TransformingHttpCommandImpl(TransformingHttpCommandExecutorService executorService, - HttpRequest request, Function transformer) { - this.request = request; - this.executorService = executorService; - this.transformer = transformer; + public TransformingHttpCommandImpl(TransformingHttpCommandExecutorService executorService, HttpRequest request, + Function transformer) { + this.request = checkNotNull(request, "request"); + this.executorService = checkNotNull(executorService, "executorService"); + this.transformer = checkNotNull(transformer, "transformer"); this.failureCount = 0; + this.redirectCount = 0; } + /** + * {@inheritDoc} + */ + @Override public ListenableFuture execute() throws ExecutionException { if (exception != null) throw new ExecutionException(exception); return executorService.submit(this, transformer); } + /** + * {@inheritDoc} + */ + @Override public int getFailureCount() { return failureCount; } + /** + * {@inheritDoc} + */ + @Override public int incrementFailureCount() { return ++failureCount; } + /** + * {@inheritDoc} + */ + @Override public void setException(Exception exception) { this.exception = exception; } + /** + * {@inheritDoc} + */ + @Override public Exception getException() { return exception; } + /** + * {@inheritDoc} + */ + @Override public int incrementRedirectCount() { return ++redirectCount; } + /** + * {@inheritDoc} + */ + @Override public int getRedirectCount() { return redirectCount; } + /** + * {@inheritDoc} + */ + @Override public boolean isReplayable() { return (request.getPayload() == null) ? true : request.getPayload().isRepeatable(); } - public HttpRequest getRequest() { + /** + * {@inheritDoc} + */ + @Override + public HttpRequest getCurrentRequest() { return request; } + /** + * {@inheritDoc} + */ + @Override + public void setCurrentRequest(HttpRequest request) { + this.request = request; + } + @Override public String toString() { return "[request=" + request.getRequestLine() + "]"; diff --git a/core/src/main/java/org/jclouds/http/filters/BasicAuthentication.java b/core/src/main/java/org/jclouds/http/filters/BasicAuthentication.java index a8229aa267..398301968d 100644 --- a/core/src/main/java/org/jclouds/http/filters/BasicAuthentication.java +++ b/core/src/main/java/org/jclouds/http/filters/BasicAuthentication.java @@ -24,7 +24,6 @@ import static org.jclouds.Constants.PROPERTY_CREDENTIAL; import static org.jclouds.Constants.PROPERTY_IDENTITY; import java.io.UnsupportedEncodingException; -import java.util.Set; import javax.inject.Inject; import javax.inject.Named; @@ -36,8 +35,7 @@ import org.jclouds.crypto.CryptoStreams; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; - -import com.google.common.collect.ImmutableSet; +import org.jclouds.http.utils.ModifyRequest; /** * Uses Basic Authentication to sign the request. @@ -49,17 +47,18 @@ import com.google.common.collect.ImmutableSet; @Singleton public class BasicAuthentication implements HttpRequestFilter { - private final Set credentialList; + private final String header; @Inject public BasicAuthentication(@Named(PROPERTY_IDENTITY) String user, @Named(PROPERTY_CREDENTIAL) String password, Crypto crypto) throws UnsupportedEncodingException { - this.credentialList = ImmutableSet.of("Basic " + this.header = "Basic " + CryptoStreams.base64(String.format("%s:%s", checkNotNull(user, "user"), - checkNotNull(password, "password")).getBytes("UTF-8"))); + checkNotNull(password, "password")).getBytes("UTF-8")); } - public void filter(HttpRequest request) throws HttpException { - request.getHeaders().replaceValues(HttpHeaders.AUTHORIZATION, credentialList); + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.replaceHeader(request, HttpHeaders.AUTHORIZATION, header); } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/http/functions/ParseContentMD5FromHeaders.java b/core/src/main/java/org/jclouds/http/functions/ParseContentMD5FromHeaders.java index e112610f53..a4576d550b 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseContentMD5FromHeaders.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseContentMD5FromHeaders.java @@ -33,7 +33,8 @@ import com.google.common.base.Function; /** * @author Adrian Cole */ -public class ParseContentMD5FromHeaders implements Function, InvocationContext { +public class ParseContentMD5FromHeaders implements Function, + InvocationContext { public static class NoContentMD5Exception extends RuntimeException { 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 fc4ccb79a8..ddd28672e7 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseJson.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseJson.java @@ -33,7 +33,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.json.Json; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; import com.google.inject.TypeLiteral; @@ -84,7 +84,7 @@ public class ParseJson implements Function { @SuppressWarnings("unchecked") public V apply(InputStream stream, Type type) throws IOException { try { - return (V) json.fromJson(Utils.toStringAndClose(stream), type); + return (V) json.fromJson(Strings2.toStringAndClose(stream), type); } finally { if (stream != null) stream.close(); diff --git a/core/src/main/java/org/jclouds/http/functions/ParseSax.java b/core/src/main/java/org/jclouds/http/functions/ParseSax.java index d313e468ca..c2b7be04ad 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseSax.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseSax.java @@ -32,7 +32,7 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.rest.InvocationContext; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; @@ -47,7 +47,7 @@ import com.google.common.base.Throwables; * * @author Adrian Cole */ -public class ParseSax implements Function, InvocationContext { +public class ParseSax implements Function, InvocationContext> { private final XMLReader parser; private final HandlerWithResult handler; @@ -77,7 +77,7 @@ public class ParseSax implements Function, InvocationContext private T convertStreamToStringAndParse(HttpResponse from) { try { - return parse(Utils.toStringAndClose(from.getPayload().getInput())); + return parse(Strings2.toStringAndClose(from.getPayload().getInput())); } catch (Exception e) { return addDetailsAndPropagate(from, e); } @@ -154,7 +154,8 @@ public class ParseSax implements Function, InvocationContext * * @author Adrian Cole */ - public abstract static class HandlerWithResult extends DefaultHandler implements InvocationContext { + public abstract static class HandlerWithResult extends DefaultHandler implements + InvocationContext> { private HttpRequest request; protected HttpRequest getRequest() { diff --git a/core/src/main/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20x.java b/core/src/main/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20x.java index 97ebdba1b7..f955bb782a 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20x.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20x.java @@ -35,7 +35,7 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.rest.InvocationContext; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; @@ -45,7 +45,7 @@ import com.google.common.base.Function; * @author Adrian Cole */ public class ParseURIFromListOrLocationHeaderIf20x implements Function, - InvocationContext { + InvocationContext { private final Provider uriBuilderProvider; @Inject @@ -62,7 +62,7 @@ public class ParseURIFromListOrLocationHeaderIf20x implements Function { InputStream payload = from.getPayload().getInput(); String toReturn = null; try { - toReturn = Utils.toStringAndClose(payload); + toReturn = Strings2.toStringAndClose(payload); } catch (IOException e) { throw new HttpException(String.format( "Couldn't receive response %1$s, payload: %2$s ", from, toReturn), e); diff --git a/core/src/main/java/org/jclouds/http/functions/ReturnTrueOn404.java b/core/src/main/java/org/jclouds/http/functions/ReturnTrueOn404.java index 933d942513..2588895365 100644 --- a/core/src/main/java/org/jclouds/http/functions/ReturnTrueOn404.java +++ b/core/src/main/java/org/jclouds/http/functions/ReturnTrueOn404.java @@ -21,10 +21,11 @@ package org.jclouds.http.functions; import static com.google.common.base.Predicates.equalTo; import static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; + import com.google.common.base.Function; @Singleton diff --git a/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java b/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java index c37746fafa..9ab4562df5 100644 --- a/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java +++ b/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java @@ -107,7 +107,7 @@ public class BackoffLimitedRetryHandler implements HttpRetryHandler, IOException return false; } else if (command.getFailureCount() > retryCountLimit) { logger.warn("Cannot retry after server error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, - command); + command); return false; } else { imposeBackoffExponentialDelay(command.getFailureCount(), "server error: " + command.toString()); diff --git a/core/src/main/java/org/jclouds/http/handlers/CloseContentAndSetExceptionErrorHandler.java b/core/src/main/java/org/jclouds/http/handlers/CloseContentAndSetExceptionErrorHandler.java index e7c5f264ca..a1ce870dbf 100644 --- a/core/src/main/java/org/jclouds/http/handlers/CloseContentAndSetExceptionErrorHandler.java +++ b/core/src/main/java/org/jclouds/http/handlers/CloseContentAndSetExceptionErrorHandler.java @@ -29,7 +29,7 @@ import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * @@ -41,8 +41,7 @@ public class CloseContentAndSetExceptionErrorHandler implements HttpErrorHandler public void handleError(HttpCommand command, HttpResponse from) { String content; try { - content = from.getPayload() != null ? Utils.toStringAndClose(from.getPayload().getInput()) - : null; + content = from.getPayload() != null ? Strings2.toStringAndClose(from.getPayload().getInput()) : null; command.setException(new HttpResponseException(command, from, content)); } catch (IOException e) { command.setException(new HttpResponseException(command, from)); diff --git a/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java b/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java index 11d715e163..f45373b060 100644 --- a/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java +++ b/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java @@ -34,8 +34,10 @@ import javax.ws.rs.core.UriBuilder; import org.jclouds.Constants; import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpRetryHandler; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.logging.Logger; import com.google.inject.Inject; @@ -70,28 +72,31 @@ public class RedirectionRetryHandler implements HttpRetryHandler { URI redirectionUrl = URI.create(hostHeader); // if you are sent the same uri, assume there's a transient problem and retry. - if (redirectionUrl.equals(command.getRequest().getEndpoint())) + HttpRequest currentRequest = command.getCurrentRequest(); + if (redirectionUrl.equals(currentRequest.getEndpoint())) return backoffHandler.shouldRetryRequest(command, response); - UriBuilder builder = uriBuilderProvider.get().uri(command.getRequest().getEndpoint()); + UriBuilder builder = uriBuilderProvider.get().uri(currentRequest.getEndpoint()); assert redirectionUrl.getPath() != null : "no path in redirect header from: " + response; builder.replacePath(redirectionUrl.getPath()); if (redirectionUrl.getScheme() != null) builder.scheme(redirectionUrl.getScheme()); - - if (redirectionUrl.getHost() != null) { - builder.host(redirectionUrl.getHost()); - if (command.getRequest().getFirstHeaderOrNull(HOST) != null) - command.getRequest().getHeaders().replaceValues(HOST, singletonList(redirectionUrl.getHost())); - } - if (redirectionUrl.getPort() != command.getRequest().getEndpoint().getPort()) + if (redirectionUrl.getPort() != currentRequest.getEndpoint().getPort()) builder.port(redirectionUrl.getPort()); - if (redirectionUrl.getQuery() != null) builder.replaceQuery(redirectionUrl.getQuery()); - command.getRequest().setEndpoint(builder.build()); + if (redirectionUrl.getHost() != null) + builder.host(redirectionUrl.getHost()); + + if (currentRequest.getFirstHeaderOrNull(HOST) != null && redirectionUrl.getHost() != null) { + command.setCurrentRequest(ModifyRequest + .replaceHeader(currentRequest, HOST, singletonList(redirectionUrl.getHost())).toBuilder() + .endpoint(builder.build()).build()); + } else { + command.setCurrentRequest(currentRequest.toBuilder().endpoint(builder.build()).build()); + } return true; } else { return false; diff --git a/core/src/main/java/org/jclouds/http/internal/BaseHttpCommandExecutorService.java b/core/src/main/java/org/jclouds/http/internal/BaseHttpCommandExecutorService.java index d21638e7a9..09a47ee87c 100644 --- a/core/src/main/java/org/jclouds/http/internal/BaseHttpCommandExecutorService.java +++ b/core/src/main/java/org/jclouds/http/internal/BaseHttpCommandExecutorService.java @@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.io.ByteStreams.copy; import static org.jclouds.http.HttpUtils.checkRequestHasContentLengthOrChunkedEncoding; import static org.jclouds.http.HttpUtils.wirePayloadIfEnabled; -import static org.jclouds.util.Utils.getFirstThrowableOfType; import java.io.FilterInputStream; import java.io.IOException; @@ -48,6 +47,7 @@ import org.jclouds.http.IOExceptionRetryHandler; import org.jclouds.http.handlers.DelegatingErrorHandler; import org.jclouds.http.handlers.DelegatingRetryHandler; import org.jclouds.logging.Logger; +import org.jclouds.util.Throwables2; import com.google.common.io.NullOutputStream; @@ -73,9 +73,9 @@ public abstract class BaseHttpCommandExecutorService implements HttpCommandEx @Inject protected BaseHttpCommandExecutorService(HttpUtils utils, - @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, - DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, - DelegatingErrorHandler errorHandler, HttpWire wire) { + @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, + DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, + DelegatingErrorHandler errorHandler, HttpWire wire) { this.utils = checkNotNull(utils, "utils"); this.retryHandler = checkNotNull(retryHandler, "retryHandler"); this.ioRetryHandler = checkNotNull(ioRetryHandler, "ioRetryHandler"); @@ -121,11 +121,11 @@ public abstract class BaseHttpCommandExecutorService implements HttpCommandEx } + @Override public Future submit(HttpCommand command) { - HttpRequest request = command.getRequest(); + HttpRequest request = command.getCurrentRequest(); checkRequestHasContentLengthOrChunkedEncoding(request, - "if the request has a payload, it must be set to chunked encoding or specify a content length: " - + request); + "if the request has a payload, it must be set to chunked encoding or specify a content length: " + request); return ioWorkerExecutor.submit(new HttpResponseCallable(command)); } @@ -140,14 +140,14 @@ public abstract class BaseHttpCommandExecutorService implements HttpCommandEx HttpResponse response = null; for (;;) { - HttpRequest request = command.getRequest(); + HttpRequest request = command.getCurrentRequest(); Q nativeRequest = null; try { for (HttpRequestFilter filter : request.getFilters()) { - filter.filter(request); + request = filter.filter(request); } checkRequestHasContentLengthOrChunkedEncoding(request, - "After filtering, the request has niether chunked encoding nor content length: " + request); + "After filtering, the request has niether chunked encoding nor content length: " + request); logger.debug("Sending request %s: %s", request.hashCode(), request.getRequestLine()); wirePayloadIfEnabled(wire, request); nativeRequest = convert(request); @@ -168,12 +168,12 @@ public abstract class BaseHttpCommandExecutorService implements HttpCommandEx break; } } catch (Exception e) { - IOException ioe = getFirstThrowableOfType(e, IOException.class); + IOException ioe = Throwables2.getFirstThrowableOfType(e, IOException.class); if (ioe != null && ioRetryHandler.shouldRetryRequest(command, ioe)) { continue; } else { command.setException(new HttpResponseException(e.getMessage() + " connecting to " - + command.getRequest().getRequestLine(), command, null, e)); + + command.getCurrentRequest().getRequestLine(), command, null, e)); break; } } finally { diff --git a/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java b/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java index 58d016fe1b..8d198cfa99 100644 --- a/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java +++ b/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java @@ -62,6 +62,7 @@ import org.jclouds.io.MutableContentMetadata; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; import org.jclouds.logging.Logger; +import org.jclouds.rest.internal.RestAnnotationProcessor; import com.google.common.base.Supplier; import com.google.common.base.Throwables; @@ -85,11 +86,11 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe @Inject public JavaUrlHttpCommandExecutorService(HttpUtils utils, - @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, - DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, - DelegatingErrorHandler errorHandler, HttpWire wire, @Named("untrusted") HostnameVerifier verifier, - @Named("untrusted") Supplier untrustedSSLContextProvider) throws SecurityException, - NoSuchFieldException { + @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, + DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, + DelegatingErrorHandler errorHandler, HttpWire wire, @Named("untrusted") HostnameVerifier verifier, + @Named("untrusted") Supplier untrustedSSLContextProvider) throws SecurityException, + NoSuchFieldException { super(utils, ioWorkerExecutor, retryHandler, ioRetryHandler, errorHandler, wire); if (utils.getMaxConnections() > 0) System.setProperty("http.maxConnections", String.valueOf(checkNotNull(utils, "utils").getMaxConnections())); @@ -116,16 +117,15 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe closeQuietly(in); in = null; } - - Payload payload = in != null ? Payloads.newInputStreamPayload(in) : null; - HttpResponse response = new HttpResponse(connection.getResponseCode(), connection.getResponseMessage(), payload); Multimap headers = LinkedHashMultimap.create(); for (String header : connection.getHeaderFields().keySet()) { headers.putAll(header, connection.getHeaderFields().get(header)); } - utils.setPayloadPropertiesFromHeaders(headers, response); - - return response; + Payload payload = in != null ? Payloads.newInputStreamPayload(in) : null; + if (payload != null) + payload.getContentMetadata().setPropertiesFromHttpHeaders(headers); + return new HttpResponse(connection.getResponseCode(), connection.getResponseMessage(), payload, + RestAnnotationProcessor.filterOutContentHeaders(headers)); } private InputStream bufferAndCloseStream(InputStream inputStream) throws IOException { @@ -189,7 +189,7 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe } } - for (String header : request.getHeaders().keySet()) { + for (String header : request.getHeaders().keys()) { for (String value : request.getHeaders().get(header)) { connection.setRequestProperty(header, value); } diff --git a/core/src/main/java/org/jclouds/http/options/BaseHttpRequestOptions.java b/core/src/main/java/org/jclouds/http/options/BaseHttpRequestOptions.java index 23122bad8c..12f710748e 100644 --- a/core/src/main/java/org/jclouds/http/options/BaseHttpRequestOptions.java +++ b/core/src/main/java/org/jclouds/http/options/BaseHttpRequestOptions.java @@ -32,10 +32,10 @@ import com.google.common.collect.Multimap; */ public class BaseHttpRequestOptions implements HttpRequestOptions { - protected Multimap matrixParameters = LinkedHashMultimap.create(); - protected Multimap formParameters = LinkedHashMultimap.create(); - protected Multimap queryParameters = LinkedHashMultimap.create(); - protected Multimap headers = LinkedHashMultimap.create(); + protected final Multimap matrixParameters = LinkedHashMultimap.create(); + protected final Multimap formParameters = LinkedHashMultimap.create(); + protected final Multimap queryParameters = LinkedHashMultimap.create(); + protected final Multimap headers = LinkedHashMultimap.create(); protected String payload; protected String pathSuffix; diff --git a/core/src/main/java/org/jclouds/http/options/GetOptions.java b/core/src/main/java/org/jclouds/http/options/GetOptions.java index 585a9b0398..af9540615e 100644 --- a/core/src/main/java/org/jclouds/http/options/GetOptions.java +++ b/core/src/main/java/org/jclouds/http/options/GetOptions.java @@ -110,12 +110,10 @@ public class GetOptions extends BaseHttpRequestOptions { * Not compatible with {@link #ifETagMatches(String)} or {@link #ifUnmodifiedSince(Date)} */ public GetOptions ifModifiedSince(Date ifModifiedSince) { - checkArgument(getIfMatch() == null, - "ifETagMatches() is not compatible with ifModifiedSince()"); - checkArgument(getIfUnmodifiedSince() == null, - "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); - this.headers.put(HttpHeaders.IF_MODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull( - ifModifiedSince, "ifModifiedSince"))); + checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifModifiedSince()"); + checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); + this.headers.put(HttpHeaders.IF_MODIFIED_SINCE, + dateService.rfc822DateFormat(checkNotNull(ifModifiedSince, "ifModifiedSince"))); return this; } @@ -137,12 +135,10 @@ public class GetOptions extends BaseHttpRequestOptions { * Not compatible with {@link #ifETagDoesntMatch(String)} or {@link #ifModifiedSince(Date)} */ public GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince) { - checkArgument(getIfNoneMatch() == null, - "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); - checkArgument(getIfModifiedSince() == null, - "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); - this.headers.put(HttpHeaders.IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull( - ifUnmodifiedSince, "ifUnmodifiedSince"))); + checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); + checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); + this.headers.put(HttpHeaders.IF_UNMODIFIED_SINCE, + dateService.rfc822DateFormat(checkNotNull(ifUnmodifiedSince, "ifUnmodifiedSince"))); return this; } @@ -170,10 +166,8 @@ public class GetOptions extends BaseHttpRequestOptions { * if there was a problem converting this into an S3 eTag string */ public GetOptions ifETagMatches(String eTag) { - checkArgument(getIfNoneMatch() == null, - "ifETagDoesntMatch() is not compatible with ifETagMatches()"); - checkArgument(getIfModifiedSince() == null, - "ifModifiedSince() is not compatible with ifETagMatches()"); + checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); + checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(HttpHeaders.IF_MATCH, String.format("\"%1$s\"", checkNotNull(eTag, "eTag"))); return this; } @@ -201,20 +195,17 @@ public class GetOptions extends BaseHttpRequestOptions { * if there was a problem converting this into an S3 eTag string */ public GetOptions ifETagDoesntMatch(String eTag) { - checkArgument(getIfMatch() == null, - "ifETagMatches() is not compatible with ifETagDoesntMatch()"); - checkArgument(getIfUnmodifiedSince() == null, - "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); - this.headers.put(HttpHeaders.IF_NONE_MATCH, String.format("\"%1$s\"", checkNotNull(eTag, - "ifETagDoesntMatch"))); + checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); + checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); + this.headers.put(HttpHeaders.IF_NONE_MATCH, String.format("\"%1$s\"", checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } /** * For use in the request header: If-None-Match *

- * Return the object only if its payload tag (ETag) is different from the one specified, otherwise - * return a 304 (not modified). + * Return the object only if its payload tag (ETag) is different from the one specified, + * otherwise return a 304 (not modified). * * @see #ifETagDoesntMatch(String) */ @@ -285,4 +276,37 @@ public class GetOptions extends BaseHttpRequestOptions { } } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((ranges == null) ? 0 : ranges.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + GetOptions other = (GetOptions) obj; + if (ranges == null) { + if (other.ranges != null) + return false; + } else if (!ranges.equals(other.ranges)) + return false; + return true; + } + + @Override + public String toString() { + return "[matrixParameters=" + matrixParameters + ", formParameters=" + formParameters + ", queryParameters=" + + queryParameters + ", headers=" + headers + ", payload=" + payload + ", pathSuffix=" + pathSuffix + + ", ranges=" + ranges + "]"; + } + } diff --git a/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java b/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java new file mode 100644 index 0000000000..7dc20bccc0 --- /dev/null +++ b/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java @@ -0,0 +1,194 @@ +/** + * + * 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, + * WIRHOUR WARRANRIES OR CONDIRIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.http.utils; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Sets.newTreeSet; +import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; + +import java.net.URI; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.SortedSet; + +import javax.annotation.Nullable; +import javax.ws.rs.core.UriBuilder; + +import org.jclouds.http.HttpRequest; +import org.jclouds.util.Strings2; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.Multimap; + +/** + * + * @author Adrian Cole + */ +public class ModifyRequest { + @SuppressWarnings("unchecked") + public static R putHeaders(R request, Multimap moreHeaders) { + return (R) request + .toBuilder() + .headers( + ImmutableMultimap. builder().putAll(request.getHeaders()).putAll(moreHeaders).build()) + .build(); + } + + @SuppressWarnings("unchecked") + public static R endpoint(R request, URI endpoint) { + return (R) checkNotNull(request, "request").toBuilder().endpoint(checkNotNull(endpoint, "endpoint")).build(); + } + + @SuppressWarnings("unchecked") + public static R replaceHeaders(R request, Multimap headers) { + Multimap newHeaders = LinkedHashMultimap.create(checkNotNull(request, "request").getHeaders()); + for (String header : headers.keySet()) + newHeaders.replaceValues(header, headers.get(header)); + return (R) request.toBuilder().headers(newHeaders).build(); + } + + public static R replaceHeader(R request, String header, String... values) { + return replaceHeader(request, header, ImmutableList.copyOf(checkNotNull(values, "values"))); + } + + @SuppressWarnings("unchecked") + public static R replaceHeader(R request, String header, Iterable values) { + Multimap headers = LinkedHashMultimap.create(checkNotNull(request, "request").getHeaders()); + headers.replaceValues(checkNotNull(header, "header"), checkNotNull(values, "values")); + return (R) request.toBuilder().headers(headers).build(); + } + + @SuppressWarnings("unchecked") + public static R removeHeader(R request, String header) { + Multimap headers = LinkedHashMultimap.create(checkNotNull(request, "request").getHeaders()); + headers.removeAll(checkNotNull(header, "header")); + return (R) request.toBuilder().headers(headers).build(); + } + + public static R addQueryParam(R request, String key, Object value, UriBuilder builder) { + return addQueryParam(request, key, ImmutableSet. of(value), builder, request.getSkips()); + } + + public static R addQueryParam(R request, String key, Iterable values, UriBuilder builder) { + return addQueryParam(request, key, values, builder, request.getSkips()); + } + + @SuppressWarnings("unchecked") + public static R addQueryParam(R request, String key, Iterable values, UriBuilder builder, + char... skips) { + builder.uri(request.getEndpoint()); + Multimap map = parseQueryToMap(request.getEndpoint().getQuery()); + for (Object o : values) + map.put(key, o.toString()); + builder.replaceQuery(makeQueryLine(map, null, skips)); + return (R) request.toBuilder().endpoint(builder.build()).build(); + } + + public static R replaceMatrixParam(R request, String name, Object value, UriBuilder builder) { + return replaceMatrixParam(request, name, new Object[] { value }, builder); + } + + @SuppressWarnings("unchecked") + public static R replaceMatrixParam(R request, String name, Object[] values, + UriBuilder builder) { + builder.uri(request.getEndpoint()); + builder.replaceMatrixParam(name, values); + return (R) request.toBuilder().endpoint(builder.build()).build(); + } + + public static R addFormParam(R request, String key, String value) { + return addFormParam(request, key, ImmutableSet. of(value)); + } + + @SuppressWarnings("unchecked") + public static R addFormParam(R request, String key, Iterable values) { + Multimap map = request.getPayload() != null ? parseQueryToMap(request.getPayload() + .getRawContent().toString()) : LinkedHashMultimap. create(); + for (Object o : values) + map.put(key, o.toString()); + return (R) request.toBuilder().payload(newUrlEncodedFormPayload(map)).build(); + } + + @SuppressWarnings("unchecked") + public static R putFormParams(R request, Multimap params) { + Multimap map = request.getPayload() != null ? parseQueryToMap(request.getPayload() + .getRawContent().toString()) : LinkedHashMultimap. create(); + map.putAll(params); + return (R) request.toBuilder().payload(newUrlEncodedFormPayload(map)).build(); + } + + public static Multimap parseQueryToMap(String in) { + Multimap map = LinkedListMultimap.create(); + if (in == null) { + } else if (in.indexOf('&') == -1) { + if (in.contains("=")) + parseKeyValueFromStringToMap(in, map); + else + map.put(in, null); + } else { + String[] parts = Strings2.urlDecode(in).split("&"); + for (String part : parts) { + parseKeyValueFromStringToMap(part, map); + } + } + return 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); + map.put(key, value); + } + + public static String makeQueryLine(Multimap params, + @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(); + formBuilder.append(Strings2.urlEncode(pair.getKey(), skips)); + if (pair.getValue() != null && !pair.getValue().equals("")) { + formBuilder.append("="); + formBuilder.append(Strings2.urlEncode(pair.getValue(), skips)); + } + if (pairs.hasNext()) + formBuilder.append("&"); + } + return formBuilder.toString(); + } + + public static SortedSet> sortEntries(Collection> in, + Comparator> sorter) { + SortedSet> entries = newTreeSet(sorter); + entries.addAll(in); + return entries; + } + +} diff --git a/core/src/main/java/org/jclouds/io/ContentMetadata.java b/core/src/main/java/org/jclouds/io/ContentMetadata.java index 0db85f6b11..a73168564c 100644 --- a/core/src/main/java/org/jclouds/io/ContentMetadata.java +++ b/core/src/main/java/org/jclouds/io/ContentMetadata.java @@ -19,12 +19,21 @@ package org.jclouds.io; +import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH; +import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; + +import java.util.Set; + import javax.annotation.Nullable; +import com.google.common.collect.ImmutableSet; + /** * @author Adrian Cole */ public interface ContentMetadata { + public static final Set HTTP_HEADERS = ImmutableSet.of(CONTENT_LENGTH, "Content-MD5", CONTENT_TYPE, + "Content-Disposition", "Content-Encoding", "Content-Language"); /** * Returns the total size of the payload, or the chunk that's available. diff --git a/core/src/main/java/org/jclouds/io/MutableContentMetadata.java b/core/src/main/java/org/jclouds/io/MutableContentMetadata.java index 60ff465e2f..eff4259b4e 100644 --- a/core/src/main/java/org/jclouds/io/MutableContentMetadata.java +++ b/core/src/main/java/org/jclouds/io/MutableContentMetadata.java @@ -21,10 +21,18 @@ package org.jclouds.io; import javax.annotation.Nullable; +import com.google.common.collect.Multimap; + /** * @author Adrian Cole */ public interface MutableContentMetadata extends ContentMetadata { + /** + * sets properties related to the http headers listed in + * {@link ContentMetadata#HTTP_HEADERS} + * + */ + void setPropertiesFromHttpHeaders(Multimap headers); void setContentLength(@Nullable Long contentLength); diff --git a/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java b/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java index daeefec692..57f0ba7a08 100644 --- a/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java +++ b/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java @@ -19,21 +19,54 @@ package org.jclouds.io.payloads; +import static com.google.common.collect.Iterables.any; +import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH; +import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; + import java.io.Serializable; import java.util.Arrays; +import java.util.Map.Entry; import javax.annotation.Nullable; +import org.jclouds.crypto.CryptoStreams; import org.jclouds.io.MutableContentMetadata; +import com.google.common.base.Predicate; +import com.google.common.collect.Multimap; + /** * @author Adrian Cole */ public class BaseMutableContentMetadata implements MutableContentMetadata, Serializable { + @Override + public void setPropertiesFromHttpHeaders(Multimap headers) { + boolean chunked = any(headers.entries(), new Predicate>() { + @Override + public boolean apply(Entry input) { + return "Transfer-Encoding".equalsIgnoreCase(input.getKey()) && "chunked".equalsIgnoreCase(input.getValue()); + } + }); + for (Entry header : headers.entries()) { + if (!chunked && CONTENT_LENGTH.equalsIgnoreCase(header.getKey())) { + setContentLength(new Long(header.getValue())); + } else if ("Content-MD5".equalsIgnoreCase(header.getKey())) { + setContentMD5(CryptoStreams.base64(header.getValue())); + } else if (CONTENT_TYPE.equalsIgnoreCase(header.getKey())) { + setContentType(header.getValue()); + } else if ("Content-Disposition".equalsIgnoreCase(header.getKey())) { + setContentDisposition(header.getValue()); + } else if ("Content-Encoding".equalsIgnoreCase(header.getKey())) { + setContentEncoding(header.getValue()); + } else if ("Content-Language".equalsIgnoreCase(header.getKey())) { + setContentLanguage(header.getValue()); + } + } + } /** The serialVersionUID */ private static final long serialVersionUID = 4572381435863125873L; - + protected String contentType = "application/unknown"; protected Long contentLength; protected byte[] contentMD5; @@ -154,8 +187,8 @@ public class BaseMutableContentMetadata implements MutableContentMetadata, Seria @Override public String toString() { return "[contentType=" + contentType + ", contentLength=" + contentLength + ", contentDisposition=" - + contentDisposition + ", contentEncoding=" + contentEncoding + ", contentLanguage=" + contentLanguage - + ", contentMD5=" + Arrays.toString(contentMD5) + "]"; + + contentDisposition + ", contentEncoding=" + contentEncoding + ", contentLanguage=" + contentLanguage + + ", contentMD5=" + Arrays.toString(contentMD5) + "]"; } @Override diff --git a/core/src/main/java/org/jclouds/io/payloads/UrlEncodedFormPayload.java b/core/src/main/java/org/jclouds/io/payloads/UrlEncodedFormPayload.java index 45373e4b00..9bf28182f7 100644 --- a/core/src/main/java/org/jclouds/io/payloads/UrlEncodedFormPayload.java +++ b/core/src/main/java/org/jclouds/io/payloads/UrlEncodedFormPayload.java @@ -19,8 +19,6 @@ package org.jclouds.io.payloads; -import static org.jclouds.http.HttpUtils.makeQueryLine; - import java.io.InputStream; import java.util.Comparator; import java.util.Map; @@ -28,7 +26,8 @@ import java.util.Map; import javax.annotation.Nullable; import javax.ws.rs.core.MediaType; -import org.jclouds.util.Utils; +import org.jclouds.http.utils.ModifyRequest; +import org.jclouds.util.Strings2; import com.google.common.collect.Multimap; @@ -42,7 +41,7 @@ public class UrlEncodedFormPayload extends BasePayload { public UrlEncodedFormPayload(Multimap formParams, @Nullable Comparator> sorter, char... skips) { - super(makeQueryLine(formParams, sorter, skips)); + super(ModifyRequest.makeQueryLine(formParams, sorter, skips)); getContentMetadata().setContentLength((long) content.length()); getContentMetadata().setContentType(MediaType.APPLICATION_FORM_URLENCODED); } @@ -52,7 +51,7 @@ public class UrlEncodedFormPayload extends BasePayload { */ @Override public InputStream getInput() { - return Utils.toInputStream(content); + return Strings2.toInputStream(content); } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/rest/Binder.java b/core/src/main/java/org/jclouds/rest/Binder.java index dcb92747f5..2ea6ac3647 100755 --- a/core/src/main/java/org/jclouds/rest/Binder.java +++ b/core/src/main/java/org/jclouds/rest/Binder.java @@ -27,5 +27,5 @@ import org.jclouds.http.HttpRequest; * @author Adrian Cole */ public interface Binder { - public void bindToRequest(HttpRequest request, Object input); + R bindToRequest(R request, Object input); } diff --git a/core/src/main/java/org/jclouds/rest/HttpAsyncClient.java b/core/src/main/java/org/jclouds/rest/HttpAsyncClient.java index 4a2ee109b2..c1424fd6ce 100644 --- a/core/src/main/java/org/jclouds/rest/HttpAsyncClient.java +++ b/core/src/main/java/org/jclouds/rest/HttpAsyncClient.java @@ -27,11 +27,10 @@ import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.POST; import javax.ws.rs.PUT; -import javax.ws.rs.Path; import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ParseETagHeader; -import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.io.Payload; import org.jclouds.rest.annotations.EndpointParam; import org.jclouds.rest.annotations.ExceptionParser; @@ -51,33 +50,20 @@ public interface HttpAsyncClient { * @see HttpClient#post */ @PUT - @Path("") @ResponseParser(ParseETagHeader.class) ListenableFuture put(@EndpointParam URI location, Payload payload); - @PUT - @Path("") - @ResponseParser(ParseETagHeader.class) - ListenableFuture put(@EndpointParam URI location, Payload payload, HttpRequestOptions options); - /** * @see HttpClient#post */ @POST - @Path("") @ResponseParser(ParseETagHeader.class) ListenableFuture post(@EndpointParam URI location, Payload payload); - @POST - @Path("") - @ResponseParser(ParseETagHeader.class) - ListenableFuture post(@EndpointParam URI location, Payload payload, HttpRequestOptions options); - /** * @see HttpClient#exists */ @HEAD - @Path("") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) ListenableFuture exists(@EndpointParam URI location); @@ -85,27 +71,18 @@ public interface HttpAsyncClient { * @see HttpClient#get */ @GET - @Path("") @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture get(@EndpointParam URI location); /** - * @see HttpClient#get + * @see HttpClient#invoke */ - @Path("") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture invoke(HttpRequest location); - - @GET - @Path("") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture get(@EndpointParam URI location, HttpRequestOptions options); + ListenableFuture invoke(HttpRequest request); /** * @see HttpClient#delete */ @DELETE - @Path("") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) ListenableFuture delete(@EndpointParam URI location); diff --git a/core/src/main/java/org/jclouds/rest/HttpClient.java b/core/src/main/java/org/jclouds/rest/HttpClient.java index 087929a443..d73360640e 100644 --- a/core/src/main/java/org/jclouds/rest/HttpClient.java +++ b/core/src/main/java/org/jclouds/rest/HttpClient.java @@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; import org.jclouds.http.HttpRequest; -import org.jclouds.http.options.HttpRequestOptions; +import org.jclouds.http.HttpResponse; import org.jclouds.io.Payload; /** @@ -35,37 +35,29 @@ import org.jclouds.io.Payload; */ @Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) public interface HttpClient { + /** + * + * @param request + * @return response, but make sure you consume its content. + */ + HttpResponse invoke(HttpRequest request); /** * @return eTag */ String put(URI location, Payload payload); - /** - * @return eTag - */ - String put(URI location, Payload payload, HttpRequestOptions options); - /** * @return eTag */ String post(URI location, Payload payload); - /** - * @return eTag - */ - String post(URI location, Payload payload, HttpRequestOptions options); - boolean exists(URI location); /** * @return null if the resource didn't exist. */ InputStream get(URI location); - - InputStream invoke(HttpRequest location); - - InputStream get(URI location, HttpRequestOptions options); /** * @return false if the resource didn't exist. diff --git a/core/src/main/java/org/jclouds/rest/InputParamValidator.java b/core/src/main/java/org/jclouds/rest/InputParamValidator.java index 1e63f8bdc4..6b2159e267 100644 --- a/core/src/main/java/org/jclouds/rest/InputParamValidator.java +++ b/core/src/main/java/org/jclouds/rest/InputParamValidator.java @@ -132,7 +132,7 @@ public class InputParamValidator { @SuppressWarnings("unchecked") private void runPredicatesAgainstArgs(List> predicates, Object... args) { - for (Validator validator : predicates) { + for (@SuppressWarnings("rawtypes") Validator validator : predicates) { Iterables.all(Arrays.asList(args), validator); } } diff --git a/core/src/main/java/org/jclouds/rest/InvocationContext.java b/core/src/main/java/org/jclouds/rest/InvocationContext.java index 156ab4f147..0b5dcc356e 100644 --- a/core/src/main/java/org/jclouds/rest/InvocationContext.java +++ b/core/src/main/java/org/jclouds/rest/InvocationContext.java @@ -29,6 +29,6 @@ import org.jclouds.http.HttpRequest; * @see PathParam * @author Adrian Cole */ -public interface InvocationContext { - Object setContext(HttpRequest request); +public interface InvocationContext> { + I setContext(HttpRequest request); } diff --git a/core/src/main/java/org/jclouds/rest/MapBinder.java b/core/src/main/java/org/jclouds/rest/MapBinder.java index b776fdbf5b..ee9a507ff2 100644 --- a/core/src/main/java/org/jclouds/rest/MapBinder.java +++ b/core/src/main/java/org/jclouds/rest/MapBinder.java @@ -36,6 +36,5 @@ public interface MapBinder extends Binder { * * @see org.jclouds.rest.annotations.MapPayloadParam */ - public void bindToRequest(HttpRequest request, Map postParams); - + R bindToRequest(R request, Map postParams); } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/rest/Providers.java b/core/src/main/java/org/jclouds/rest/Providers.java new file mode 100644 index 0000000000..4d5f232b60 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/Providers.java @@ -0,0 +1,152 @@ +/** + * + * 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.rest; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Predicates.notNull; +import static com.google.common.base.Throwables.propagate; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.get; +import static com.google.common.collect.Iterables.transform; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +import javax.annotation.Nullable; + +import org.jclouds.PropertiesBuilder; +import org.jclouds.util.SaxUtils; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Splitter; + +/** + * + * @author Adrian Cole + */ +public class Providers { + + /** + * Gets a set of supported providers. Idea stolen from pallets (supported-clouds). Uses + * rest.properties to populate the set. + * + */ + public static Iterable getSupportedProviders() { + return Providers.getSupportedProvidersOfType(RestContextBuilder.class); + } + + /** + * Gets a set of supported providers. Idea stolen from pallets (supported-clouds). Uses + * rest.properties to populate the set. + * + */ + public static Iterable getSupportedProvidersOfType( + @SuppressWarnings("rawtypes") Class type) { + Properties properties = new Properties(); + try { + properties.load(SaxUtils.class.getResourceAsStream("/rest.properties")); + } catch (IOException e) { + throw new RuntimeException(e); + } + return Providers.getSupportedProvidersOfTypeInProperties(type, properties); + } + + public static Iterable getSupportedProvidersOfTypeInProperties( + @SuppressWarnings("rawtypes") final Class type, final Properties properties) { + return filter(transform(filter(properties.entrySet(), new Predicate>() { + + @Override + public boolean apply(Entry input) { + String keyString = input.getKey().toString(); + return keyString.endsWith(".contextbuilder") || keyString.endsWith(".sync"); + } + + }), new Function, String>() { + + @Override + public String apply(Entry from) { + String keyString = from.getKey().toString(); + try { + String provider = get(Splitter.on('.').split(keyString), 0); + Class> clazz = Providers.resolveContextBuilderClass(provider, + properties); + if (type.isAssignableFrom(clazz)) + return provider; + } catch (ClassNotFoundException e) { + } catch (Exception e) { + propagate(e); + } + return null; + } + + }), notNull()); + } + + @SuppressWarnings("unchecked") + public static Class> resolveContextBuilderClass(String provider, + Properties properties) throws ClassNotFoundException, IllegalArgumentException, SecurityException, + InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + String contextBuilderClassName = properties.getProperty(provider + ".contextbuilder"); + String syncClassName = properties.getProperty(provider + ".sync"); + String asyncClassName = properties.getProperty(provider + ".async"); + if (syncClassName != null) { + checkArgument(asyncClassName != null, "please configure async class for " + syncClassName); + Class.forName(syncClassName); + Class.forName(asyncClassName); + return (Class>) (contextBuilderClassName != null ? Class + .forName(contextBuilderClassName) : RestContextBuilder.class); + } else { + checkArgument(contextBuilderClassName != null, "please configure contextbuilder class for " + provider); + return (Class>) Class.forName(contextBuilderClassName); + } + } + + public static RestContextBuilder initContextBuilder( + Class> contextBuilderClass, @Nullable Class sync, @Nullable Class async, + Properties properties) throws ClassNotFoundException, IllegalArgumentException, SecurityException, + InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + checkArgument(properties != null, "please configure properties for " + contextBuilderClass); + try { + return (RestContextBuilder) contextBuilderClass.getConstructor(Properties.class).newInstance(properties); + } catch (NoSuchMethodException e) { + checkArgument(sync != null, "please configure sync class for " + contextBuilderClass); + checkArgument(async != null, "please configure async class for " + contextBuilderClass); + return (RestContextBuilder) contextBuilderClass.getConstructor(sync.getClass(), async.getClass(), + Properties.class).newInstance(sync, async, properties); + } + } + + @SuppressWarnings("unchecked") + public static Class resolvePropertiesBuilderClass(String providerName, Properties props) + throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, + NoSuchMethodException { + String propertiesBuilderClassName = props.getProperty(providerName + ".propertiesbuilder", null); + if (propertiesBuilderClassName != null) { + return (Class) Class.forName(propertiesBuilderClassName); + } else { + return PropertiesBuilder.class; + } + } + +} diff --git a/core/src/main/java/org/jclouds/rest/RestContextBuilder.java b/core/src/main/java/org/jclouds/rest/RestContextBuilder.java index 5a5aa2621f..66a12f5ba9 100755 --- a/core/src/main/java/org/jclouds/rest/RestContextBuilder.java +++ b/core/src/main/java/org/jclouds/rest/RestContextBuilder.java @@ -177,7 +177,7 @@ public class RestContextBuilder { protected void addContextModule(List modules) { modules.add(new AbstractModule() { - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void configure() { bind( @@ -188,6 +188,11 @@ public class RestContextBuilder { } + public String toString() { + return String.format("configure rest context %s->%s", syncClientType.getSimpleName(), + asyncClientType.getSimpleName()); + } + }); } diff --git a/core/src/main/java/org/jclouds/rest/RestContextFactory.java b/core/src/main/java/org/jclouds/rest/RestContextFactory.java index 37aca2af06..727bea5e67 100644 --- a/core/src/main/java/org/jclouds/rest/RestContextFactory.java +++ b/core/src/main/java/org/jclouds/rest/RestContextFactory.java @@ -25,12 +25,7 @@ import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.size; import static com.google.common.collect.Iterables.transform; import static java.util.Collections.EMPTY_LIST; -import static org.jclouds.util.Utils.initContextBuilder; -import static org.jclouds.util.Utils.modulesForProviderInProperties; -import static org.jclouds.util.Utils.propagateAuthorizationOrOriginalException; -import static org.jclouds.util.Utils.resolveContextBuilderClass; -import static org.jclouds.util.Utils.resolvePropertiesBuilderClass; -import static org.jclouds.util.Utils.toStringAndClose; +import static org.jclouds.util.Throwables2.propagateAuthorizationOrOriginalException; import java.io.File; import java.io.IOException; @@ -40,6 +35,8 @@ import javax.annotation.Nullable; import javax.inject.Inject; import org.jclouds.PropertiesBuilder; +import org.jclouds.util.Modules2; +import org.jclouds.util.Strings2; import com.google.common.base.Charsets; import com.google.common.base.Function; @@ -85,7 +82,7 @@ public class RestContextFactory { return new RestContextSpec(provider, endpoint, apiVersion, identity, credential, sync, async); } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public static RestContextSpec contextSpec(String provider, String endpoint, String apiVersion, String identity, String credential, Class sync, Class async, Iterable modules) { return new RestContextSpec(provider, endpoint, apiVersion, identity, credential, sync, async, @@ -293,15 +290,15 @@ public class RestContextFactory { loadCredentialOrDefault(props, "jclouds.credential", credential)); String syncClassName = props.getProperty(providerName + ".sync", null); String asyncClassName = props.getProperty(providerName + ".async", null); - Iterable modules = concat(modulesForProviderInProperties(providerName, props), wiring); + Iterable modules = concat(Modules2.modulesForProviderInProperties(providerName, props), wiring); Class> contextBuilderClass; Class propertiesBuilderClass; Class sync; Class async; try { - contextBuilderClass = resolveContextBuilderClass(providerName, props); - propertiesBuilderClass = resolvePropertiesBuilderClass(providerName, props); + contextBuilderClass = Providers.resolveContextBuilderClass(providerName, props); + propertiesBuilderClass = Providers.resolvePropertiesBuilderClass(providerName, props); sync = (Class) (syncClassName != null ? Class.forName(syncClassName) : null); async = (Class) (syncClassName != null ? Class.forName(asyncClassName) : null); } catch (Exception e) { @@ -319,7 +316,7 @@ public class RestContextFactory { return properties.getProperty(property); else if (properties.containsKey(property + ".resource")) try { - return toStringAndClose(RestContextFactory.class.getResourceAsStream(properties.getProperty(property + return Strings2.toStringAndClose(RestContextFactory.class.getResourceAsStream(properties.getProperty(property + ".resource"))); } catch (IOException e) { throw new RuntimeException("error reading resource: " + properties.getProperty(property + ".resource")); @@ -363,7 +360,7 @@ public class RestContextFactory { if (contextSpec.endpoint != null) builder.endpoint(contextSpec.endpoint); - RestContextBuilder contextBuilder = initContextBuilder(contextSpec.contextBuilderClass, + RestContextBuilder contextBuilder = Providers.initContextBuilder(contextSpec.contextBuilderClass, contextSpec.sync, contextSpec.async, builder.build()); contextBuilder.withModules(concat(modules, contextSpec.modules)); diff --git a/core/src/main/java/org/jclouds/rest/RestContextSpec.java b/core/src/main/java/org/jclouds/rest/RestContextSpec.java index 8d4f42b37b..9304443e8a 100644 --- a/core/src/main/java/org/jclouds/rest/RestContextSpec.java +++ b/core/src/main/java/org/jclouds/rest/RestContextSpec.java @@ -63,7 +63,7 @@ public class RestContextSpec { this.modules = ImmutableList.copyOf(modules); } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public RestContextSpec(String provider, String endpoint, String apiVersion, String identity, String credential, Class sync, Class async) { this(provider, endpoint, apiVersion, identity, credential, sync, async, PropertiesBuilder.class, diff --git a/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java b/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java index 4e25e9793a..ed3d80c1a8 100644 --- a/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java @@ -47,14 +47,14 @@ public class BindAsHostPrefix implements Binder { this.uriBuilderProvider = uriBuilderProvider; } - public void bindToRequest(HttpRequest request, Object payload) { + @Override + @SuppressWarnings("unchecked") + public R bindToRequest(R request, Object payload) { checkNotNull(payload, "hostprefix"); - checkArgument(isValid(request.getEndpoint().getHost()), "this is only valid for hostnames: " - + request); + checkArgument(isValid(request.getEndpoint().getHost()), "this is only valid for hostnames: " + request); UriBuilder builder = uriBuilderProvider.get().uri(request.getEndpoint()); - InternetDomainName name = InternetDomainName.from(request.getEndpoint().getHost()).child( - payload.toString()); + InternetDomainName name = InternetDomainName.from(request.getEndpoint().getHost()).child(payload.toString()); builder.host(name.name()); - request.setEndpoint(builder.build()); + return (R) request.toBuilder().endpoint(builder.build()).build(); } } diff --git a/core/src/main/java/org/jclouds/rest/binders/BindMapToMatrixParams.java b/core/src/main/java/org/jclouds/rest/binders/BindMapToMatrixParams.java index d74a879b8d..0e80142044 100644 --- a/core/src/main/java/org/jclouds/rest/binders/BindMapToMatrixParams.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindMapToMatrixParams.java @@ -21,7 +21,6 @@ package org.jclouds.rest.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.http.HttpUtils.replaceMatrixParam; import java.util.Map; import java.util.Map.Entry; @@ -31,6 +30,7 @@ import javax.inject.Provider; import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; /** @@ -46,14 +46,15 @@ public class BindMapToMatrixParams implements Binder { this.builder = builder; } - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Object input) { + @SuppressWarnings("unchecked") @Override + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Maps!"); Map map = (Map) input; for (Entry entry : map.entrySet()) { - replaceMatrixParam(request, entry.getKey(), entry.getValue(), builder.get()); + request = ModifyRequest.replaceMatrixParam(request, entry.getKey(), entry.getValue(), builder.get()); } + return request; } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/rest/binders/BindToJsonPayload.java b/core/src/main/java/org/jclouds/rest/binders/BindToJsonPayload.java index 855630c3d4..0da9af87bc 100644 --- a/core/src/main/java/org/jclouds/rest/binders/BindToJsonPayload.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindToJsonPayload.java @@ -41,15 +41,18 @@ public class BindToJsonPayload implements MapBinder { @Inject protected Json jsonBinder; - public void bindToRequest(HttpRequest request, Map postParams) { - bindToRequest(request, (Object) postParams); + @Override + public R bindToRequest(R request, Map postParams) { + return bindToRequest(request, (Object) postParams); } - public void bindToRequest(HttpRequest request, Object toBind) { + @Override + public R bindToRequest(R request, Object payload) { checkState(jsonBinder != null, "Program error: json should have been injected at this point"); - String json = jsonBinder.toJson(toBind); + String json = jsonBinder.toJson(payload); request.setPayload(json); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); + return request; } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/rest/binders/BindToStringPayload.java b/core/src/main/java/org/jclouds/rest/binders/BindToStringPayload.java index c769a63fe7..e1190a055c 100755 --- a/core/src/main/java/org/jclouds/rest/binders/BindToStringPayload.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindToStringPayload.java @@ -31,7 +31,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindToStringPayload implements Binder { - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { request.setPayload(payload.toString()); + return request; } } diff --git a/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java b/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java index 2d8438002b..2bb2b1b9a6 100644 --- a/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java +++ b/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java @@ -20,8 +20,6 @@ package org.jclouds.rest.config; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.toInputStream; -import static org.jclouds.util.Utils.toStringAndClose; import java.io.IOException; import java.io.InputStream; @@ -38,6 +36,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.json.Json; import org.jclouds.logging.Logger; import org.jclouds.rest.ConfiguresCredentialStore; +import org.jclouds.util.Strings2; import com.google.common.annotations.Beta; import com.google.common.base.Function; @@ -95,7 +94,7 @@ public class CredentialStoreModule extends AbstractModule { @Override public InputStream apply(Credentials from) { - return toInputStream(json.toJson(checkNotNull(from))); + return Strings2.toInputStream(json.toJson(checkNotNull(from))); } } @@ -161,7 +160,7 @@ public class CredentialStoreModule extends AbstractModule { @Override public Credentials apply(InputStream from) { try { - PrivateCredentials credentials = json.fromJson(toStringAndClose(checkNotNull(from)), + PrivateCredentials credentials = json.fromJson(Strings2.toStringAndClose(checkNotNull(from)), PrivateCredentials.class); return new Credentials(credentials.identity, credentials.credential); } catch (Exception e) { diff --git a/core/src/main/java/org/jclouds/rest/config/RestClientModule.java b/core/src/main/java/org/jclouds/rest/config/RestClientModule.java index 0d5d85012f..f50354e399 100644 --- a/core/src/main/java/org/jclouds/rest/config/RestClientModule.java +++ b/core/src/main/java/org/jclouds/rest/config/RestClientModule.java @@ -63,7 +63,7 @@ public class RestClientModule extends AbstractModule { ., Class> of(syncClientType, asyncClientType)); } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void configure() { // Ensures the restcontext can be looked up without generic types. diff --git a/core/src/main/java/org/jclouds/rest/config/RestModule.java b/core/src/main/java/org/jclouds/rest/config/RestModule.java index 4adbe8aac1..142509db48 100755 --- a/core/src/main/java/org/jclouds/rest/config/RestModule.java +++ b/core/src/main/java/org/jclouds/rest/config/RestModule.java @@ -25,6 +25,7 @@ import javax.inject.Named; import javax.inject.Singleton; import javax.ws.rs.core.UriBuilder; +import org.jclouds.functions.IdentityFunction; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.http.TransformingHttpCommand; @@ -63,11 +64,12 @@ public class RestModule extends AbstractModule { protected void configure() { install(new SaxParserModule()); install(new GsonModule()); + bind(IdentityFunction.class).toInstance(IdentityFunction.INSTANCE); bind(UriBuilder.class).to(UriBuilderImpl.class); bind(AsyncRestClientProxy.Factory.class).to(Factory.class).in(Scopes.SINGLETON); BinderUtils.bindAsyncClient(binder(), HttpAsyncClient.class); - BinderUtils.bindClient(binder(), HttpClient.class, HttpAsyncClient.class, ImmutableMap., Class> of( - HttpClient.class, HttpAsyncClient.class)); + BinderUtils.bindClient(binder(), HttpClient.class, HttpAsyncClient.class, + ImmutableMap., Class> of(HttpClient.class, HttpAsyncClient.class)); } @Provides @@ -87,7 +89,7 @@ public class RestModule extends AbstractModule { this.factory = factory; } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Object apply(final ClassMethodArgs from) { Class clazz = from.getAsyncClass(); @@ -110,8 +112,10 @@ public class RestModule extends AbstractModule { @Inject private TransformingHttpCommandExecutorService executorService; - @SuppressWarnings("unchecked") - public TransformingHttpCommand create(HttpRequest request, Function transformer) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public TransformingHttpCommand create(HttpRequest request, + Function transformer) { return new TransformingHttpCommandImpl(executorService, request, transformer); } diff --git a/core/src/main/java/org/jclouds/rest/functions/MapHttp4xxCodesToExceptions.java b/core/src/main/java/org/jclouds/rest/functions/MapHttp4xxCodesToExceptions.java index 2bd9f4d93a..5d98ce6676 100644 --- a/core/src/main/java/org/jclouds/rest/functions/MapHttp4xxCodesToExceptions.java +++ b/core/src/main/java/org/jclouds/rest/functions/MapHttp4xxCodesToExceptions.java @@ -19,7 +19,7 @@ package org.jclouds.rest.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java index a1e719ed80..f055287450 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java @@ -20,7 +20,7 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.util.List; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java index ad6730e961..bdb50a7a6e 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java @@ -20,7 +20,7 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.util.Map; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java index 0dd92533a2..c819c56a00 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java @@ -20,7 +20,7 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Inject; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java index 6936f5f5df..2250f07ff4 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java @@ -20,7 +20,7 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.util.Set; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnNullOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnNullOnNotFoundOr404.java index ef15b5ce19..31cc40f4ef 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnNullOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnNullOnNotFoundOr404.java @@ -20,7 +20,7 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Inject; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnVoidOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnVoidOnNotFoundOr404.java index 2f26beabf2..1fc0d95a53 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnVoidOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnVoidOnNotFoundOr404.java @@ -20,7 +20,7 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Inject; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java b/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java index 29ad5224a7..419f16f284 100755 --- a/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java +++ b/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java @@ -43,7 +43,7 @@ import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.InvocationContext; import org.jclouds.rest.annotations.Delegate; -import org.jclouds.util.Utils; +import org.jclouds.util.Throwables2; import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; @@ -73,7 +73,7 @@ public class AsyncRestClientProxy implements InvocationHandler { @SuppressWarnings("unchecked") @Inject public AsyncRestClientProxy(Injector injector, Factory factory, RestAnnotationProcessor util, - TypeLiteral typeLiteral, @Named("async") ConcurrentMap delegateMap) { + TypeLiteral typeLiteral, @Named("async") ConcurrentMap delegateMap) { this.injector = injector; this.annotationProcessor = util; this.declaring = (Class) typeLiteral.getRawType(); @@ -93,57 +93,56 @@ public class AsyncRestClientProxy implements InvocationHandler { } else if (method.isAnnotationPresent(Delegate.class)) { return delegateMap.get(new ClassMethodArgs(method.getReturnType(), method, args)); } else if (annotationProcessor.getDelegateOrNull(method) != null - && ListenableFuture.class.isAssignableFrom(method.getReturnType())) { + && ListenableFuture.class.isAssignableFrom(method.getReturnType())) { return createListenableFuture(method, args); } else { throw new RuntimeException("method is intended solely to set constants: " + method); } } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) private ListenableFuture createListenableFuture(Method method, Object[] args) throws ExecutionException { method = annotationProcessor.getDelegateOrNull(method); logger.trace("Converting %s.%s", declaring.getSimpleName(), method.getName()); Function exceptionParser = annotationProcessor - .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(method); + .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(method); // in case there is an exception creating the request, we should at least // pass in args if (exceptionParser instanceof InvocationContext) { - ((InvocationContext) exceptionParser).setContext(null); + ((InvocationContext) exceptionParser).setContext((HttpRequest) null); } - HttpRequest request = RestAnnotationProcessor.findHttpRequestInArgs(args); - if (request == null) { - try { - request = annotationProcessor.createRequest(method, args); - if (exceptionParser instanceof InvocationContext && request instanceof GeneratedHttpRequest) { - ((InvocationContext) exceptionParser).setContext((GeneratedHttpRequest) request); - } - } catch (RuntimeException e) { - AuthorizationException aex = Utils.getFirstThrowableOfType(e, AuthorizationException.class); - if (aex != null) - e = aex; - if (exceptionParser != null) { - try { - return Futures.immediateFuture(exceptionParser.apply(e)); - } catch (Exception ex) { - return Futures.immediateFailedFuture(ex); - } - } - return Futures.immediateFailedFuture(e); + ListenableFuture result; + try { + GeneratedHttpRequest request = annotationProcessor.createRequest(method, args); + if (exceptionParser instanceof InvocationContext) { + ((InvocationContext) exceptionParser).setContext(request); } - } - logger.trace("Converted %s.%s to %s", declaring.getSimpleName(), method.getName(), request.getRequestLine()); + logger.trace("Converted %s.%s to %s", declaring.getSimpleName(), method.getName(), request.getRequestLine()); - Function transformer = annotationProcessor.createResponseParser(method, request); - logger.trace("Response from %s.%s is parsed by %s", declaring.getSimpleName(), method.getName(), transformer + Function transformer = annotationProcessor.createResponseParser(method, request); + logger.trace("Response from %s.%s is parsed by %s", declaring.getSimpleName(), method.getName(), transformer .getClass().getSimpleName()); - logger.debug("Invoking %s.%s", declaring.getSimpleName(), method.getName()); - ListenableFuture result = commandFactory.create(request, transformer).execute(); + logger.debug("Invoking %s.%s", declaring.getSimpleName(), method.getName()); + result = commandFactory.create(request, transformer).execute(); + + } catch (RuntimeException e) { + AuthorizationException aex = Throwables2.getFirstThrowableOfType(e, AuthorizationException.class); + if (aex != null) + e = aex; + if (exceptionParser != null) { + try { + return Futures.immediateFuture(exceptionParser.apply(e)); + } catch (Exception ex) { + return Futures.immediateFailedFuture(ex); + } + } + return Futures.immediateFailedFuture(e); + } if (exceptionParser != null) { logger.trace("Exceptions from %s.%s are parsed by %s", declaring.getSimpleName(), method.getName(), - exceptionParser.getClass().getSimpleName()); + exceptionParser.getClass().getSimpleName()); result = new ExceptionParsingListenableFuture(result, exceptionParser); } return result; diff --git a/core/src/main/java/org/jclouds/rest/internal/GeneratedHttpRequest.java b/core/src/main/java/org/jclouds/rest/internal/GeneratedHttpRequest.java index 57f123fa60..f475979d9a 100644 --- a/core/src/main/java/org/jclouds/rest/internal/GeneratedHttpRequest.java +++ b/core/src/main/java/org/jclouds/rest/internal/GeneratedHttpRequest.java @@ -19,10 +19,21 @@ package org.jclouds.rest.internal; +import static com.google.common.base.Preconditions.checkNotNull; + import java.lang.reflect.Method; import java.net.URI; +import java.util.List; + +import javax.annotation.Nullable; import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpRequestFilter; +import org.jclouds.io.Payload; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; /** * Represents a request generated from annotations @@ -30,21 +41,96 @@ import org.jclouds.http.HttpRequest; * @author Adrian Cole */ public class GeneratedHttpRequest extends HttpRequest { - private final Class declaring; - private final Method javaMethod; - private final Object[] args; - - GeneratedHttpRequest(String method, URI endpoint, Class declaring, Method javaMethod, - Object... args) { - this(method, endpoint, new char[] {}, declaring, javaMethod, args); + public static Builder builder() { + return new Builder(); } - GeneratedHttpRequest(String method, URI endpoint, char[] skips, Class declaring, - Method javaMethod, Object... args) { - super(method, endpoint, skips); - this.declaring = declaring; - this.javaMethod = javaMethod; - this.args = args; + public static class Builder extends HttpRequest.Builder> { + protected Class declaring; + protected Method javaMethod; + protected List args; + + public Builder declaring(Class declaring) { + this.declaring = checkNotNull(declaring, "declaring"); + return this; + } + + public Builder javaMethod(Method javaMethod) { + this.javaMethod = checkNotNull(javaMethod, "javaMethod"); + return this; + } + + public Builder args(Object[] args) { + // TODO make immutable. ImmutableList.of() doesn't accept nulls + return args((args == null) ? ImmutableList. of() : Lists.newArrayList(args)); + } + + public Builder args(List args) { + this.args = checkNotNull(args, "args"); + return this; + } + + @Override + public Builder filters(List requestFilters) { + return (Builder) super.filters(requestFilters); + } + + @Override + public Builder method(String method) { + return (Builder) super.method(method); + } + + @Override + public Builder endpoint(URI endpoint) { + return (Builder) super.endpoint(endpoint); + } + + @Override + public Builder skips(char[] skips) { + return (Builder) super.skips(skips); + } + + @Override + public Builder payload(Payload payload) { + return (Builder) super.payload(payload); + } + + @Override + public Builder headers(Multimap headers) { + return (Builder) super.headers(headers); + } + + @Override + public GeneratedHttpRequest build() { + return new GeneratedHttpRequest(method, endpoint, skips, requestFilters, payload, headers, declaring, + javaMethod, args); + } + + public static Builder from(HttpRequest input) { + return new Builder().method(input.getMethod()).endpoint(input.getEndpoint()).skips(input.getSkips()) + .filters(input.getFilters()).payload(input.getPayload()).headers(input.getHeaders()); + } + + public static Builder from(GeneratedHttpRequest input) { + return new Builder().method(input.getMethod()).endpoint(input.getEndpoint()).skips(input.getSkips()) + .filters(input.getFilters()).payload(input.getPayload()).headers(input.getHeaders()) + .declaring(input.getDeclaring()).javaMethod(input.getJavaMethod()).args(input.getArgs()); + } + + } + + private final Class declaring; + private final Method javaMethod; + private final List args; + + GeneratedHttpRequest(String method, URI endpoint, char[] skips, List requestFilters, + @Nullable Payload payload, Multimap headers, Class declaring, Method javaMethod, + Iterable args) { + super(method, endpoint, skips, requestFilters, payload, headers); + this.declaring = checkNotNull(declaring, "declaring"); + this.javaMethod = checkNotNull(javaMethod, "javaMethod"); + // TODO make immutable. ImmutableList.of() doesn't accept nulls + this.args = Lists.newArrayList(checkNotNull(args, "args")); } public Class getDeclaring() { @@ -55,8 +141,13 @@ public class GeneratedHttpRequest extends HttpRequest { return javaMethod; } - public Object[] getArgs() { + public List getArgs() { return args; } + @Override + public Builder toBuilder() { + return Builder.from(this); + } + } 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 725f0c5b43..30b123cca6 100755 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -33,14 +33,10 @@ import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newTreeSet; import static java.util.Arrays.asList; -import static javax.ws.rs.core.HttpHeaders.*; +import static javax.ws.rs.core.HttpHeaders.ACCEPT; import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; import static javax.ws.rs.core.HttpHeaders.HOST; -import static org.jclouds.http.HttpUtils.makeQueryLine; -import static org.jclouds.http.HttpUtils.parseQueryToMap; -import static org.jclouds.http.HttpUtils.urlEncode; import static org.jclouds.io.Payloads.newPayload; -import static org.jclouds.util.Utils.replaceTokens; import java.io.InputStream; import java.lang.annotation.Annotation; @@ -56,9 +52,9 @@ import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; -import java.util.Map.Entry; import javax.annotation.Nullable; import javax.annotation.Resource; @@ -77,21 +73,24 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; +import org.jclouds.functions.IdentityFunction; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpUtils; import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseSax; +import org.jclouds.http.functions.ParseSax.HandlerWithResult; 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.utils.ModifyRequest; import org.jclouds.internal.ClassMethodArgs; +import org.jclouds.io.ContentMetadata; import org.jclouds.io.Payload; import org.jclouds.io.PayloadEnclosing; import org.jclouds.io.Payloads; @@ -124,15 +123,20 @@ import org.jclouds.rest.annotations.Unwrap; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Inject; import com.google.inject.Injector; @@ -249,7 +253,7 @@ public class RestAnnotationProcessor { transformer = injector.getInstance(getParserOrThrowException(method)); } if (transformer instanceof InvocationContext) { - ((InvocationContext) transformer).setContext((GeneratedHttpRequest) request); + ((InvocationContext) transformer).setContext(request); } return transformer; } @@ -402,8 +406,18 @@ public class RestAnnotationProcessor { endpoint = injector.getInstance(Key.get(URI.class, org.jclouds.rest.annotations.Provider.class)); logger.trace("using default endpoint %s for %s", endpoint, cma); } + GeneratedHttpRequest.Builder requestBuilder; + HttpRequest r = RestAnnotationProcessor.findHttpRequestInArgs(args); + if (r != null) { + requestBuilder = GeneratedHttpRequest.Builder. from(r); + endpoint = r.getEndpoint(); + } else { + requestBuilder = GeneratedHttpRequest. builder(); + requestBuilder.method(getHttpMethodOrConstantOrThrowException(method)); + } - String httpMethod = getHttpMethodOrConstantOrThrowException(method); + requestBuilder.declaring(declaring).javaMethod(method).args(args).skips(skips); + requestBuilder.filters(getFiltersIfAnnotated(method)); UriBuilder builder = uriBuilderProvider.get().uri(endpoint); @@ -413,26 +427,27 @@ public class RestAnnotationProcessor { Multimap formParams = addFormParams(tokenValues.entries(), method, args); Multimap queryParams = addQueryParams(tokenValues.entries(), method, args); - - addMatrixParams(builder, tokenValues.entries(), method, args); - + Multimap matrixParams = addMatrixParams(tokenValues.entries(), method, args); Multimap headers = buildHeaders(tokenValues.entries(), method, args); + if (shouldAddHostHeader(method)) + headers.put(HOST, endpoint.getHost()); + 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())); + headers.put(header.getKey(), Strings2.replaceTokens(header.getValue(), tokenValues.entries())); } for (Entry matrix : options.buildMatrixParameters().entries()) { - builder.matrixParam(matrix.getKey(), replaceTokens(matrix.getValue(), tokenValues.entries())); + matrixParams.put(matrix.getKey(), Strings2.replaceTokens(matrix.getValue(), tokenValues.entries())); } for (Entry query : options.buildQueryParameters().entries()) { - queryParams.put(query.getKey(), replaceTokens(query.getValue(), tokenValues.entries())); + queryParams.put(query.getKey(), Strings2.replaceTokens(query.getValue(), tokenValues.entries())); } for (Entry form : options.buildFormParameters().entries()) { - formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues.entries())); + formParams.put(form.getKey(), Strings2.replaceTokens(form.getValue(), tokenValues.entries())); } String pathSuffix = options.buildPathSuffix(); @@ -444,23 +459,25 @@ public class RestAnnotationProcessor { payload = Payloads.newStringPayload(stringPayload); } - if (queryParams.size() > 0) { - builder.replaceQuery(makeQueryLine(queryParams, null, skips)); + if (matrixParams.size() > 0) { + for (String key : matrixParams.keySet()) + builder.matrixParam(key, Lists.newArrayList(matrixParams.get(key)).toArray()); } + if (queryParams.size() > 0) { + builder.replaceQuery(ModifyRequest.makeQueryLine(queryParams, null, skips)); + } + + requestBuilder.headers(filterOutContentHeaders(headers)); + try { - endpoint = builder.buildFromEncodedMap(convertUnsafe(tokenValues)); + requestBuilder.endpoint(builder.buildFromEncodedMap(convertUnsafe(tokenValues))); } catch (IllegalArgumentException e) { throw new IllegalStateException(e); } catch (UriBuilderException e) { throw new IllegalStateException(e); } - 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, concat(tokenValues.entries(), formParams.entries())); @@ -477,18 +494,47 @@ public class RestAnnotationProcessor { payload.getContentMetadata().setContentType(Iterables.get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { - request.setPayload(payload); + requestBuilder.payload(payload); } - decorateRequest(request, headers); + GeneratedHttpRequest request = requestBuilder.build(); + + org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(method, args); + if (mapBinder != null) { + Map mapParams = buildPostParams(method, args); + if (method.isAnnotationPresent(MapPayloadParams.class)) { + MapPayloadParams params = method.getAnnotation(MapPayloadParams.class); + addMapPayload(mapParams, params, headers.entries()); + } + request = mapBinder.bindToRequest(request, mapParams); + } else { + request = decorateRequest(request); + } + + if (request.getPayload() != null) + request.getPayload().getContentMetadata().setPropertiesFromHttpHeaders(headers); + utils.checkRequestHasRequiredProperties(request); return request; } + public static Multimap filterOutContentHeaders(Multimap headers) { + // TODO make a filter like {@link Maps.filterKeys} instead of this + ImmutableMultimap.Builder headersBuilder = ImmutableMultimap.builder(); + // http message usually comes in as a null key header, let's filter it out. + for (String header : Iterables.filter(headers.keySet(), Predicates.notNull())) { + if (!ContentMetadata.HTTP_HEADERS.contains(header)) { + headersBuilder.putAll(header, headers.get(header)); + } + } + return headersBuilder.build(); + } + public static final String BOUNDARY = "--JCLOUDS--"; private Multimap addPathAndGetTokens(Class clazz, Method method, Object[] args, UriBuilder builder) { if (clazz.isAnnotationPresent(Path.class)) builder.path(clazz); - builder.path(method); + if (method.isAnnotationPresent(Path.class)) + builder.path(method); return encodeValues(getPathParamKeyValues(method, args), skips); } @@ -499,25 +545,27 @@ public class RestAnnotationProcessor { 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(ModifyRequest.makeQueryLine(ModifyRequest.parseQueryToMap(newQuery), sorter, skips)); return builder.build(); } - private void addMatrixParams(UriBuilder builder, Collection> tokenValues, Method method, + private Multimap addMatrixParams(Collection> tokenValues, Method method, Object... args) { + Multimap matrixMap = LinkedListMultimap.create(); if (declaring.isAnnotationPresent(MatrixParams.class)) { MatrixParams matrix = declaring.getAnnotation(MatrixParams.class); - addMatrix(builder, matrix, tokenValues); + addMatrix(matrixMap, matrix, tokenValues); } if (method.isAnnotationPresent(MatrixParams.class)) { MatrixParams matrix = method.getAnnotation(MatrixParams.class); - addMatrix(builder, matrix, tokenValues); + addMatrix(matrixMap, matrix, tokenValues); } for (Entry matrix : getMatrixParamKeyValues(method, args).entries()) { - builder.matrixParam(matrix.getKey(), replaceTokens(matrix.getValue(), tokenValues)); + matrixMap.put(matrix.getKey(), Strings2.replaceTokens(matrix.getValue(), tokenValues)); } + return matrixMap; } private Multimap addFormParams(Collection> tokenValues, Method method, @@ -534,7 +582,7 @@ public class RestAnnotationProcessor { } for (Entry form : getFormParamKeyValues(method, args).entries()) { - formMap.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); + formMap.put(form.getKey(), Strings2.replaceTokens(form.getValue(), tokenValues)); } return formMap; } @@ -553,7 +601,7 @@ public class RestAnnotationProcessor { } for (Entry query : getQueryParamKeyValues(method, args).entries()) { - queryMap.put(query.getKey(), replaceTokens(query.getValue(), tokenValues)); + queryMap.put(query.getKey(), Strings2.replaceTokens(query.getValue(), tokenValues)); } return queryMap; } @@ -565,18 +613,7 @@ 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)); - } - } - } - - private void addMapPayload(Map postParams, MapPayloadParams mapDefaults, - Collection> tokenValues) { - for (int i = 0; i < mapDefaults.keys().length; i++) { - if (mapDefaults.values()[i].equals(MapPayloadParams.NULL)) { - postParams.put(mapDefaults.keys()[i], null); - } else { - postParams.put(mapDefaults.keys()[i], replaceTokens(mapDefaults.values()[i], tokenValues)); + formParams.put(form.keys()[i], Strings2.replaceTokens(form.values()[i], tokenValues)); } } } @@ -588,38 +625,54 @@ public class RestAnnotationProcessor { 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], Strings2.replaceTokens(query.values()[i], tokenValues)); } } } - private void addMatrix(UriBuilder builder, MatrixParams matrix, Collection> tokenValues) { + private void addMatrix(Multimap matrixParams, 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]); + matrixParams.removeAll(matrix.keys()[i]); + matrixParams.put(matrix.keys()[i], null); } else { - builder.matrixParam(matrix.keys()[i], replaceTokens(matrix.values()[i], tokenValues)); + matrixParams.put(matrix.keys()[i], Strings2.replaceTokens(matrix.values()[i], tokenValues)); } } } - private void addFiltersIfAnnotated(Method method, HttpRequest request) { + private void addMapPayload(Map postParams, MapPayloadParams mapDefaults, + Collection> tokenValues) { + for (int i = 0; i < mapDefaults.keys().length; i++) { + if (mapDefaults.values()[i].equals(MapPayloadParams.NULL)) { + postParams.put(mapDefaults.keys()[i], null); + } else { + postParams.put(mapDefaults.keys()[i], Strings2.replaceTokens(mapDefaults.values()[i], tokenValues)); + } + } + } + + @VisibleForTesting + List getFiltersIfAnnotated(Method method) { + List filters = Lists.newArrayList(); if (declaring.isAnnotationPresent(RequestFilters.class)) { 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()); + filters.add(instance); + logger.trace("adding filter %s from annotation on %s", instance, declaring.getName()); } } if (method.isAnnotationPresent(RequestFilters.class)) { if (method.isAnnotationPresent(OverrideRequestFilters.class)) - request.getFilters().clear(); + filters.clear(); 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()); + filters.add(instance); + logger.trace("adding filter %s from annotation on %s", instance, method.getName()); } } + return filters; } @VisibleForTesting @@ -682,18 +735,18 @@ public class RestAnnotationProcessor { public static final TypeLiteral> futureBooleanLiteral = new TypeLiteral>() { }; - public static final TypeLiteral> futureStringLiteral = new TypeLiteral>() { }; - public static final TypeLiteral> futureVoidLiteral = new TypeLiteral>() { }; public static final TypeLiteral> futureURILiteral = new TypeLiteral>() { }; public static final TypeLiteral> futureInputStreamLiteral = new TypeLiteral>() { }; + public static final TypeLiteral> futureHttpResponseLiteral = new TypeLiteral>() { + }; - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public static Key> getParserOrThrowException(Method method) { ResponseParser annotation = method.getAnnotation(ResponseParser.class); if (annotation == null) { @@ -706,6 +759,9 @@ public class RestAnnotationProcessor { } else if (method.getReturnType().equals(InputStream.class) || TypeLiteral.get(method.getGenericReturnType()).equals(futureInputStreamLiteral)) { return Key.get(ReturnInputStream.class); + } else if (method.getReturnType().equals(HttpResponse.class) + || TypeLiteral.get(method.getGenericReturnType()).equals(futureHttpResponseLiteral)) { + return Key.get((Class) IdentityFunction.class); } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) { Type returnVal; if (method.getReturnType().getTypeParameters().length == 0) { @@ -780,7 +836,8 @@ public class RestAnnotationProcessor { private Multimap constants = LinkedHashMultimap.create(); public boolean isHttpMethod(Method method) { - return method.isAnnotationPresent(Path.class) || getHttpMethods(method) != null; + return method.isAnnotationPresent(Path.class) || getHttpMethods(method) != null + || Sets.newHashSet(method.getParameterTypes()).contains(HttpRequest.class); } public boolean isConstantDeclaration(Method method) { @@ -815,61 +872,53 @@ public class RestAnnotationProcessor { return requests.iterator().next(); } - public void addHostHeaderIfAnnotatedWithVirtualHost(Multimap headers, String host, Method method) { + public boolean shouldAddHostHeader(Method method) { if (declaring.isAnnotationPresent(VirtualHost.class) || method.isAnnotationPresent(VirtualHost.class)) { - headers.put(HOST, host); + return true; } + return false; } - public void decorateRequest(GeneratedHttpRequest request, Multimap headers) { - org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(request.getJavaMethod(), request.getArgs()); - if (mapBinder != null) { - Map mapParams = buildPostParams(request.getJavaMethod(), request.getArgs()); - if (request.getJavaMethod().isAnnotationPresent(MapPayloadParams.class)) { - MapPayloadParams params = request.getJavaMethod().getAnnotation(MapPayloadParams.class); - addMapPayload(mapParams, params, headers.entries()); - } - mapBinder.bindToRequest(request, mapParams); - } else { - OUTER: for (Entry> entry : filterValues( - 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(); - Binder binder = injector.getInstance(payloadAnnotation.value()); - 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; - if (arrayLength == 0) - break OUTER; - 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()) { - input = request.getArgs()[entry.getKey()]; - } else { - input = request.getArgs()[entry.getKey()]; - if (input.getClass().isArray()) { - Object[] payloadArray = (Object[]) input; - input = payloadArray.length > 0 ? payloadArray[0] : null; - } + public GeneratedHttpRequest decorateRequest(GeneratedHttpRequest request) { + OUTER: for (Entry> entry : filterValues( + methodToIndexOfParamToDecoratorParamAnnotation.get(request.getJavaMethod()), + new Predicate>() { + public boolean apply(Set input) { + return input.size() >= 1; } - if (input != null) { - binder.bindToRequest(request, input); - } - if (shouldBreak) + }).entrySet()) { + boolean shouldBreak = false; + BinderParam payloadAnnotation = (BinderParam) entry.getValue().iterator().next(); + Binder binder = injector.getInstance(payloadAnnotation.value()); + if (request.getArgs().size() >= entry.getKey() + 1 && request.getArgs().get(entry.getKey()) != null) { + Object input; + Class parameterType = request.getJavaMethod().getParameterTypes()[entry.getKey()]; + Class argType = request.getArgs().get(entry.getKey()).getClass(); + if (!argType.isArray() && request.getJavaMethod().isVarArgs() && parameterType.isArray()) { + int arrayLength = request.getArgs().size() - request.getJavaMethod().getParameterTypes().length + 1; + if (arrayLength == 0) break OUTER; + input = (Object[]) Array.newInstance(request.getArgs().get(entry.getKey()).getClass(), arrayLength); + System.arraycopy(request.getArgs().toArray(), entry.getKey(), input, 0, arrayLength); + shouldBreak = true; + } else if (argType.isArray() && request.getJavaMethod().isVarArgs() && parameterType.isArray()) { + input = request.getArgs().get(entry.getKey()); + } else { + input = request.getArgs().get(entry.getKey()); + if (input.getClass().isArray()) { + Object[] payloadArray = (Object[]) input; + input = payloadArray.length > 0 ? payloadArray[0] : null; + } } + if (input != null) { + request = binder.bindToRequest(request, input); + } + if (shouldBreak) + break OUTER; } } - utils.setPayloadPropertiesFromHeaders(headers, request); + + return request; } public static Map> indexWithOnlyOneAnnotation(Method method, String description, @@ -928,7 +977,7 @@ public class RestAnnotationProcessor { for (Entry> entry : indexToHeaderParam.entrySet()) { for (Annotation key : entry.getValue()) { String value = args[entry.getKey()].toString(); - value = replaceTokens(value, tokenValues); + value = Strings2.replaceTokens(value, tokenValues); headers.put(((HeaderParam) key).value(), value); } } @@ -983,7 +1032,7 @@ public class RestAnnotationProcessor { Collection> tokenValues) { for (int i = 0; i < header.keys().length; i++) { String value = header.values()[i]; - value = replaceTokens(value, tokenValues); + value = Strings2.replaceTokens(value, tokenValues); headers.put(header.keys()[i], value); } @@ -1007,7 +1056,7 @@ public class RestAnnotationProcessor { if (!PartParam.NO_CONTENT_TYPE.equals(param.contentType())) options.contentType(param.contentType()); if (!PartParam.NO_FILENAME.equals(param.filename())) - options.filename(replaceTokens(param.filename(), iterable)); + options.filename(Strings2.replaceTokens(param.filename(), iterable)); Part part = Part.create(param.name(), newPayload(args[entry.getKey()]), options); parts.add(part); } @@ -1068,7 +1117,7 @@ public class RestAnnotationProcessor { private Multimap encodeValues(Multimap unencoded, char... skips) { Multimap encoded = LinkedHashMultimap.create(); for (Entry entry : unencoded.entries()) { - encoded.put(entry.getKey(), urlEncode(entry.getValue(), skips)); + encoded.put(entry.getKey(), Strings2.urlEncode(entry.getValue(), skips)); } return encoded; } diff --git a/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java b/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java index 04dfd6e313..99742c61fe 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java @@ -138,7 +138,6 @@ public class RestContextImpl implements RestContext { return result; } - @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) @@ -147,7 +146,7 @@ public class RestContextImpl implements RestContext { return false; if (getClass() != obj.getClass()) return false; - RestContextImpl other = (RestContextImpl) obj; + RestContextImpl other = (RestContextImpl) obj; if (apiVersion == null) { if (other.apiVersion != null) return false; diff --git a/core/src/main/java/org/jclouds/util/Assertions.java b/core/src/main/java/org/jclouds/util/Assertions.java new file mode 100644 index 0000000000..092c1dd594 --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Assertions.java @@ -0,0 +1,45 @@ +/** + * + * 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.util; + +import com.google.common.base.Supplier; + +/** + * + * @author Adrian Cole + */ +public class Assertions { + + public static boolean eventuallyTrue(Supplier assertion, long inconsistencyMillis) + throws InterruptedException { + + for (int i = 0; i < 30; i++) { + if (!assertion.get()) { + Thread.sleep(inconsistencyMillis / 30); + continue; + } + return true; + } + return false; + } + + + +} diff --git a/core/src/main/java/org/jclouds/util/CredentialUtils.java b/core/src/main/java/org/jclouds/util/CredentialUtils.java new file mode 100644 index 0000000000..fd24e132dc --- /dev/null +++ b/core/src/main/java/org/jclouds/util/CredentialUtils.java @@ -0,0 +1,58 @@ +/** + * + * 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.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Nullable; + +import org.jclouds.crypto.Pems; +import org.jclouds.domain.Credentials; + + + +/** + * + * + * @author Adrian Cole + */ +public class CredentialUtils { + + public static Credentials overrideCredentialsIfSupplied(Credentials defaultCredentials, + @Nullable Credentials overridingCredentials) { + if (overridingCredentials == null) + return defaultCredentials; + String identity = overridingCredentials.identity != null ? overridingCredentials.identity : checkNotNull( + defaultCredentials, "defaultCredentials").identity; + String credential = overridingCredentials.credential != null ? overridingCredentials.credential : checkNotNull( + defaultCredentials, "defaultCredentials").credential; + + return new Credentials(identity, credential); + } + + public static boolean isPrivateKeyCredential(Credentials credentials) { + return credentials != null + && credentials.credential != null + && (credentials.credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credentials.credential + .startsWith(Pems.PRIVATE_PKCS8_MARKER)); + } + + +} diff --git a/core/src/main/java/org/jclouds/util/InputStreamChain.java b/core/src/main/java/org/jclouds/util/InputStreamChain.java index 60527b396f..be5af49d1b 100644 --- a/core/src/main/java/org/jclouds/util/InputStreamChain.java +++ b/core/src/main/java/org/jclouds/util/InputStreamChain.java @@ -71,7 +71,7 @@ public class InputStreamChain extends InputStream { * @return instance of self (for fluent calls) */ public InputStreamChain addAsInputStream(final String value) { - return addInputStream(Utils.toInputStream(value)); + return addInputStream(Strings2.toInputStream(value)); } @Override diff --git a/core/src/main/java/org/jclouds/util/Lists2.java b/core/src/main/java/org/jclouds/util/Lists2.java new file mode 100644 index 0000000000..71fa38b02e --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Lists2.java @@ -0,0 +1,56 @@ +/** + * + * 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.util; + +import static com.google.common.collect.Lists.newArrayList; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + + +/** + * + * @author Adrian Cole + */ +public class Lists2 { + + /** + * Like Ordering, but handle the case where there are multiple valid maximums + */ + @SuppressWarnings("unchecked") + public static List multiMax(Comparator ordering, Iterable iterable) { + Iterator iterator = iterable.iterator(); + List maxes = newArrayList(iterator.next()); + E maxSoFar = maxes.get(0); + while (iterator.hasNext()) { + E current = iterator.next(); + int comparison = ordering.compare(maxSoFar, current); + if (comparison == 0) { + maxes.add(current); + } else if (comparison < 0) { + maxes = newArrayList(current); + maxSoFar = current; + } + } + return maxes; + } + +} diff --git a/core/src/main/java/org/jclouds/util/Maps2.java b/core/src/main/java/org/jclouds/util/Maps2.java new file mode 100644 index 0000000000..a1e768838f --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Maps2.java @@ -0,0 +1,115 @@ +/** + * + * 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.util; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.equalTo; +import static com.google.common.base.Predicates.not; +import static com.google.common.collect.Maps.filterKeys; + +import java.util.Map; +import java.util.Map.Entry; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Maps; + +/** + * General utilities used in jclouds code for {@link Map}s. + * + * @author Adrian Cole + */ +public class Maps2 { + + /** + * If the supplied map contains the key {@code k1}, its value will be assigned to the key + * {@code k2}. Note that this doesn't modify the input map. + * + * @param + * type of value the map holds + * @param in + * the map you wish to make a copy of + * @param k1 + * old key + * @param k2 + * new key + * @return copy of the map with the value of the key re-routed, or the original, if it {@code k1} + * wasn't present. + */ + public static Map renameKey(Map in, String k1, String k2) { + if (checkNotNull(in, "input map").containsKey(checkNotNull(k1, "old key"))) { + Builder builder = ImmutableMap.builder(); + builder.putAll(filterKeys(in, not(equalTo(k1)))); + V tags = in.get(k1); + builder.put(checkNotNull(k2, "new key"), tags); + in = builder.build(); + } + return in; + } + + /** + * change the keys but keep the values in-tact. + * + * @param + * input key type + * @param + * output key type + * @param + * value type + * @param in + * input map to transform + * @param fn + * how to transform the values + * @return immutableMap with the new keys. + */ + public static Map transformKeys(Map in, Function fn) { + checkNotNull(in, "input map"); + checkNotNull(fn, "function"); + Builder returnVal = ImmutableMap.builder(); + for (Entry entry : in.entrySet()) + returnVal.put(fn.apply(entry.getKey()), entry.getValue()); + return returnVal.build(); + } + + public static Supplier> composeMapSupplier(Iterable>> suppliers) { + return new ListMapSupplier(suppliers); + } + + static class ListMapSupplier implements Supplier> { + + private final Iterable>> suppliers; + + ListMapSupplier(Iterable>> suppliers) { + this.suppliers = checkNotNull(suppliers, "suppliers"); + } + + @Override + public Map get() { + Map toReturn = Maps.newLinkedHashMap(); + for (Supplier> supplier : suppliers) { + toReturn.putAll(supplier.get()); + } + return toReturn; + } + } + +} diff --git a/core/src/main/java/org/jclouds/util/Modules2.java b/core/src/main/java/org/jclouds/util/Modules2.java new file mode 100644 index 0000000000..4f1118e975 --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Modules2.java @@ -0,0 +1,75 @@ +/** + * + * 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.util; + +import static com.google.common.base.Splitter.on; +import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.Iterables.transform; + +import java.util.Properties; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + + + +/** + * + * + * @author Adrian Cole + */ +public class Modules2 { + + public static Iterable modulesFromCommaDelimitedString(String moduleClasses) { + Iterable modules = ImmutableSet.of(); + if (moduleClasses != null) { + Iterable transformer = ImmutableList.copyOf(on(',').split(moduleClasses)); + modules = transform(transformer, new Function() { + + @Override + public Module apply(String from) { + try { + return (Module) Class.forName(from).newInstance(); + } catch (InstantiationException e) { + throw new RuntimeException("error instantiating " + from, e); + } catch (IllegalAccessException e) { + throw new RuntimeException("error instantiating " + from, e); + } catch (ClassNotFoundException e) { + throw new RuntimeException("error instantiating " + from, e); + } + } + + }); + } + return modules; + } + + public static Iterable modulesForProviderInProperties(String providerName, Properties props) { + return concat(modulesFromProperty(props, "jclouds.modules"), + modulesFromProperty(props, providerName + ".modules")); + } + + public static Iterable modulesFromProperty(Properties props, String property) { + return modulesFromCommaDelimitedString(props.getProperty(property, null)); + } + +} diff --git a/core/src/main/java/org/jclouds/util/NullSafeCollections.java b/core/src/main/java/org/jclouds/util/NullSafeCollections.java new file mode 100644 index 0000000000..97f35d0db6 --- /dev/null +++ b/core/src/main/java/org/jclouds/util/NullSafeCollections.java @@ -0,0 +1,39 @@ +/** + * + * 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.util; + +import java.util.Set; + +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +public class NullSafeCollections { + + public static Set nullSafeSet(T in) { + if (in == null) { + return ImmutableSet. of(); + } + return ImmutableSet. of(in); + } + +} diff --git a/core/src/main/java/org/jclouds/util/Preconditions2.java b/core/src/main/java/org/jclouds/util/Preconditions2.java new file mode 100644 index 0000000000..ba7c66ddbd --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Preconditions2.java @@ -0,0 +1,55 @@ +/** + * + * 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.util; + +import static com.google.common.base.Preconditions.checkArgument; + + +/** + * Preconditions not in guava. + * + * @author Adrian Cole + */ +public class Preconditions2 { + + /** + * Will throw an exception if the argument is null or empty. + * + * @param nullableString + * string to verify. Can be null or empty. + */ + public static void checkNotEmpty(String nullableString) { + Preconditions2.checkNotEmpty(nullableString, "Argument can't be null or empty"); + } + + /** + * Will throw an exception if the argument is null or empty. Accepts a custom error message. + * + * @param nullableString + * string to verify. Can be null or empty. + * @param message + * message to show in case of exception + */ + public static void checkNotEmpty(String nullableString, String message) { + checkArgument(nullableString != null && nullableString.length() > 0, message); + } + + +} diff --git a/core/src/main/java/org/jclouds/util/SaxUtils.java b/core/src/main/java/org/jclouds/util/SaxUtils.java new file mode 100644 index 0000000000..d6a20265be --- /dev/null +++ b/core/src/main/java/org/jclouds/util/SaxUtils.java @@ -0,0 +1,46 @@ +/** + * + * 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.util; + + +import java.util.Map; + + +import org.xml.sax.Attributes; + +import com.google.common.collect.Maps; + +/** + * + * @author Adrian Cole + */ +public class SaxUtils { + public static Map cleanseAttributes(Attributes in) { + Map attrs = Maps.newLinkedHashMap(); + for (int i = 0; i < in.getLength(); i++) { + String name = in.getQName(i); + if (name.indexOf(':') != -1) + name = name.substring(name.indexOf(':') + 1); + attrs.put(name, in.getValue(i)); + } + return attrs; + } + +} diff --git a/core/src/main/java/org/jclouds/util/Strings2.java b/core/src/main/java/org/jclouds/util/Strings2.java new file mode 100644 index 0000000000..6a80f754e8 --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Strings2.java @@ -0,0 +1,203 @@ +/** + * + * 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.util; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.io.ByteStreams.toByteArray; +import static com.google.common.io.Closeables.closeQuietly; +import static org.jclouds.util.Patterns.CHAR_TO_ENCODED_PATTERN; +import static org.jclouds.util.Patterns.CHAR_TO_PATTERN; +import static org.jclouds.util.Patterns.PLUS_PATTERN; +import static org.jclouds.util.Patterns.STAR_PATTERN; +import static org.jclouds.util.Patterns.TOKEN_TO_PATTERN; +import static org.jclouds.util.Patterns.URL_ENCODED_PATTERN; +import static org.jclouds.util.Patterns._7E_PATTERN; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.annotation.Resource; + +import org.jclouds.logging.Logger; + +import com.google.common.base.Charsets; + +/** + * + * + * @author Adrian Cole + */ +public class Strings2 { + + /** + * 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)) + return in; + try { + String returnVal = URLEncoder.encode(in, "UTF-8"); + returnVal = Strings2.replaceAll(returnVal, '+', PLUS_PATTERN, "%20"); + returnVal = Strings2.replaceAll(returnVal, '*', STAR_PATTERN, "%2A"); + returnVal = Strings2.replaceAll(returnVal, _7E_PATTERN, "~"); + for (char c : skipEncode) { + returnVal = Strings2.replaceAll(returnVal, CHAR_TO_ENCODED_PATTERN.get(c), c + ""); + } + return returnVal; + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("Bad encoding on input: " + in, e); + } + } + + public static boolean isUrlEncoded(String in) { + return URL_ENCODED_PATTERN.matcher(in).matches(); + } + + public static String urlDecode(String in) { + try { + return URLDecoder.decode(in, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("Bad encoding on input: " + in, e); + } + } + + public static String replaceTokens(String value, Iterable> tokenValues) { + for (Entry tokenValue : tokenValues) { + value = Strings2.replaceAll(value, TOKEN_TO_PATTERN.get(tokenValue.getKey()), tokenValue.getValue()); + } + return value; + } + + public static String replaceAll(String returnVal, Pattern pattern, String replace) { + Matcher m = pattern.matcher(returnVal); + returnVal = m.replaceAll(replace); + return returnVal; + } + + public static String replaceAll(String input, char ifMatch, Pattern pattern, String replacement) { + if (input.indexOf(ifMatch) != -1) { + input = pattern.matcher(input).replaceAll(replacement); + } + return input; + } + + public static String replaceAll(String input, char match, String replacement) { + if (input.indexOf(match) != -1) { + input = CHAR_TO_PATTERN.get(match).matcher(input).replaceAll(replacement); + } + return input; + } + + public static final String UTF8_ENCODING = "UTF-8"; + + public static String toStringAndClose(InputStream input) throws IOException { + checkNotNull(input, "input"); + try { + return new String(toByteArray(input), Charsets.UTF_8); + } catch (IOException e) { + logger.warn(e, "Failed to read from stream"); + return null; + } catch (NullPointerException e) { + return null; + } finally { + closeQuietly(input); + } + } + + public static InputStream toInputStream(String in) { + return new ByteArrayInputStream(in.getBytes(Charsets.UTF_8)); + } + + /** + * Encode the given string with the given encoding, if possible. If the encoding fails with + * {@link UnsupportedEncodingException}, log a warning and fall back to the system's default + * encoding. + * + * @param str + * what to encode + * @param charsetName + * the name of a supported {@link java.nio.charset.Charset charset} + * @return properly encoded String. + */ + public static byte[] encodeString(String str, String charsetName) { + try { + return str.getBytes(charsetName); + } catch (UnsupportedEncodingException e) { + logger.warn(e, "Failed to encode string to bytes with encoding " + charsetName + + ". Falling back to system's default encoding"); + return str.getBytes(); + } + } + + @Resource + private static Logger logger = Logger.NULL; + + /** + * Encode the given string with the UTF-8 encoding, the sane default. In the very unlikely event + * the encoding fails with {@link UnsupportedEncodingException}, log a warning and fall back to + * the system's default encoding. + * + * @param str + * what to encode + * @return properly encoded String. + */ + public static byte[] encodeString(String str) { + return encodeString(str, UTF8_ENCODING); + } + + /** + * replaces tokens that are expressed as {token} + * + *

+ * ex. if input is "hello {where}"
+ * and replacements is "where" -> "world"
+ * then replaceTokens returns "hello world" + * + * @param input + * source to replace + * @param replacements + * token/value pairs + */ + public static String replaceTokens(String input, Map replacements) { + Matcher matcher = Patterns.TOKEN_PATTERN.matcher(input); + StringBuilder builder = new StringBuilder(); + int i = 0; + while (matcher.find()) { + String replacement = replacements.get(matcher.group(1)); + builder.append(input.substring(i, matcher.start())); + if (replacement == null) + builder.append(matcher.group(0)); + else + builder.append(replacement); + i = matcher.end(); + } + builder.append(input.substring(i, input.length())); + return builder.toString(); + } + +} diff --git a/core/src/main/java/org/jclouds/util/Suppliers2.java b/core/src/main/java/org/jclouds/util/Suppliers2.java new file mode 100644 index 0000000000..8d98ce10d9 --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Suppliers2.java @@ -0,0 +1,49 @@ +/** + * + * 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.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.io.IOException; +import java.io.OutputStream; + +import com.google.common.io.OutputSupplier; + +/** + * + * @author Adrian Cole + */ +public class Suppliers2 { + + /** + * converts an {@link OutputStream} to an {@link OutputSupplier} + * + */ + public static OutputSupplier newOutputStreamSupplier(final OutputStream output) { + checkNotNull(output, "output"); + return new OutputSupplier() { + public OutputStream getOutput() throws IOException { + return output; + } + }; + } + + +} diff --git a/core/src/main/java/org/jclouds/util/Throwables2.java b/core/src/main/java/org/jclouds/util/Throwables2.java new file mode 100644 index 0000000000..d9cc364bb2 --- /dev/null +++ b/core/src/main/java/org/jclouds/util/Throwables2.java @@ -0,0 +1,107 @@ +/** + * + * 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.util; + +import static com.google.common.base.Predicates.instanceOf; +import static com.google.common.base.Throwables.getCausalChain; +import static com.google.common.base.Throwables.propagate; +import static com.google.common.collect.Iterables.find; + +import java.util.NoSuchElementException; + +import org.jclouds.http.HttpResponseException; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Throwables; +import com.google.inject.ProvisionException; +import com.google.inject.spi.Message; + + +/** + * General utilities used in jclouds code. + * + * @author Adrian Cole + */ +public class Throwables2 { + + @SuppressWarnings("unchecked") + public static T getFirstThrowableOfType(Throwable from, Class clazz) { + if (from instanceof ProvisionException) + return getFirstThrowableOfType(ProvisionException.class.cast(from), clazz); + try { + return (T) find(getCausalChain(from), instanceOf(clazz)); + } catch (NoSuchElementException e) { + return null; + } + } + + public static T getFirstThrowableOfType(ProvisionException e, Class clazz) { + for (Message message : e.getErrorMessages()) { + if (message.getCause() != null) { + T cause = getFirstThrowableOfType(message.getCause(), clazz); + if (cause instanceof ProvisionException) + return getFirstThrowableOfType(ProvisionException.class.cast(cause), clazz); + return cause; + } + } + return null; + } + + public static T propagateOrNull(Exception from) { + propagate(from); + assert false : "exception should have propogated"; + return null; + } + + // Note this needs to be kept up-to-date with all top-level exceptions jclouds works against + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static Exception returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(Class[] exceptionTypes, + Exception exception) throws Exception { + for (Class type : exceptionTypes) { + Throwable throwable = getFirstThrowableOfType(exception, type); + if (throwable != null) { + return (Exception) throwable; + } + } + for (Class propagatableExceptionType : new Class[] { IllegalStateException.class, + UnsupportedOperationException.class, IllegalArgumentException.class, AuthorizationException.class, + ResourceNotFoundException.class, HttpResponseException.class }) { + Throwable throwable = getFirstThrowableOfType(exception, propagatableExceptionType); + if (throwable != null) { + throw (Exception) throwable; + } + } + Throwables.throwCause(exception, true); + return exception; + } + + public static T propagateAuthorizationOrOriginalException(Exception e) { + AuthorizationException aex = getFirstThrowableOfType(e, AuthorizationException.class); + if (aex != null) + throw aex; + propagate(e); + assert false : "exception should have propogated " + e; + return null; + } + + + +} diff --git a/core/src/main/java/org/jclouds/util/Utils.java b/core/src/main/java/org/jclouds/util/Utils.java deleted file mode 100644 index d638266cb8..0000000000 --- a/core/src/main/java/org/jclouds/util/Utils.java +++ /dev/null @@ -1,559 +0,0 @@ -/** - * - * 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.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Predicates.equalTo; -import static com.google.common.base.Predicates.instanceOf; -import static com.google.common.base.Predicates.not; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.base.Splitter.on; -import static com.google.common.base.Throwables.getCausalChain; -import static com.google.common.base.Throwables.propagate; -import static com.google.common.collect.Iterables.concat; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.find; -import static com.google.common.collect.Iterables.get; -import static com.google.common.collect.Iterables.transform; -import static com.google.common.collect.Lists.newArrayList; -import static com.google.common.collect.Maps.filterKeys; -import static com.google.common.io.ByteStreams.toByteArray; -import static com.google.common.io.Closeables.closeQuietly; -import static org.jclouds.util.Patterns.CHAR_TO_PATTERN; -import static org.jclouds.util.Patterns.TOKEN_TO_PATTERN; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; -import javax.annotation.Resource; - -import org.jclouds.PropertiesBuilder; -import org.jclouds.crypto.Pems; -import org.jclouds.domain.Credentials; -import org.jclouds.http.HttpResponseException; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.rest.RestContextBuilder; -import org.xml.sax.Attributes; - -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Supplier; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.io.OutputSupplier; -import com.google.inject.Module; -import com.google.inject.ProvisionException; -import com.google.inject.spi.Message; - -/** - * General utilities used in jclouds code. - * - * @author Adrian Cole - */ -public class Utils { - public static Map cleanseAttributes(Attributes in) { - Map attrs = Maps.newLinkedHashMap(); - for (int i = 0; i < in.getLength(); i++) { - String name = in.getQName(i); - if (name.indexOf(':') != -1) - name = name.substring(name.indexOf(':') + 1); - attrs.put(name, in.getValue(i)); - } - return attrs; - } - - /** - * If the supplied map contains the key {@code k1}, its value will be assigned to the key - * {@code k2}. Note that this doesn't modify the input map. - * - * @param - * type of value the map holds - * @param in - * the map you wish to make a copy of - * @param k1 - * old key - * @param k2 - * new key - * @return copy of the map with the value of the key re-routed, or the original, if it {@code k1} - * wasn't present. - */ - public static Map renameKey(Map in, String k1, String k2) { - if (in.containsKey(k1)) { - Builder builder = ImmutableMap.builder(); - builder.putAll(filterKeys(in, not(equalTo(k1)))); - V tags = in.get(k1); - builder.put(k2, tags); - in = builder.build(); - } - return in; - } - - public static Supplier> composeMapSupplier(Iterable>> suppliers) { - return new ListMapSupplier(suppliers); - } - - static class ListMapSupplier implements Supplier> { - - private final Iterable>> suppliers; - - ListMapSupplier(Iterable>> suppliers) { - this.suppliers = suppliers; - } - - @Override - public Map get() { - Map toReturn = Maps.newLinkedHashMap(); - for (Supplier> supplier : suppliers) { - toReturn.putAll(supplier.get()); - } - return toReturn; - } - } - - public static T propagateAuthorizationOrOriginalException(Exception e) { - AuthorizationException aex = getFirstThrowableOfType(e, AuthorizationException.class); - if (aex != null) - throw aex; - propagate(e); - assert false : "exception should have propogated " + e; - return null; - } - - /** - * Like Ordering, but handle the case where there are multiple valid maximums - */ - @SuppressWarnings("unchecked") - public static List multiMax(Comparator ordering, Iterable iterable) { - Iterator iterator = iterable.iterator(); - List maxes = newArrayList(iterator.next()); - E maxSoFar = maxes.get(0); - while (iterator.hasNext()) { - E current = iterator.next(); - int comparison = ordering.compare(maxSoFar, current); - if (comparison == 0) { - maxes.add(current); - } else if (comparison < 0) { - maxes = newArrayList(current); - maxSoFar = current; - } - } - return maxes; - } - - public static final String UTF8_ENCODING = "UTF-8"; - - public static Set nullSafeSet(T in) { - if (in == null) { - return ImmutableSet. of(); - } - return ImmutableSet. of(in); - } - - public static T propagateOrNull(Exception from) { - propagate(from); - assert false : "exception should have propogated"; - return null; - } - - @SuppressWarnings("unchecked") - public static T getFirstThrowableOfType(Throwable from, Class clazz) { - if (from instanceof ProvisionException) - return getFirstThrowableOfType(ProvisionException.class.cast(from), clazz); - try { - return (T) find(getCausalChain(from), instanceOf(clazz)); - } catch (NoSuchElementException e) { - return null; - } - } - - public static T getFirstThrowableOfType(ProvisionException e, Class clazz) { - for (Message message : e.getErrorMessages()) { - if (message.getCause() != null) { - T cause = getFirstThrowableOfType(message.getCause(), clazz); - if (cause instanceof ProvisionException) - return getFirstThrowableOfType(ProvisionException.class.cast(cause), clazz); - return cause; - } - } - return null; - } - - public static String replaceTokens(String value, Iterable> tokenValues) { - for (Entry tokenValue : tokenValues) { - value = replaceAll(value, TOKEN_TO_PATTERN.get(tokenValue.getKey()), tokenValue.getValue()); - } - return value; - } - - public static String replaceAll(String returnVal, Pattern pattern, String replace) { - Matcher m = pattern.matcher(returnVal); - returnVal = m.replaceAll(replace); - return returnVal; - } - - public static String replaceAll(String input, char ifMatch, Pattern pattern, String replacement) { - if (input.indexOf(ifMatch) != -1) { - input = pattern.matcher(input).replaceAll(replacement); - } - return input; - } - - public static String replaceAll(String input, char match, String replacement) { - if (input.indexOf(match) != -1) { - input = CHAR_TO_PATTERN.get(match).matcher(input).replaceAll(replacement); - } - return input; - } - - /** - * converts an {@link OutputStream} to an {@link OutputSupplier} - * - */ - public static OutputSupplier newOutputStreamSupplier(final OutputStream output) { - checkNotNull(output, "output"); - return new OutputSupplier() { - public OutputStream getOutput() throws IOException { - return output; - } - }; - } - - public static boolean eventuallyTrue(Supplier assertion, long inconsistencyMillis) - throws InterruptedException { - - for (int i = 0; i < 30; i++) { - if (!assertion.get()) { - Thread.sleep(inconsistencyMillis / 30); - continue; - } - return true; - } - return false; - - } - - @Resource - protected static Logger logger = Logger.NULL; - - public static String toStringAndClose(InputStream input) throws IOException { - checkNotNull(input, "input"); - try { - return new String(toByteArray(input), Charsets.UTF_8); - } catch (IOException e) { - logger.warn(e, "Failed to read from stream"); - return null; - } catch (NullPointerException e) { - return null; - } finally { - closeQuietly(input); - } - } - - public static InputStream toInputStream(String in) { - return new ByteArrayInputStream(in.getBytes(Charsets.UTF_8)); - } - - /** - * Encode the given string with the given encoding, if possible. If the encoding fails with - * {@link UnsupportedEncodingException}, log a warning and fall back to the system's default - * encoding. - * - * @param str - * what to encode - * @param charsetName - * the name of a supported {@link java.nio.charset.Charset
charset} - * @return properly encoded String. - */ - public static byte[] encodeString(String str, String charsetName) { - try { - return str.getBytes(charsetName); - } catch (UnsupportedEncodingException e) { - logger.warn(e, "Failed to encode string to bytes with encoding " + charsetName - + ". Falling back to system's default encoding"); - return str.getBytes(); - } - } - - /** - * Encode the given string with the UTF-8 encoding, the sane default. In the very unlikely event - * the encoding fails with {@link UnsupportedEncodingException}, log a warning and fall back to - * the system's default encoding. - * - * @param str - * what to encode - * @return properly encoded String. - */ - public static byte[] encodeString(String str) { - return encodeString(str, UTF8_ENCODING); - } - - /** - * replaces tokens that are expressed as {token} - * - *

- * ex. if input is "hello {where}"
- * and replacements is "where" -> "world"
- * then replaceTokens returns "hello world" - * - * @param input - * source to replace - * @param replacements - * token/value pairs - */ - public static String replaceTokens(String input, Map replacements) { - Matcher matcher = Patterns.TOKEN_PATTERN.matcher(input); - StringBuilder builder = new StringBuilder(); - int i = 0; - while (matcher.find()) { - String replacement = replacements.get(matcher.group(1)); - builder.append(input.substring(i, matcher.start())); - if (replacement == null) - builder.append(matcher.group(0)); - else - builder.append(replacement); - i = matcher.end(); - } - builder.append(input.substring(i, input.length())); - return builder.toString(); - } - - /** - * Will throw an exception if the argument is null or empty. - * - * @param nullableString - * string to verify. Can be null or empty. - */ - public static void checkNotEmpty(String nullableString) { - checkNotEmpty(nullableString, "Argument can't be null or empty"); - } - - /** - * Will throw an exception if the argument is null or empty. Accepts a custom error message. - * - * @param nullableString - * string to verify. Can be null or empty. - * @param message - * message to show in case of exception - */ - public static void checkNotEmpty(String nullableString, String message) { - checkArgument(nullableString != null && nullableString.length() > 0, message); - } - - /** - * Gets a set of supported providers. Idea stolen from pallets (supported-clouds). Uses - * rest.properties to populate the set. - * - */ - public static Iterable getSupportedProviders() { - return getSupportedProvidersOfType(RestContextBuilder.class); - } - - /** - * Gets a set of supported providers. Idea stolen from pallets (supported-clouds). Uses - * rest.properties to populate the set. - * - */ - @SuppressWarnings("unchecked") - public static Iterable getSupportedProvidersOfType(Class type) { - Properties properties = new Properties(); - try { - properties.load(Utils.class.getResourceAsStream("/rest.properties")); - } catch (IOException e) { - throw new RuntimeException(e); - } - return getSupportedProvidersOfTypeInProperties(type, properties); - } - - @SuppressWarnings("unchecked") - public static Iterable getSupportedProvidersOfTypeInProperties( - final Class type, final Properties properties) { - return filter(transform(filter(properties.entrySet(), new Predicate>() { - - @Override - public boolean apply(Entry input) { - String keyString = input.getKey().toString(); - return keyString.endsWith(".contextbuilder") || keyString.endsWith(".sync"); - } - - }), new Function, String>() { - - @Override - public String apply(Entry from) { - String keyString = from.getKey().toString(); - try { - String provider = get(Splitter.on('.').split(keyString), 0); - Class> clazz = resolveContextBuilderClass(provider, properties); - if (type.isAssignableFrom(clazz)) - return provider; - } catch (ClassNotFoundException e) { - } catch (Exception e) { - propagate(e); - } - return null; - } - - }), notNull()); - } - - @SuppressWarnings("unchecked") - public static Class> resolveContextBuilderClass(String provider, - Properties properties) throws ClassNotFoundException, IllegalArgumentException, SecurityException, - InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { - String contextBuilderClassName = properties.getProperty(provider + ".contextbuilder"); - String syncClassName = properties.getProperty(provider + ".sync"); - String asyncClassName = properties.getProperty(provider + ".async"); - if (syncClassName != null) { - checkArgument(asyncClassName != null, "please configure async class for " + syncClassName); - Class.forName(syncClassName); - Class.forName(asyncClassName); - return (Class>) (contextBuilderClassName != null ? Class - .forName(contextBuilderClassName) : RestContextBuilder.class); - } else { - checkArgument(contextBuilderClassName != null, "please configure contextbuilder class for " + provider); - return (Class>) Class.forName(contextBuilderClassName); - } - } - - public static RestContextBuilder initContextBuilder( - Class> contextBuilderClass, @Nullable Class sync, @Nullable Class async, - Properties properties) throws ClassNotFoundException, IllegalArgumentException, SecurityException, - InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { - checkArgument(properties != null, "please configure properties for " + contextBuilderClass); - try { - return (RestContextBuilder) contextBuilderClass.getConstructor(Properties.class).newInstance(properties); - } catch (NoSuchMethodException e) { - checkArgument(sync != null, "please configure sync class for " + contextBuilderClass); - checkArgument(async != null, "please configure async class for " + contextBuilderClass); - return (RestContextBuilder) contextBuilderClass.getConstructor(sync.getClass(), async.getClass(), - Properties.class).newInstance(sync, async, properties); - } - } - - @SuppressWarnings("unchecked") - public static Class resolvePropertiesBuilderClass(String providerName, Properties props) - throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, - NoSuchMethodException { - String propertiesBuilderClassName = props.getProperty(providerName + ".propertiesbuilder", null); - if (propertiesBuilderClassName != null) { - return (Class) Class.forName(propertiesBuilderClassName); - } else { - return PropertiesBuilder.class; - } - } - - public static Iterable modulesForProviderInProperties(String providerName, Properties props) { - return concat(modulesFromProperty(props, "jclouds.modules"), - modulesFromProperty(props, providerName + ".modules")); - } - - public static Iterable modulesFromProperty(Properties props, String property) { - return modulesFromCommaDelimitedString(props.getProperty(property, null)); - } - - public static Iterable modulesFromCommaDelimitedString(String moduleClasses) { - Iterable modules = ImmutableSet.of(); - if (moduleClasses != null) { - Iterable transformer = ImmutableList.copyOf(on(',').split(moduleClasses)); - modules = transform(transformer, new Function() { - - @Override - public Module apply(String from) { - try { - return (Module) Class.forName(from).newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException("error instantiating " + from, e); - } catch (IllegalAccessException e) { - throw new RuntimeException("error instantiating " + from, e); - } catch (ClassNotFoundException e) { - throw new RuntimeException("error instantiating " + from, e); - } - } - - }); - } - return modules; - } - - public static boolean isPrivateKeyCredential(Credentials credentials) { - return credentials != null - && credentials.credential != null - && (credentials.credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credentials.credential - .startsWith(Pems.PRIVATE_PKCS8_MARKER)); - } - - public static Credentials overrideCredentialsIfSupplied(Credentials defaultCredentials, - @Nullable Credentials overridingCredentials) { - if (overridingCredentials == null) - return defaultCredentials; - String identity = overridingCredentials.identity != null ? overridingCredentials.identity : checkNotNull( - defaultCredentials, "defaultCredentials").identity; - String credential = overridingCredentials.credential != null ? overridingCredentials.credential : checkNotNull( - defaultCredentials, "defaultCredentials").credential; - - return new Credentials(identity, credential); - } - - // Note this needs to be kept up-to-date with all top-level exceptions jclouds works against - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Exception returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(Class[] exceptionTypes, - Exception exception) throws Exception { - for (Class type : exceptionTypes) { - Throwable throwable = getFirstThrowableOfType(exception, type); - if (throwable != null) { - return (Exception) throwable; - } - } - for (Class propagatableExceptionType : new Class[] { IllegalStateException.class, - UnsupportedOperationException.class, IllegalArgumentException.class, AuthorizationException.class, - ResourceNotFoundException.class, HttpResponseException.class }) { - Throwable throwable = getFirstThrowableOfType(exception, propagatableExceptionType); - if (throwable != null) { - throw (Exception) throwable; - } - } - Throwables.throwCause(exception, true); - return exception; - } - -} diff --git a/core/src/test/java/org/jclouds/PerformanceTest.java b/core/src/test/java/org/jclouds/PerformanceTest.java index 820467a053..700cf3edfd 100644 --- a/core/src/test/java/org/jclouds/PerformanceTest.java +++ b/core/src/test/java/org/jclouds/PerformanceTest.java @@ -28,14 +28,16 @@ import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.jclouds.date.DateServiceTest; +import org.jclouds.date.DateService; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; /** * * @author Adrian Cole */ +@Test(groups="performance") public abstract class PerformanceTest { protected static int LOOP_COUNT = 1000; protected static int THREAD_COUNT = 1000; @@ -63,7 +65,7 @@ public abstract class PerformanceTest { * This code is heavily based on Listing 5.11 in "Java Concurrency in Practice" by Brian Goetz et * al, Addison-Wesley Professional. * - * @see {@link DateServiceTest} for example usage. + * @see {@link DateService} for example usage. * * @param performanceTestName * @param tasks diff --git a/core/src/test/java/org/jclouds/concurrent/FutureExceptionParserTest.java b/core/src/test/java/org/jclouds/concurrent/FutureExceptionParserTest.java index a1fb673c2f..c178db140a 100755 --- a/core/src/test/java/org/jclouds/concurrent/FutureExceptionParserTest.java +++ b/core/src/test/java/org/jclouds/concurrent/FutureExceptionParserTest.java @@ -19,7 +19,7 @@ package org.jclouds.concurrent; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import static org.testng.Assert.assertEquals; import java.util.concurrent.Callable; @@ -41,7 +41,7 @@ import com.google.common.util.concurrent.ListenableFuture; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "concurrent.FutureExceptionParserTest") +@Test(groups = "unit") public class FutureExceptionParserTest { ExecutorService executorService = MoreExecutors.sameThreadExecutor(); @@ -69,7 +69,7 @@ public class FutureExceptionParserTest { assertEquals(future.get(1, TimeUnit.SECONDS), "foo"); } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) private Future createFuture(final Exception exception) { ListenableFuture future = Futures.makeListenable(executorService.submit(new Callable() { diff --git a/core/src/test/java/org/jclouds/concurrent/FutureIterablesTest.java b/core/src/test/java/org/jclouds/concurrent/FutureIterablesTest.java index da4349435d..5e98999f55 100644 --- a/core/src/test/java/org/jclouds/concurrent/FutureIterablesTest.java +++ b/core/src/test/java/org/jclouds/concurrent/FutureIterablesTest.java @@ -41,7 +41,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(enabled = false, groups = "performance", sequential = true, testName = "concurrent.FutureIterablesTest") +@Test(enabled = false, groups = "performance", sequential = true) public class FutureIterablesTest { @Test(enabled = false) public void testMakeListenableDoesntSerializeFutures() throws InterruptedException, ExecutionException { diff --git a/core/src/test/java/org/jclouds/concurrent/FuturesComposePerformanceTest.java b/core/src/test/java/org/jclouds/concurrent/FuturesComposePerformanceTest.java index 1a8717fee7..4b2fd25b85 100644 --- a/core/src/test/java/org/jclouds/concurrent/FuturesComposePerformanceTest.java +++ b/core/src/test/java/org/jclouds/concurrent/FuturesComposePerformanceTest.java @@ -59,7 +59,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(enabled = false, groups = "performance", sequential = true, testName = "concurrent.ConcurrentUtilsTest") +@Test(enabled = false, groups = "performance", sequential = true) public class FuturesComposePerformanceTest { ExecutorService callableExecutor = newCachedThreadPool(); diff --git a/core/src/test/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplierTest.java b/core/src/test/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplierTest.java index 23db0cb7ac..09f30fb488 100644 --- a/core/src/test/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplierTest.java +++ b/core/src/test/java/org/jclouds/concurrent/RetryOnTimeOutExceptionSupplierTest.java @@ -39,7 +39,7 @@ import com.google.common.base.Supplier; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "concurrent.RetryOnTimeOutExceptionSupplierTest") +@Test(groups = "unit") public class RetryOnTimeOutExceptionSupplierTest { ExecutorService executorService = MoreExecutors.sameThreadExecutor(); diff --git a/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java b/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java index ce953f37e9..43428828f2 100644 --- a/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java +++ b/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java @@ -44,7 +44,7 @@ import com.google.common.util.concurrent.ListenableFuture; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "concurrent.ListenableFutureExceptionParserTest") +@Test(groups = "unit", sequential = true) public class SyncProxyTest { @Test diff --git a/core/src/test/java/org/jclouds/crypto/CryptoStreamsTest.java b/core/src/test/java/org/jclouds/crypto/CryptoStreamsTest.java index d6efdae157..50e65a8a5b 100644 --- a/core/src/test/java/org/jclouds/crypto/CryptoStreamsTest.java +++ b/core/src/test/java/org/jclouds/crypto/CryptoStreamsTest.java @@ -32,7 +32,7 @@ import com.google.common.base.Charsets; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "jclouds.CryptoStreamsTest") +@Test(groups = "unit", sequential = true) public class CryptoStreamsTest { @Test diff --git a/core/src/test/java/org/jclouds/crypto/PemsTest.java b/core/src/test/java/org/jclouds/crypto/PemsTest.java index 0edc803b6d..b5d488d7bc 100644 --- a/core/src/test/java/org/jclouds/crypto/PemsTest.java +++ b/core/src/test/java/org/jclouds/crypto/PemsTest.java @@ -36,7 +36,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "jclouds.PemsTest") +@Test(groups = "unit", sequential = true) public class PemsTest { public static final String PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\n-----END RSA PRIVATE KEY-----\n"; diff --git a/core/src/test/java/org/jclouds/date/DateServiceTest.java b/core/src/test/java/org/jclouds/date/DateServiceTest.java index a3f4921ec3..6ebb3864dd 100755 --- a/core/src/test/java/org/jclouds/date/DateServiceTest.java +++ b/core/src/test/java/org/jclouds/date/DateServiceTest.java @@ -45,7 +45,8 @@ import com.google.inject.Injector; * @author Adrian Cole * @author James Murty */ -@Test(sequential = true, timeOut = 2 * 60 * 1000, testName = "core.DateTest") +// NOTE:without testName, this will fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "DateServiceTest") public class DateServiceTest extends PerformanceTest { protected DateService dateService; @@ -67,8 +68,8 @@ public class DateServiceTest extends PerformanceTest { public final Date date; - TestData(String iso8601, String iso8601DateStringTz, String iso8601Seconds, String rfc822, - String cDateString, Date dateTime) { + TestData(String iso8601, String iso8601DateStringTz, String iso8601Seconds, String rfc822, String cDateString, + Date dateTime) { this.iso8601DateString = iso8601; this.iso8601DateStringTz = iso8601DateStringTz; this.iso8601SecondsDateString = iso8601Seconds; @@ -81,24 +82,18 @@ public class DateServiceTest extends PerformanceTest { public DateServiceTest() { // Constant time test values, each TestData item must contain matching times! testData = new TestData[] { - new TestData("2009-03-12T02:00:07.000Z", "2009-03-12T02:00:07-04:00", - "2009-03-12T02:00:07Z", "Thu, 12 Mar 2009 02:00:07 GMT", - "Thu Mar 12 02:00:07 +0000 2009", new Date(1236823207000l)), - new TestData("2009-03-12T02:00:07.000Z", "2009-03-12T02:00:07+04:00", - "2009-03-12T02:00:07Z", "Thu, 12 Mar 2009 02:00:07 GMT", - "Thu Mar 12 02:00:07 +0000 2009", new Date(1236823207000l)), - new TestData("2009-03-14T04:00:07.000Z", "2009-03-14T04:00:07Z+04:00", - "2009-03-14T04:00:07Z", "Sat, 14 Mar 2009 04:00:07 GMT", - "Thu Mar 14 04:00:07 +0000 2009", new Date(1237003207000l)), - new TestData("2009-03-16T06:00:07.000Z", "2009-03-16T06:00:07Z+04:00", - "2009-03-16T06:00:07Z", "Mon, 16 Mar 2009 06:00:07 GMT", - "Thu Mar 16 06:00:07 +0000 2009", new Date(1237183207000l)), - new TestData("2009-03-18T08:00:07.000Z", "2009-03-18T08:00:07Z+04:00", - "2009-03-18T08:00:07Z", "Wed, 18 Mar 2009 08:00:07 GMT", - "Thu Mar 18 08:00:07 +0000 2009", new Date(1237363207000l)), - new TestData("2009-03-20T10:00:07.000Z", "2009-03-20T10:00:07Z+04:00", - "2009-03-20T10:00:07Z", "Fri, 20 Mar 2009 10:00:07 GMT", - "Thu Mar 20 10:00:07 +0000 2009", new Date(1237543207000l)) }; + new TestData("2009-03-12T02:00:07.000Z", "2009-03-12T02:00:07-04:00", "2009-03-12T02:00:07Z", + "Thu, 12 Mar 2009 02:00:07 GMT", "Thu Mar 12 02:00:07 +0000 2009", new Date(1236823207000l)), + new TestData("2009-03-12T02:00:07.000Z", "2009-03-12T02:00:07+04:00", "2009-03-12T02:00:07Z", + "Thu, 12 Mar 2009 02:00:07 GMT", "Thu Mar 12 02:00:07 +0000 2009", new Date(1236823207000l)), + new TestData("2009-03-14T04:00:07.000Z", "2009-03-14T04:00:07Z+04:00", "2009-03-14T04:00:07Z", + "Sat, 14 Mar 2009 04:00:07 GMT", "Thu Mar 14 04:00:07 +0000 2009", new Date(1237003207000l)), + new TestData("2009-03-16T06:00:07.000Z", "2009-03-16T06:00:07Z+04:00", "2009-03-16T06:00:07Z", + "Mon, 16 Mar 2009 06:00:07 GMT", "Thu Mar 16 06:00:07 +0000 2009", new Date(1237183207000l)), + new TestData("2009-03-18T08:00:07.000Z", "2009-03-18T08:00:07Z+04:00", "2009-03-18T08:00:07Z", + "Wed, 18 Mar 2009 08:00:07 GMT", "Thu Mar 18 08:00:07 +0000 2009", new Date(1237363207000l)), + new TestData("2009-03-20T10:00:07.000Z", "2009-03-20T10:00:07Z+04:00", "2009-03-20T10:00:07Z", + "Fri, 20 Mar 2009 10:00:07 GMT", "Thu Mar 20 10:00:07 +0000 2009", new Date(1237543207000l)) }; } @Test @@ -106,6 +101,7 @@ public class DateServiceTest extends PerformanceTest { Date dsDate = dateService.iso8601DateParse(testData[0].iso8601DateString); assertEquals(dsDate, testData[0].date); } + @Test public void testIso8601DateParseTz() throws ExecutionException, InterruptedException { Date dsDate = dateService.iso8601SecondsDateParse(testData[0].iso8601DateStringTz); diff --git a/core/src/test/java/org/jclouds/domain/CredentialsTest.java b/core/src/test/java/org/jclouds/domain/CredentialsTest.java index 37bcede059..b7c48bd001 100644 --- a/core/src/test/java/org/jclouds/domain/CredentialsTest.java +++ b/core/src/test/java/org/jclouds/domain/CredentialsTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "compute.CredentialsTest") +@Test(groups = "unit") public class CredentialsTest { public void testAzure() { diff --git a/core/src/test/java/org/jclouds/domain/JsonBallTest.java b/core/src/test/java/org/jclouds/domain/JsonBallTest.java index 30322ba2a4..8cce91f797 100644 --- a/core/src/test/java/org/jclouds/domain/JsonBallTest.java +++ b/core/src/test/java/org/jclouds/domain/JsonBallTest.java @@ -41,7 +41,7 @@ import com.google.inject.TypeLiteral; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "jclouds.JsonBallTest") +@Test(groups = "unit") public class JsonBallTest { private ParseJson> handler; private Json mapper; diff --git a/core/src/test/java/org/jclouds/domain/JsonObjectTest.java b/core/src/test/java/org/jclouds/domain/JsonObjectTest.java index 34e50c0c5e..0b7b759fd9 100644 --- a/core/src/test/java/org/jclouds/domain/JsonObjectTest.java +++ b/core/src/test/java/org/jclouds/domain/JsonObjectTest.java @@ -42,7 +42,7 @@ import com.google.inject.TypeLiteral; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "jclouds.ObjectTest") +@Test(groups = "unit") public class JsonObjectTest { private ParseJson> handler; private Json mapper; diff --git a/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java b/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java index 4506abafb8..7ae2c63cf0 100644 --- a/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java +++ b/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java @@ -41,7 +41,8 @@ import org.jclouds.http.options.GetOptions; import org.jclouds.io.InputSuppliers; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; +import org.jclouds.util.Throwables2; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -51,9 +52,8 @@ import com.google.common.collect.Multimap; import com.google.common.io.Closeables; /** - * Tests for functionality all HttpCommandExecutorServices must express. These - * tests will operate against an in-memory http engine, so as to ensure - * end-to-end functionality works. + * Tests for functionality all HttpCommandExecutorServices must express. These tests will operate + * against an in-memory http engine, so as to ensure end-to-end functionality works. * * @author Adrian Cole */ @@ -85,6 +85,17 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base assertEquals(client.download("").trim(), XML); } + @Test(invocationCount = 5, timeOut = 5000) + public void testGetStringViaRequest() throws ExecutionException, InterruptedException, + TimeoutException, IOException { + assertEquals( + Strings2.toStringAndClose( + client.invoke( + HttpRequest.builder().method("GET") + .endpoint(URI.create("http://localhost:" + testPort + "/objects/")).build()).getPayload() + .getInput()).trim(), XML); + } + @DataProvider(name = "gets") public Object[][] createData() { return new Object[][] { { "object" }, { "/path" }, { "sp ace" }, { "unic₪de" }, { "qu?stion" } }; @@ -127,7 +138,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base // must retry directly. In this case, we are assuming lightning doesn't // strike // twice in the same spot. - if (Utils.getFirstThrowableOfType(e, IOException.class) != null) { + if (Throwables2.getFirstThrowableOfType(e, IOException.class) != null) { input = getConsitution(); assertEquals(CryptoStreams.md5Base64(InputSuppliers.of(input)), md5); } @@ -135,8 +146,8 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base } private InputStream getConsitution() { - InputStream input = context.utils().http().get( - URI.create(String.format("http://localhost:%d/%s", testPort, "101constitutions"))); + InputStream input = context.utils().http() + .get(URI.create(String.format("http://localhost:%d/%s", testPort, "101constitutions"))); return input; } @@ -167,8 +178,8 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base } /** - * Tests sending a big file to the server. Note: this is a heavy test, takes - * several minutes to finish. + * Tests sending a big file to the server. Note: this is a heavy test, takes several minutes to + * finish. * * @throws java.io.IOException */ @@ -202,8 +213,8 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base byte[] digest = digester.digest(); payload.getContentMetadata().setContentMD5(digest); Multimap headers = client.postPayloadAndReturnHeaders("", payload); - assertEquals(headers.get("x-Content-MD5"), Collections.singleton(CryptoStreams.base64Encode(InputSuppliers - .of(digest)))); + assertEquals(headers.get("x-Content-MD5"), + Collections.singleton(CryptoStreams.base64Encode(InputSuppliers.of(digest)))); payload.release(); } finally { if (os != null) @@ -241,20 +252,18 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base assertEquals(headers.get("x-Content-Disposition"), Collections.singleton("attachment; filename=photo.jpg")); payload.release(); } - + @Test(invocationCount = 5, timeOut = 5000) - public void testPostContentEncoding() throws ExecutionException, InterruptedException, TimeoutException, - IOException { + public void testPostContentEncoding() throws ExecutionException, InterruptedException, TimeoutException, IOException { Payload payload = Payloads.newStringPayload("foo"); payload.getContentMetadata().setContentEncoding("gzip"); Multimap headers = client.postPayloadAndReturnHeaders("", payload); assertEquals(headers.get("x-Content-Encoding"), Collections.singleton("gzip")); payload.release(); } - + @Test(invocationCount = 5, timeOut = 5000) - public void testPostContentLanguage() throws ExecutionException, InterruptedException, TimeoutException, - IOException { + public void testPostContentLanguage() throws ExecutionException, InterruptedException, TimeoutException, IOException { Payload payload = Payloads.newStringPayload("foo"); payload.getContentMetadata().setContentLanguage("mi, en"); Multimap headers = client.postPayloadAndReturnHeaders("", payload); diff --git a/core/src/test/java/org/jclouds/http/BaseHttpErrorHandlerTest.java b/core/src/test/java/org/jclouds/http/BaseHttpErrorHandlerTest.java index 2dc19cde7a..b22794221e 100644 --- a/core/src/test/java/org/jclouds/http/BaseHttpErrorHandlerTest.java +++ b/core/src/test/java/org/jclouds/http/BaseHttpErrorHandlerTest.java @@ -70,7 +70,7 @@ public abstract class BaseHttpErrorHandlerTest { HttpRequest request = new HttpRequest(method, uri); HttpResponse response = new HttpResponse(statusCode, message, Payloads.newStringPayload(content)); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); diff --git a/core/src/test/java/org/jclouds/http/BaseJettyTest.java b/core/src/test/java/org/jclouds/http/BaseJettyTest.java index 0a574cc437..1b7079db08 100644 --- a/core/src/test/java/org/jclouds/http/BaseJettyTest.java +++ b/core/src/test/java/org/jclouds/http/BaseJettyTest.java @@ -29,7 +29,6 @@ import static com.google.common.io.Closeables.closeQuietly; import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH; import static org.jclouds.rest.RestContextFactory.contextSpec; import static org.jclouds.rest.RestContextFactory.createContextBuilder; -import static org.jclouds.util.Utils.toStringAndClose; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -53,6 +52,7 @@ import org.jclouds.io.InputSuppliers; import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContextBuilder; import org.jclouds.rest.RestContextSpec; +import org.jclouds.util.Strings2; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Handler; import org.mortbay.jetty.Request; @@ -118,7 +118,7 @@ public abstract class BaseJettyTest { } else if (request.getMethod().equals("PUT")) { if (request.getContentLength() > 0) { response.setStatus(HttpServletResponse.SC_OK); - response.getWriter().println(toStringAndClose(request.getInputStream()) + "PUT"); + response.getWriter().println(Strings2.toStringAndClose(request.getInputStream()) + "PUT"); } else { response.sendError(500, "no content"); } @@ -194,7 +194,7 @@ public abstract class BaseJettyTest { response.setStatus(HttpServletResponse.SC_OK); String responseString = "POST"; if (request.getContentLength() < 10240) { - responseString = toStringAndClose(request.getInputStream()) + "POST"; + responseString = Strings2.toStringAndClose(request.getInputStream()) + "POST"; } else { closeQuietly(request.getInputStream()); } @@ -212,7 +212,7 @@ public abstract class BaseJettyTest { if (request.getMethod().equals("PUT")) { if (request.getContentLength() > 0) { response.setStatus(HttpServletResponse.SC_OK); - response.getWriter().println(toStringAndClose(request.getInputStream()) + "PUTREDIRECT"); + response.getWriter().println(Strings2.toStringAndClose(request.getInputStream()) + "PUTREDIRECT"); } } else if (request.getMethod().equals("POST")) { if (request.getContentLength() > 0) { @@ -310,12 +310,13 @@ public abstract class BaseJettyTest { return false; } - @SuppressWarnings("unchecked") protected boolean failIfNoContentLength(HttpServletRequest request, HttpServletResponse response) throws IOException { Multimap realHeaders = LinkedHashMultimap.create(); + @SuppressWarnings("rawtypes") Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement().toString(); + @SuppressWarnings("rawtypes") Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { realHeaders.put(header, values.nextElement().toString()); diff --git a/core/src/test/java/org/jclouds/http/HttpPropertiesBuilderTest.java b/core/src/test/java/org/jclouds/http/HttpPropertiesBuilderTest.java index 8084bc8d3d..72f4022314 100755 --- a/core/src/test/java/org/jclouds/http/HttpPropertiesBuilderTest.java +++ b/core/src/test/java/org/jclouds/http/HttpPropertiesBuilderTest.java @@ -29,7 +29,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rest.HttpPropertiesBuilderTest") +@Test(groups = "unit") public class HttpPropertiesBuilderTest { public void testBuilder() { diff --git a/core/src/test/java/org/jclouds/http/IntegrationTestAsyncClient.java b/core/src/test/java/org/jclouds/http/IntegrationTestAsyncClient.java index 98110ecb86..c80477f8d8 100644 --- a/core/src/test/java/org/jclouds/http/IntegrationTestAsyncClient.java +++ b/core/src/test/java/org/jclouds/http/IntegrationTestAsyncClient.java @@ -37,6 +37,7 @@ import javax.ws.rs.PathParam; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.options.HttpRequestOptions; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.io.Payload; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.ExceptionParser; @@ -48,7 +49,7 @@ import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.binders.BindMapToMatrixParams; import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToStringPayload; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; import com.google.common.collect.Multimap; @@ -60,7 +61,7 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adrian Cole */ public interface IntegrationTestAsyncClient { - @Target( { ElementType.METHOD }) + @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @HttpMethod("ROWDY") public @interface ROWDY { @@ -78,6 +79,8 @@ public interface IntegrationTestAsyncClient { @Path("/objects/{id}") ListenableFuture download(@PathParam("id") String id); + ListenableFuture invoke(HttpRequest request); + @GET @Path("/{path}") ListenableFuture synch(@PathParam("path") String id); @@ -111,14 +114,15 @@ public interface IntegrationTestAsyncClient { @POST @Path("/objects/{id}") ListenableFuture postAsInputStream(@PathParam("id") String id, - @BinderParam(BindToInputStreamPayload.class) String toPut); + @BinderParam(BindToInputStreamPayload.class) String toPut); static class BindToInputStreamPayload extends BindToStringPayload { @Override - public void bindToRequest(HttpRequest request, Object payload) { - super.bindToRequest(request, payload); - request.setPayload(Utils.toInputStream(payload.toString())); + public R bindToRequest(R request, Object payload) { + request = super.bindToRequest(request, payload); + request.setPayload(Strings2.toInputStream(payload.toString())); request.getPayload().getContentMetadata().setContentLength((long) payload.toString().getBytes().length); + return request; } } @@ -144,7 +148,7 @@ public interface IntegrationTestAsyncClient { @POST @Path("/objects/{id}/action/{action}") ListenableFuture action(@PathParam("id") String id, @PathParam("action") String action, - @BinderParam(BindMapToMatrixParams.class) Map options); + @BinderParam(BindMapToMatrixParams.class) Map options); @GET @Path("/objects/{id}") @@ -152,10 +156,11 @@ public interface IntegrationTestAsyncClient { ListenableFuture downloadFilter(@PathParam("id") String id, @HeaderParam("filterme") String header); static class Filter implements HttpRequestFilter { - public void filter(HttpRequest request) throws HttpException { + public HttpRequest filter(HttpRequest request) throws HttpException { if (request.getHeaders().containsKey("filterme")) { - request.getHeaders().put("test", "test"); + request = ModifyRequest.replaceHeader(request, "test", "test"); } + return request; } } diff --git a/core/src/test/java/org/jclouds/http/IntegrationTestClient.java b/core/src/test/java/org/jclouds/http/IntegrationTestClient.java index 94ead6232a..065732974b 100644 --- a/core/src/test/java/org/jclouds/http/IntegrationTestClient.java +++ b/core/src/test/java/org/jclouds/http/IntegrationTestClient.java @@ -35,35 +35,37 @@ import com.google.common.collect.Multimap; */ @Timeout(duration = 40, timeUnit = TimeUnit.SECONDS) public interface IntegrationTestClient { - String rowdy(String path); + String rowdy(String path); - boolean exists(String path); + boolean exists(String path); - String synch(String id); + String synch(String id); - String download(String id); + String download(String id); - String downloadException(String id, HttpRequestOptions options); + HttpResponse invoke(HttpRequest request); - String synchException(String id, String header); + String downloadException(String id, HttpRequestOptions options); - String upload(String id, String toPut); + String synchException(String id, String header); - String post(String id, String toPut); + String upload(String id, String toPut); - String postAsInputStream(String id, String toPut); + String post(String id, String toPut); + + String postAsInputStream(String id, String toPut); Multimap postPayloadAndReturnHeaders(String id, Payload payload); - String postJson(String id, String toPut); + String postJson(String id, String toPut); - String action(String id, String action, Map options); + String action(String id, String action, Map options); - String downloadFilter(String id, String header); + String downloadFilter(String id, String header); - String download(String id, String header); + String download(String id, String header); - String downloadAndParse(String id); + String downloadAndParse(String id); - StringBuffer newStringBuffer(); + StringBuffer newStringBuffer(); } diff --git a/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java b/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java index 24209cda92..25354b33db 100755 --- a/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java +++ b/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java @@ -36,7 +36,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "http.BasicAuthenticationTest") +@Test(groups = "unit") public class BasicAuthenticationTest { private static final String USER = "Aladdin"; @@ -45,7 +45,7 @@ public class BasicAuthenticationTest { public void testAuth() throws UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException { BasicAuthentication filter = new BasicAuthentication(USER, PASSWORD, new JCECrypto(null)); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); - filter.filter(request); + request = filter.filter(request); assertEquals(request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } diff --git a/core/src/test/java/org/jclouds/http/functions/BaseHandlerTest.java b/core/src/test/java/org/jclouds/http/functions/BaseHandlerTest.java index fd16662452..a0ad70b710 100644 --- a/core/src/test/java/org/jclouds/http/functions/BaseHandlerTest.java +++ b/core/src/test/java/org/jclouds/http/functions/BaseHandlerTest.java @@ -22,10 +22,16 @@ package org.jclouds.http.functions; import org.jclouds.http.functions.config.SaxParserModule; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; import com.google.inject.Guice; import com.google.inject.Injector; +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") public class BaseHandlerTest { protected Injector injector = null; diff --git a/core/src/test/java/org/jclouds/http/functions/ParseSaxTest.java b/core/src/test/java/org/jclouds/http/functions/ParseSaxTest.java index c1df2737f9..762f6ced96 100644 --- a/core/src/test/java/org/jclouds/http/functions/ParseSaxTest.java +++ b/core/src/test/java/org/jclouds/http/functions/ParseSaxTest.java @@ -36,6 +36,13 @@ import org.testng.annotations.Test; import org.xml.sax.Locator; import org.xml.sax.SAXParseException; +/** + * Tests behavior of {@code ParseSax} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ParseSaxTest") public class ParseSaxTest extends BaseHandlerTest { public static class TestHandler extends ParseSax.HandlerWithResult { @Override diff --git a/core/src/test/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20xTest.java b/core/src/test/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20xTest.java index 89848ffefe..96f7fcc343 100644 --- a/core/src/test/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20xTest.java +++ b/core/src/test/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20xTest.java @@ -36,7 +36,7 @@ import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payload; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.mortbay.jetty.HttpHeaders; import org.testng.annotations.Test; @@ -115,7 +115,7 @@ public class ParseURIFromListOrLocationHeaderIf20xTest { expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE)).andReturn("text/uri-list"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getInput()).andReturn(Utils.toInputStream("http://locahost")).atLeastOnce(); + expect(payload.getInput()).andReturn(Strings2.toInputStream("http://locahost")).atLeastOnce(); payload.release(); replay(payload); diff --git a/core/src/test/java/org/jclouds/http/functions/ReturnStringIf200Test.java b/core/src/test/java/org/jclouds/http/functions/ReturnStringIf200Test.java index 2a28d02c4f..fbf956d2fc 100644 --- a/core/src/test/java/org/jclouds/http/functions/ReturnStringIf200Test.java +++ b/core/src/test/java/org/jclouds/http/functions/ReturnStringIf200Test.java @@ -31,7 +31,7 @@ import java.util.concurrent.TimeoutException; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payload; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -88,7 +88,7 @@ public class ReturnStringIf200Test { expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getInput()).andReturn(Utils.toInputStream("hello")); + expect(payload.getInput()).andReturn(Strings2.toInputStream("hello")); payload.release(); replay(payload); diff --git a/core/src/test/java/org/jclouds/http/handlers/BackoffLimitedRetryHandlerTest.java b/core/src/test/java/org/jclouds/http/handlers/BackoffLimitedRetryHandlerTest.java index 005610aa8a..87835ac498 100644 --- a/core/src/test/java/org/jclouds/http/handlers/BackoffLimitedRetryHandlerTest.java +++ b/core/src/test/java/org/jclouds/http/handlers/BackoffLimitedRetryHandlerTest.java @@ -55,7 +55,7 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.sun.jersey.api.uri.UriBuilderImpl; -@Test(groups = "unit", testName = "core.BackoffLimitedRetryHandler") +@Test(groups = "unit") public class BackoffLimitedRetryHandlerTest { BackoffLimitedRetryHandler handler = new BackoffLimitedRetryHandler(); diff --git a/core/src/test/java/org/jclouds/http/handlers/DelegatingErrorHandlerTest.java b/core/src/test/java/org/jclouds/http/handlers/DelegatingErrorHandlerTest.java index cc2f85029b..38de6d4a39 100644 --- a/core/src/test/java/org/jclouds/http/handlers/DelegatingErrorHandlerTest.java +++ b/core/src/test/java/org/jclouds/http/handlers/DelegatingErrorHandlerTest.java @@ -32,7 +32,7 @@ import com.google.inject.Guice; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "core.DelegatingErrorHandlerTest") +@Test(groups = "unit") public class DelegatingErrorHandlerTest { public void testDefaultInjection() { diff --git a/core/src/test/java/org/jclouds/http/handlers/RedirectionRetryHandlerTest.java b/core/src/test/java/org/jclouds/http/handlers/RedirectionRetryHandlerTest.java index f7698718bd..129a60b9bb 100644 --- a/core/src/test/java/org/jclouds/http/handlers/RedirectionRetryHandlerTest.java +++ b/core/src/test/java/org/jclouds/http/handlers/RedirectionRetryHandlerTest.java @@ -23,7 +23,6 @@ import static org.easymock.EasyMock.expect; import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; -import static org.testng.Assert.assertEquals; import java.net.URI; @@ -44,7 +43,7 @@ import com.google.inject.Guice; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "http.RedirectionRetryHandlerTest") +@Test(groups = "unit") public class RedirectionRetryHandlerTest { @Test @@ -157,7 +156,8 @@ public class RedirectionRetryHandlerTest { HttpCommand command = createMock(HttpCommand.class); expect(command.incrementRedirectCount()).andReturn(0); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request); + command.setCurrentRequest(expected); replay(command); @@ -165,7 +165,6 @@ public class RedirectionRetryHandlerTest { RedirectionRetryHandler.class); assert retry.shouldRetryRequest(command, response); - assertEquals(command.getRequest(), expected); verify(command); } } diff --git a/core/src/test/java/org/jclouds/http/internal/WireLiveTest.java b/core/src/test/java/org/jclouds/http/internal/WireLiveTest.java index 423dfc6474..037b5e695c 100644 --- a/core/src/test/java/org/jclouds/http/internal/WireLiveTest.java +++ b/core/src/test/java/org/jclouds/http/internal/WireLiveTest.java @@ -28,6 +28,7 @@ import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; +import java.net.UnknownHostException; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -41,7 +42,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "core.WireLiveTest") +@Test(groups = "live", sequential = true) public class WireLiveTest { private static final String sysHttpStreamUrl = System.getProperty("jclouds.wire.httpstream.url"); @@ -134,14 +135,18 @@ public class WireLiveTest { @Test(groups = "live") public void testRemoteInputStream() throws Exception { - URL url = new URL(checkNotNull(sysHttpStreamUrl, "sysHttpStreamUrl")); - URLConnection connection = url.openConnection(); - HttpWire wire = setUp(); - final InputStream in = wire.input(connection.getInputStream()); - byte[] compare = CryptoStreams.md5(InputSuppliers.of(in)); - Thread.sleep(100); - assertEquals(CryptoStreams.hex(compare), checkNotNull(sysHttpStreamMd5, sysHttpStreamMd5)); - assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484); + try { + URL url = new URL(checkNotNull(sysHttpStreamUrl, "sysHttpStreamUrl")); + URLConnection connection = url.openConnection(); + HttpWire wire = setUp(); + final InputStream in = wire.input(connection.getInputStream()); + byte[] compare = CryptoStreams.md5(InputSuppliers.of(in)); + Thread.sleep(100); + assertEquals(CryptoStreams.hex(compare), checkNotNull(sysHttpStreamMd5, sysHttpStreamMd5)); + assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484); + } catch (UnknownHostException e) { + // probably in offline mode + } } @Test(groups = "live", enabled = false) @@ -155,14 +160,18 @@ public class WireLiveTest { @Test(groups = "live") public void testRemoteInputStreamSynch() throws Exception { - URL url = new URL(checkNotNull(sysHttpStreamUrl, "sysHttpStreamUrl")); - URLConnection connection = url.openConnection(); - HttpWire wire = setUpSynch(); - final InputStream in = wire.input(connection.getInputStream()); - byte[] compare = CryptoStreams.md5(InputSuppliers.of(in)); - Thread.sleep(100); - assertEquals(CryptoStreams.hex(compare), checkNotNull(sysHttpStreamMd5, sysHttpStreamMd5)); - assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484); + try { + URL url = new URL(checkNotNull(sysHttpStreamUrl, "sysHttpStreamUrl")); + URLConnection connection = url.openConnection(); + HttpWire wire = setUpSynch(); + final InputStream in = wire.input(connection.getInputStream()); + byte[] compare = CryptoStreams.md5(InputSuppliers.of(in)); + Thread.sleep(100); + assertEquals(CryptoStreams.hex(compare), checkNotNull(sysHttpStreamMd5, sysHttpStreamMd5)); + assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484); + } catch (UnknownHostException e) { + // probably in offline mode + } } } diff --git a/core/src/test/java/org/jclouds/http/internal/WireTest.java b/core/src/test/java/org/jclouds/http/internal/WireTest.java index cefdcdaadb..8e721aea27 100644 --- a/core/src/test/java/org/jclouds/http/internal/WireTest.java +++ b/core/src/test/java/org/jclouds/http/internal/WireTest.java @@ -25,14 +25,14 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; /** * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "core.WireTest") +@Test(groups = "unit", sequential = true) public class WireTest { class BufferLogger implements Logger { @@ -103,7 +103,7 @@ public class WireTest { public void testInputInputStream() throws Exception { HttpWire wire = setUp(); InputStream in = wire.input(new ByteArrayInputStream("foo".getBytes())); - String compare = Utils.toStringAndClose(in); + String compare = Strings2.toStringAndClose(in); Thread.sleep(100); assertEquals(compare, "foo"); assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), "<< \"foo\""); @@ -112,7 +112,7 @@ public class WireTest { public void testInputInputStreamSynch() throws Exception { HttpWire wire = setUpSynch(); InputStream in = wire.input(new ByteArrayInputStream("foo".getBytes())); - String compare = Utils.toStringAndClose(in); + String compare = Strings2.toStringAndClose(in); assertEquals(compare, "foo"); assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), "<< \"foo\""); } @@ -120,7 +120,7 @@ public class WireTest { public void testOutputInputStream() throws Exception { HttpWire wire = setUp(); InputStream in = wire.output(new ByteArrayInputStream("foo".getBytes())); - String compare = Utils.toStringAndClose(in); + String compare = Strings2.toStringAndClose(in); Thread.sleep(100); assertEquals(compare, "foo"); assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), ">> \"foo\""); diff --git a/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java b/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java index 9518cd850b..14916b2721 100644 --- a/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java +++ b/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java @@ -41,7 +41,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "http.GetOptionsTest") +@Test(groups = "unit") public class GetOptionsTest { private String etag; diff --git a/core/src/test/java/org/jclouds/http/utils/ModifyRequestTest.java b/core/src/test/java/org/jclouds/http/utils/ModifyRequestTest.java new file mode 100644 index 0000000000..8d950da381 --- /dev/null +++ b/core/src/test/java/org/jclouds/http/utils/ModifyRequestTest.java @@ -0,0 +1,134 @@ +/** + * + * 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.http.utils; + +import static org.jclouds.http.utils.ModifyRequest.parseQueryToMap; +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.http.HttpRequest; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Iterables; +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.Multimap; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ModifyRequestTest { + + public void testEndpoint() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + assertEquals(ModifyRequest.endpoint(request, URI.create("http://bar")), HttpRequest.builder().method("GET") + .endpoint(URI.create("http://bar")).build()); + } + + public void testReplaceHeader() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap.of("foo", "bar")).build(); + + assertEquals( + ModifyRequest.replaceHeader(request, "foo", "baz"), + HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap.of("foo", "baz")).build()); + } + + public void testRemoveHeader() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap.of("foo", "bar")).build(); + + assertEquals(ModifyRequest.removeHeader(request, "foo"), + HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build()); + } + + public void testReplaceHeaders() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap.of("foo", "bar", "rabbit", "tree")).build(); + + assertEquals( + ModifyRequest.replaceHeaders(request, + ImmutableMultimap.of("foo", "bar", "rabbit", "robot", "robert", "baz")), + HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap.of("foo", "bar", "rabbit", "robot", "robert", "baz")).build()); + } + + public void testPutHeadersAddsAnotherValue() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap.of("foo", "bar")).build(); + + assertEquals( + ModifyRequest.putHeaders(request, ImmutableMultimap.of("foo", "baz")), + HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .headers(ImmutableMultimap. builder().put("foo", "bar").put("foo", "baz").build()) + .build()); + } + + public void testPutFormParamsAddsAnotherValue() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")) + .payload(Payloads.newStringPayload("foo=bar")).build(); + Payload payload = Payloads.newStringPayload("foo=bar&foo=baz"); + payload.getContentMetadata().setContentType(MediaType.APPLICATION_FORM_URLENCODED); + assertEquals(ModifyRequest.putFormParams(request, ImmutableMultimap.of("foo", "baz")), HttpRequest.builder() + .method("GET").endpoint(URI.create("http://foo")).payload(payload).build()); + } + + public void testParseBase64InForm() { + Multimap expects = LinkedListMultimap.create(); + expects.put("Version", "2010-06-15"); + expects.put("Action", "ModifyInstanceAttribute"); + expects.put("Attribute", "userData"); + expects.put("Value", "dGVzdA=="); + expects.put("InstanceId", "1"); + assertEquals( + expects, + parseQueryToMap("Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=userData&Value=dGVzdA%3D%3D&InstanceId=1")); + } + + @Test + public void testParseQueryToMapSingleParam() { + Multimap parsedMap = parseQueryToMap("v=1.3"); + assert parsedMap.keySet().size() == 1 : "Expected 1 key, found: " + parsedMap.keySet().size(); + assert parsedMap.keySet().contains("v") : "Expected v to be a part of the keys"; + String valueForV = Iterables.getOnlyElement(parsedMap.get("v")); + assert valueForV.equals("1.3") : "Expected the value for 'v' to be '1.3', found: " + valueForV; + } + + @Test + public void testParseQueryToMapMultiParam() { + Multimap parsedMap = parseQueryToMap("v=1.3&sig=123"); + assert parsedMap.keySet().size() == 2 : "Expected 2 keys, found: " + parsedMap.keySet().size(); + assert parsedMap.keySet().contains("v") : "Expected v to be a part of the keys"; + assert parsedMap.keySet().contains("sig") : "Expected sig to be a part of the keys"; + String valueForV = Iterables.getOnlyElement(parsedMap.get("v")); + assert valueForV.equals("1.3") : "Expected the value for 'v' to be '1.3', found: " + valueForV; + String valueForSig = Iterables.getOnlyElement(parsedMap.get("sig")); + assert valueForSig.equals("123") : "Expected the value for 'v' to be '123', found: " + valueForSig; + } + +} diff --git a/core/src/test/java/org/jclouds/io/CryptoTest.java b/core/src/test/java/org/jclouds/io/CryptoTest.java index 1ed72ab30c..e16c98f709 100644 --- a/core/src/test/java/org/jclouds/io/CryptoTest.java +++ b/core/src/test/java/org/jclouds/io/CryptoTest.java @@ -46,7 +46,8 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "performance", sequential = true, testName = "jclouds.CryptoTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "CryptoTest") public class CryptoTest extends PerformanceTest { protected Crypto crypto; diff --git a/core/src/test/java/org/jclouds/io/payloads/MultipartFormTest.java b/core/src/test/java/org/jclouds/io/payloads/MultipartFormTest.java index 6e8e2a088f..115b83f9aa 100644 --- a/core/src/test/java/org/jclouds/io/payloads/MultipartFormTest.java +++ b/core/src/test/java/org/jclouds/io/payloads/MultipartFormTest.java @@ -33,7 +33,7 @@ import javax.ws.rs.core.MediaType; import org.jclouds.io.Payloads; import org.jclouds.io.payloads.Part.PartOptions; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; /** @@ -55,7 +55,7 @@ public class MultipartFormTest { MultipartForm multipartForm = new MultipartForm(boundary, newPart("hello")); - assertEquals(Utils.toStringAndClose(multipartForm.getInput()), expects); + assertEquals(Strings2.toStringAndClose(multipartForm.getInput()), expects); assertEquals(multipartForm.getContentMetadata().getContentLength(), new Long(199)); } @@ -120,11 +120,11 @@ public class MultipartFormTest { MultipartForm multipartForm = new MultipartForm(boundary, newPart("hello"), newPart("goodbye")); - assertEquals(Utils.toStringAndClose(multipartForm.getInput()), expects); + assertEquals(Strings2.toStringAndClose(multipartForm.getInput()), expects); // test repeatable assert multipartForm.isRepeatable(); - assertEquals(Utils.toStringAndClose(multipartForm.getInput()), expects); + assertEquals(Strings2.toStringAndClose(multipartForm.getInput()), expects); assertEquals(multipartForm.getContentMetadata().getContentLength(), new Long(352)); } diff --git a/core/src/test/java/org/jclouds/predicates/RetryablePredicateTest.java b/core/src/test/java/org/jclouds/predicates/RetryablePredicateTest.java index 9ede87b833..6a7f2c0b66 100644 --- a/core/src/test/java/org/jclouds/predicates/RetryablePredicateTest.java +++ b/core/src/test/java/org/jclouds/predicates/RetryablePredicateTest.java @@ -32,7 +32,7 @@ import com.google.common.base.Predicates; * @author Adrian Cole * */ -@Test(groups = "unit", sequential = true, testName = "jclouds.RetryablePredicateTest") +@Test(groups = "unit", sequential = true) public class RetryablePredicateTest { @Test diff --git a/core/src/test/java/org/jclouds/rest/BaseRestClientTest.java b/core/src/test/java/org/jclouds/rest/BaseRestClientTest.java index df6dc40983..824b0d1b43 100644 --- a/core/src/test/java/org/jclouds/rest/BaseRestClientTest.java +++ b/core/src/test/java/org/jclouds/rest/BaseRestClientTest.java @@ -22,7 +22,6 @@ package org.jclouds.rest; import static com.google.common.base.Throwables.propagate; import static org.easymock.classextension.EasyMock.createMock; import static org.jclouds.http.HttpUtils.sortAndConcatHeadersIntoString; -import static org.jclouds.util.Utils.toStringAndClose; import static org.mortbay.jetty.HttpHeaders.TRANSFER_ENCODING; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; @@ -45,11 +44,18 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.io.MutableContentMetadata; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.jclouds.util.Strings2; +import org.testng.annotations.Test; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.name.Names; +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") public abstract class BaseRestClientTest { protected Injector injector; @@ -71,8 +77,10 @@ public abstract class BaseRestClientTest { @Override protected void configure() { - bind(ExecutorService.class).annotatedWith(Names.named(Constants.PROPERTY_USER_THREADS)).toInstance(MoreExecutors.sameThreadExecutor()); - bind(ExecutorService.class).annotatedWith(Names.named(Constants.PROPERTY_IO_WORKER_THREADS)).toInstance(MoreExecutors.sameThreadExecutor()); + bind(ExecutorService.class).annotatedWith(Names.named(Constants.PROPERTY_USER_THREADS)).toInstance( + MoreExecutors.sameThreadExecutor()); + bind(ExecutorService.class).annotatedWith(Names.named(Constants.PROPERTY_IO_WORKER_THREADS)).toInstance( + MoreExecutors.sameThreadExecutor()); bind(TransformingHttpCommandExecutorService.class).toInstance(mock); } } @@ -88,7 +96,7 @@ public abstract class BaseRestClientTest { } else { String payload = null; try { - payload = toStringAndClose(request.getPayload().getInput()); + payload = Strings2.toStringAndClose(request.getPayload().getInput()); } catch (IOException e) { propagate(e); } @@ -110,8 +118,7 @@ public abstract class BaseRestClientTest { assertEquals(md.getContentLength(), length); } else { assertEquals(request.getFirstHeaderOrNull(TRANSFER_ENCODING), "chunked"); - assert md.getContentLength() == null - || md.getContentLength().equals(length); + assert md.getContentLength() == null || md.getContentLength().equals(length); } assertEquals(md.getContentType(), contentType); assertEquals(md.getContentDisposition(), contentDispositon); @@ -131,11 +138,15 @@ public abstract class BaseRestClientTest { protected void assertExceptionParserClassEquals(Method method, @Nullable Class parserClass) { if (parserClass == null) - assertEquals(RestAnnotationProcessor.createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(injector, - method).getClass(), MapHttp4xxCodesToExceptions.class); + assertEquals( + RestAnnotationProcessor + .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(injector, method).getClass(), + MapHttp4xxCodesToExceptions.class); else - assertEquals(RestAnnotationProcessor.createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(injector, - method).getClass(), parserClass); + assertEquals( + RestAnnotationProcessor + .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(injector, method).getClass(), + parserClass); } protected void assertSaxResponseParserClassEquals(Method method, @Nullable Class parserClass) { diff --git a/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java b/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java index cdf0fa1f4c..603cffdd3f 100755 --- a/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java +++ b/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java @@ -19,7 +19,6 @@ package org.jclouds.rest; -import static org.jclouds.util.Utils.toStringAndClose; import static org.testng.Assert.assertEquals; import java.io.ByteArrayInputStream; @@ -34,6 +33,7 @@ import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; import org.jclouds.rest.config.CredentialStoreModule; import org.jclouds.rest.config.CredentialStoreModule.CopyInputStreamInputSupplierMap; +import org.jclouds.util.Strings2; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -47,7 +47,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "rest.CredentialStoreModuleTest") +@Test(groups = "unit", sequential = true) public class CredentialStoreModuleTest { Json json = createInjector().getInstance(Json.class); @@ -157,7 +157,7 @@ public class CredentialStoreModuleTest { protected void checkToJson(Map map, String key, String identity, String credential) throws IOException { - assertEquals(toStringAndClose(map.get(key)), json.toJson(new Credentials(identity, credential))); + assertEquals(Strings2.toStringAndClose(map.get(key)), json.toJson(new Credentials(identity, credential))); } protected void put(Map map, Map store, String key, String identity, diff --git a/core/src/test/java/org/jclouds/rest/InputParamValidatorTest.java b/core/src/test/java/org/jclouds/rest/InputParamValidatorTest.java index 327e80d89a..93af2dc92a 100644 --- a/core/src/test/java/org/jclouds/rest/InputParamValidatorTest.java +++ b/core/src/test/java/org/jclouds/rest/InputParamValidatorTest.java @@ -26,7 +26,6 @@ import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; import javax.ws.rs.POST; -import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.jclouds.concurrent.Timeout; @@ -45,21 +44,19 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.util.Types; -@Test(groups = "unit", testName = "rest.InputParamValidator") +@Test(groups = "unit") public class InputParamValidatorTest { @Timeout(duration = 1000, timeUnit = TimeUnit.SECONDS) @SkipEncoding('/') class InputParamValidatorForm { @POST - @Path("") - @ParamValidators( { AllLowerCaseValidator.class }) + @ParamValidators( { AllLowerCaseValidator.class }) public void allParamsValidated(@PathParam("param1") String param1, @PathParam("param2") String param2) { } @POST - @Path("") - public void oneParamValidated(@PathParam("param1") String param1, + public void oneParamValidated(@PathParam("param1") String param1, @ParamValidators( { AllLowerCaseValidator.class }) @PathParam("param2") String param2) { } } diff --git a/core/src/test/java/org/jclouds/rest/RestClientTest.java b/core/src/test/java/org/jclouds/rest/RestClientTest.java index 44f22d9beb..9fbf381e36 100644 --- a/core/src/test/java/org/jclouds/rest/RestClientTest.java +++ b/core/src/test/java/org/jclouds/rest/RestClientTest.java @@ -29,6 +29,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.logging.config.NullLoggingModule; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; import com.google.inject.Binder; @@ -36,6 +37,11 @@ import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.TypeLiteral; +/** + * + * @author Adrian Cole + */ +@Test(groups = "unit") public abstract class RestClientTest extends BaseRestClientTest { protected RestAnnotationProcessor processor; @@ -61,8 +67,8 @@ public abstract class RestClientTest extends BaseRestClientTest { protected void setupFactory() throws IOException { RestContextSpec contextSpec = createContextSpec(); injector = createContextBuilder(contextSpec, - ImmutableSet.of(new MockModule(), new NullLoggingModule(), createModule()), - getProperties()).buildInjector(); + ImmutableSet.of(new MockModule(), new NullLoggingModule(), createModule()), getProperties()) + .buildInjector(); parserFactory = injector.getInstance(ParseSax.Factory.class); processor = injector.getInstance(Key.get(createTypeLiteral())); } diff --git a/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java b/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java index 0cb8ae6c41..6fcf684a83 100755 --- a/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java +++ b/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java @@ -45,7 +45,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rest.RestContextBuilderTest") +@Test(groups = "unit") public class RestContextBuilderTest { @ConfiguresHttpCommandExecutorService diff --git a/core/src/test/java/org/jclouds/rest/RestContextFactoryTest.java b/core/src/test/java/org/jclouds/rest/RestContextFactoryTest.java index 63d71a4a78..292377bcb4 100644 --- a/core/src/test/java/org/jclouds/rest/RestContextFactoryTest.java +++ b/core/src/test/java/org/jclouds/rest/RestContextFactoryTest.java @@ -47,7 +47,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rest.RestContextFactoryTest") +@Test(groups = "unit") public class RestContextFactoryTest { private static final String provider = "test"; @@ -98,6 +98,7 @@ public class RestContextFactoryTest { @SuppressWarnings("unchecked") public void testBuilderPropertiesWithContextBuilder() { + @SuppressWarnings("rawtypes") RestContextSpec contextSpec = contextSpec(provider, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class, (Class) IntegrationTestContextBuilder.class, Collections.EMPTY_LIST); @@ -118,6 +119,7 @@ public class RestContextFactoryTest { @SuppressWarnings("unchecked") public void testBuilderPropertiesWithModule() { + @SuppressWarnings("rawtypes") RestContextSpec contextSpec = contextSpec(provider, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class, (Class) IntegrationTestContextBuilder.class, Collections. singleton(new A())); @@ -138,6 +140,7 @@ public class RestContextFactoryTest { @SuppressWarnings("unchecked") public void testBuilderPropertiesWithModules() { + @SuppressWarnings("rawtypes") RestContextSpec contextSpec = contextSpec(provider, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class, (Class) IntegrationTestContextBuilder.class, Arrays. asList(new A(), new B())); @@ -238,7 +241,7 @@ public class RestContextFactoryTest { @SuppressWarnings("unchecked") @Test(expectedExceptions = IllegalArgumentException.class) public void testBuilderPropertiesWithWrongConfig() { - @SuppressWarnings("unused") + @SuppressWarnings({ "unused", "rawtypes" }) RestContextSpec contextSpec = contextSpec(provider, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, (Class) IntegrationTestContextBuilder.class, (Class) PropertiesBuilder.class, Collections.EMPTY_LIST); diff --git a/core/src/test/java/org/jclouds/rest/binders/BindMapToMatrixParamsTest.java b/core/src/test/java/org/jclouds/rest/binders/BindMapToMatrixParamsTest.java index 8c1de1f3c7..71dd5a3649 100644 --- a/core/src/test/java/org/jclouds/rest/binders/BindMapToMatrixParamsTest.java +++ b/core/src/test/java/org/jclouds/rest/binders/BindMapToMatrixParamsTest.java @@ -19,10 +19,7 @@ package org.jclouds.rest.binders; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; +import static org.testng.Assert.assertEquals; import java.io.File; import java.net.URI; @@ -32,7 +29,6 @@ import javax.ws.rs.HttpMethod; import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpRequest; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; @@ -43,19 +39,13 @@ import com.sun.jersey.api.uri.UriBuilderImpl; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rest.BindMapToMatrixParamsTest") +@Test(groups = "unit") public class BindMapToMatrixParamsTest { @Test public void testCorrect() throws SecurityException, NoSuchMethodException { - HttpRequest request = createMock(HttpRequest.class); - expect(request.getEndpoint()).andReturn(URI.create("http://momma/")); - request.setEndpoint(URI.create("http://momma/;imageName=foo")); - expect(request.getEndpoint()).andReturn(URI.create("http://momma/;imageName=foo")); - request.setEndpoint(URI.create("http://momma/;imageName=foo;serverId=2")); - - replay(request); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); BindMapToMatrixParams binder = new BindMapToMatrixParams(new Provider() { @Override @@ -65,9 +55,8 @@ public class BindMapToMatrixParamsTest { }); - binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")); - - verify(request); + assertEquals(binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")), HttpRequest + .builder().method("GET").endpoint(URI.create("http://momma/;imageName=foo;serverId=2")).build()); } @@ -81,7 +70,7 @@ public class BindMapToMatrixParamsTest { @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToMatrixParams binder = new BindMapToMatrixParams(null); - GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); binder.bindToRequest(request, null); } } 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 b0bf75a07a..64c89a1da7 100755 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -33,7 +33,6 @@ import static org.jclouds.io.Payloads.newInputStreamPayload; import static org.jclouds.io.Payloads.newStringPayload; import static org.jclouds.rest.RestContextFactory.contextSpec; import static org.jclouds.rest.RestContextFactory.createContextBuilder; -import static org.jclouds.util.Utils.toInputStream; import static org.testng.Assert.assertEquals; import java.io.File; @@ -134,6 +133,7 @@ import org.jclouds.rest.binders.BindMapToMatrixParams; import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToStringPayload; import org.jclouds.rest.config.RestClientModule; +import org.jclouds.util.Strings2; import org.mortbay.jetty.HttpHeaders; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -157,11 +157,12 @@ import com.google.inject.Module; import com.sun.jersey.api.uri.UriBuilderImpl; /** - * Tests behavior of {@code RestAnnotationProcessorTest} + * Tests behavior of {@code RestAnnotationProcessor} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "jclouds.RestAnnotationProcessorTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "RestAnnotationProcessorTest") public class RestAnnotationProcessorTest extends BaseRestClientTest { @RequiresHttp @@ -245,7 +246,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Override public boolean matches(Object arg) { - return ((HttpCommand) arg).getRequest().getRequestLine().equals(requestLine); + return ((HttpCommand) arg).getCurrentRequest().getRequestLine().equals(requestLine); } }); @@ -368,21 +369,17 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public interface TestPayloadParamVarargs { @POST - @Path("") - public void varargs(HttpRequestOptions... options); + public void varargs(HttpRequestOptions... options); @POST - @Path("") - public void post(HttpRequestOptions options); + public void post(HttpRequestOptions options); @POST - @Path("") - @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Produces(MediaType.APPLICATION_OCTET_STREAM) public void post(); @POST - @Path("") - @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Produces(MediaType.APPLICATION_OCTET_STREAM) public void post(Payload payload); } @@ -448,8 +445,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public class TestCustomMethod { @FOO - @Path("") - public void foo() { + public void foo() { } } @@ -467,8 +463,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public class TestOverridden implements Parent { @POST - @Path("") - public void foo() { + public void foo() { } } @@ -484,13 +479,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST @Endpoint(Localhost2.class) - @Path("") - public void foo() { + public void foo() { } @POST - @Path("") - public void foo(@EndpointParam URI endpoint) { + public void foo(@EndpointParam URI endpoint) { } } @@ -515,12 +508,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public interface TestPost { @POST - @Path("") - void post(@Nullable @BinderParam(BindToStringPayload.class) String content); + void post(@Nullable @BinderParam(BindToStringPayload.class) String content); @POST - @Path("") - public void postAsJson(@BinderParam(BindToJsonPayload.class) String content); + public void postAsJson(@BinderParam(BindToJsonPayload.class) String content); @POST @Path("/{foo}") @@ -568,11 +559,14 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { 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) { + @Override + public R bindToRequest(R request, Map postParams) { request.setPayload(postParams.get("fooble")); + return request; } - public void bindToRequest(HttpRequest request, Object toBind) { + @Override + public R bindToRequest(R request, Object toBind) { throw new RuntimeException("this shouldn't be used in POST"); } }); @@ -600,25 +594,20 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { static interface TestMultipartForm { @POST - @Path("") - void withStringPart(@PartParam(name = "fooble") String path); + void withStringPart(@PartParam(name = "fooble") String path); @POST - @Path("") - void withParamStringPart(@FormParam("name") String name, @PartParam(name = "file") String path); + void withParamStringPart(@FormParam("name") String name, @PartParam(name = "file") String path); @POST - @Path("") - void withParamFilePart(@FormParam("name") String name, @PartParam(name = "file") File path); + void withParamFilePart(@FormParam("name") String name, @PartParam(name = "file") File path); @POST - @Path("") - void withParamFileBinaryPart(@FormParam("name") String name, + void withParamFileBinaryPart(@FormParam("name") String name, @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path); @POST - @Path("") - void withParamByteArrayBinaryPart( + void withParamByteArrayBinaryPart( @FormParam("name") String name, @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content); } @@ -945,29 +934,31 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } static class TestRequestFilter1 implements HttpRequestFilter { - public void filter(HttpRequest request) throws HttpException { + public HttpRequest filter(HttpRequest request) throws HttpException { + return request; } } static class TestRequestFilter2 implements HttpRequestFilter { - public void filter(HttpRequest request) throws HttpException { + public HttpRequest filter(HttpRequest request) throws HttpException { + return request; } } @RequestFilters(TestRequestFilter1.class) - static class TestRequestFilter { + static interface TestRequestFilter { @GET - @Path("") - @RequestFilters(TestRequestFilter2.class) - public void get() { - } + @RequestFilters(TestRequestFilter2.class) + public void get(); @GET - @Path("") + @OverrideRequestFilters + @RequestFilters(TestRequestFilter2.class) + public void getOverride(); + @OverrideRequestFilters @RequestFilters(TestRequestFilter2.class) - public void getOverride() { - } + public void getOverride(HttpRequest request); } @Test @@ -986,6 +977,14 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class); } + public void testRequestFilterOverrideOnRequest() throws SecurityException, NoSuchMethodException { + Method method = TestRequestFilter.class.getMethod("getOverride", HttpRequest.class); + HttpRequest request = factory(TestRequestFilter.class).createRequest(method, + HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build()); + assertEquals(request.getFilters().size(), 1); + assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class); + } + @SkipEncoding('/') public class TestEncoding { @GET @@ -1428,47 +1427,37 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public interface TestTransformers { @GET - @Path("") - int noTransformer(); + int noTransformer(); @GET - @Path("") - @ResponseParser(ReturnStringIf2xx.class) + @ResponseParser(ReturnStringIf2xx.class) void oneTransformer(); @GET - @Path("") - @ResponseParser(ReturnStringIf200Context.class) + @ResponseParser(ReturnStringIf200Context.class) void oneTransformerWithContext(); @GET - @Path("") - InputStream inputStream(); + InputStream inputStream(); @GET - @Path("") - ListenableFuture futureInputStream(); + ListenableFuture futureInputStream(); @GET - @Path("") - URI uri(); + URI uri(); @GET - @Path("") - ListenableFuture futureUri(); + ListenableFuture futureUri(); @PUT - @Path("") - ListenableFuture put(Payload payload); + ListenableFuture put(Payload payload); @PUT - @Path("") - @Headers(keys = "Transfer-Encoding", values = "chunked") + @Headers(keys = "Transfer-Encoding", values = "chunked") ListenableFuture putXfer(Payload payload); @PUT - @Path("") - ListenableFuture put(PayloadEnclosing payload); + ListenableFuture put(PayloadEnclosing payload); } public void testPutPayloadEnclosing() throws SecurityException, NoSuchMethodException, IOException { @@ -1494,7 +1483,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { 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(Strings2.toInputStream("whoops"))); calculateMD5(payloadEnclosing, crypto.md5()); HttpRequest request = factory(TestQuery.class).createRequest(method, payloadEnclosing); @@ -1562,7 +1552,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public void testPutInputStreamPayload() throws SecurityException, NoSuchMethodException, IOException { - Payload payload = newInputStreamPayload(toInputStream("whoops")); + Payload payload = newInputStreamPayload(Strings2.toInputStream("whoops")); payload.getContentMetadata().setContentLength((long) "whoops".length()); Method method = TestTransformers.class.getMethod("put", Payload.class); HttpRequest request = factory(TestQuery.class).createRequest(method, payload); @@ -1613,7 +1603,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertEquals(transformer, ParseURIFromListOrLocationHeaderIf20x.class); } - public static class ReturnStringIf200Context extends ReturnStringIf2xx implements InvocationContext { + public static class ReturnStringIf200Context extends ReturnStringIf2xx implements + InvocationContext { public HttpRequest request; @@ -1634,8 +1625,9 @@ 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 = GeneratedHttpRequest. builder().method("GET") + .endpoint(URI.create("http://localhost")).declaring(TestTransformers.class).javaMethod(method) + .args(new Object[] {}).build(); Function transformer = processor.createResponseParser(method, request); assertEquals(transformer.getClass(), ReturnStringIf200Context.class); assertEquals(((ReturnStringIf200Context) transformer).request, request); @@ -1975,8 +1967,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public interface TestPayload { @PUT - @Path("") - public void put(@BinderParam(BindToStringPayload.class) String content); + public void put(@BinderParam(BindToStringPayload.class) String content); @PUT @Path("/{foo}") @@ -1984,8 +1975,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @BinderParam(BindToStringPayload.class) String content); @PUT - @Path("") - public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1, + public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1, @BinderParam(BindToStringPayload.class) String payload2); } diff --git a/core/src/test/java/org/jclouds/util/CredentialUtilsTest.java b/core/src/test/java/org/jclouds/util/CredentialUtilsTest.java new file mode 100644 index 0000000000..7cdfe8ad07 --- /dev/null +++ b/core/src/test/java/org/jclouds/util/CredentialUtilsTest.java @@ -0,0 +1,61 @@ +/** + * + * 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.util; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.domain.Credentials; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class CredentialUtilsTest { + + public void testOverridingCredentialsWhenOverridingIsNull() { + Credentials defaultCredentials = new Credentials("foo", "bar"); + Credentials overridingCredentials = null; + assertEquals(CredentialUtils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), + defaultCredentials); + } + + public void testOverridingCredentialsWhenOverridingLoginIsNull() { + Credentials defaultCredentials = new Credentials("foo", "bar"); + Credentials overridingCredentials = new Credentials(null, "baz"); + assertEquals(CredentialUtils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), + new Credentials("foo", "baz")); + } + + public void testOverridingCredentialsWhenOverridingCredentialIsNull() { + Credentials defaultCredentials = new Credentials("foo", "bar"); + Credentials overridingCredentials = new Credentials("fooble", null); + assertEquals(CredentialUtils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), + new Credentials("fooble", "bar")); + } + + public void testOverridingCredentialsWhenOverridingCredentialsAreNull() { + Credentials defaultCredentials = new Credentials("foo", "bar"); + Credentials overridingCredentials = new Credentials(null, null); + assertEquals(CredentialUtils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), + new Credentials("foo", "bar")); + } + +} diff --git a/core/src/test/java/org/jclouds/util/HttpUtilsTest.java b/core/src/test/java/org/jclouds/util/HttpUtilsTest.java index 740685aa65..4e1ac708e8 100644 --- a/core/src/test/java/org/jclouds/util/HttpUtilsTest.java +++ b/core/src/test/java/org/jclouds/util/HttpUtilsTest.java @@ -20,32 +20,20 @@ package org.jclouds.util; import static com.google.common.base.Predicates.equalTo; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.jclouds.http.HttpUtils.changeSchemeHostAndPortTo; -import static org.jclouds.http.HttpUtils.parseQueryToMap; import static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull; import static org.testng.Assert.assertEquals; import java.net.URI; -import java.util.Collections; import javax.inject.Provider; -import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.UriBuilder; import org.jclouds.PerformanceTest; -import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpUtils; import org.testng.annotations.Test; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Iterables; -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Multimap; import com.sun.jersey.api.uri.UriBuilderImpl; /** @@ -53,7 +41,8 @@ import com.sun.jersey.api.uri.UriBuilderImpl; * * @author Adrian Cole */ -@Test(groups = "performance", sequential = true, testName = "jclouds.HttpUtils") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "HttpUtilsTest") public class HttpUtilsTest extends PerformanceTest { Provider uriBuilderProvider = new Provider() { @@ -64,62 +53,6 @@ public class HttpUtilsTest extends PerformanceTest { }; - public void testParseBase64InForm() { - Multimap expects = LinkedListMultimap.create(); - expects.put("Version", "2010-06-15"); - expects.put("Action", "ModifyInstanceAttribute"); - expects.put("Attribute", "userData"); - expects.put("Value", "dGVzdA=="); - expects.put("InstanceId", "1"); - assertEquals( - expects, - parseQueryToMap("Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=userData&Value=dGVzdA%3D%3D&InstanceId=1")); - } - - @Test - public void testParseQueryToMapSingleParam() { - Multimap parsedMap = parseQueryToMap("v=1.3"); - assert parsedMap.keySet().size() == 1 : "Expected 1 key, found: " + parsedMap.keySet().size(); - assert parsedMap.keySet().contains("v") : "Expected v to be a part of the keys"; - String valueForV = Iterables.getOnlyElement(parsedMap.get("v")); - assert valueForV.equals("1.3") : "Expected the value for 'v' to be '1.3', found: " + valueForV; - } - - @Test - public void testParseQueryToMapMultiParam() { - Multimap parsedMap = parseQueryToMap("v=1.3&sig=123"); - assert parsedMap.keySet().size() == 2 : "Expected 2 keys, found: " + parsedMap.keySet().size(); - assert parsedMap.keySet().contains("v") : "Expected v to be a part of the keys"; - assert parsedMap.keySet().contains("sig") : "Expected sig to be a part of the keys"; - String valueForV = Iterables.getOnlyElement(parsedMap.get("v")); - assert valueForV.equals("1.3") : "Expected the value for 'v' to be '1.3', found: " + valueForV; - String valueForSig = Iterables.getOnlyElement(parsedMap.get("sig")); - assert valueForSig.equals("123") : "Expected the value for 'v' to be '123', found: " + valueForSig; - } - - @Test - public void testChangeSchemeHostAndPortTo() { - HttpRequest request = createMock(HttpRequest.class); - expect(request.getEndpoint()).andReturn(URI.create("http://localhost/mypath")); - request.setEndpoint(URI.create("https://remotehost:443/mypath")); - Multimap headers = HashMultimap.create(); - expect(request.getHeaders()).andReturn(headers); - replay(request); - changeSchemeHostAndPortTo(request, "https", "remotehost", 443, uriBuilderProvider.get()); - assertEquals(headers.get(HttpHeaders.HOST), Collections.singletonList("remotehost")); - } - - public void testIsEncoded() { - assert HttpUtils.isUrlEncoded("/read-tests/%73%6f%6d%65%20%66%69%6c%65"); - assert !HttpUtils.isUrlEncoded("/read-tests/ tep"); - } - - public void testNoDoubleEncode() { - assertEquals(HttpUtils.urlEncode("/read-tests/%73%6f%6d%65%20%66%69%6c%65", '/'), - "/read-tests/%73%6f%6d%65%20%66%69%6c%65"); - assertEquals(HttpUtils.urlEncode("/read-tests/ tep", '/'), "/read-tests/%20tep"); - } - public void testIBM() { URI ibm = HttpUtils .createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram/assetDetail/generalDetails.faces?guid={A31FF849-0E97-431A-0324-097385A46298}&v=1.2"); @@ -189,6 +122,7 @@ public class HttpUtilsTest extends PerformanceTest { Exception from = new HttpResponseException("message", null, new HttpResponse(404, "not found", null)); assertEquals(returnValueOnCodeOrNull(from, true, equalTo(404)), Boolean.TRUE); } + public void testNullResponse() { Exception from = new HttpResponseException("message", null, null); assertEquals(returnValueOnCodeOrNull(from, true, equalTo(404)), null); diff --git a/core/src/test/java/org/jclouds/util/Lists2Test.java b/core/src/test/java/org/jclouds/util/Lists2Test.java new file mode 100644 index 0000000000..5db8df5f82 --- /dev/null +++ b/core/src/test/java/org/jclouds/util/Lists2Test.java @@ -0,0 +1,45 @@ +/** + * + * 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.util; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Ordering; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class Lists2Test { + + public void testMultiMax() { + Iterable values = ImmutableList.of("1", "2", "2", "3", "3"); + assertEquals(Lists2.multiMax(Ordering.natural(), values), ImmutableList.of("3", "3")); + } + + public void testMultiMax1() { + Iterable values = ImmutableList.of("1", "2", "2", "3"); + assertEquals(Lists2.multiMax(Ordering.natural(), values), ImmutableList.of("3")); + } + +} diff --git a/core/src/test/java/org/jclouds/util/Maps2Test.java b/core/src/test/java/org/jclouds/util/Maps2Test.java new file mode 100644 index 0000000000..9857cb9733 --- /dev/null +++ b/core/src/test/java/org/jclouds/util/Maps2Test.java @@ -0,0 +1,58 @@ +/** + * + * 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.util; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class Maps2Test { + public void testRenameKeyWhenNotFound() { + Map nothing = ImmutableMap.of(); + assertEquals(Maps2.renameKey(nothing, "foo", "bar"), nothing); + } + + public void testRenameKeyWhenFound() { + Map nothing = ImmutableMap.of("foo", "bar"); + assertEquals(Maps2.renameKey(nothing, "foo", "bar"), ImmutableMap.of("bar", "bar")); + } + + public void testTransformKeys() { + Map map = ImmutableMap.of("prefix:foo", "bar"); + assertEquals(Maps2.transformKeys(map, new Function() { + + @Override + public String apply(String arg0) { + return arg0.replace("prefix:", ""); + } + + }), ImmutableMap.of("foo", "bar")); + } + +} diff --git a/core/src/test/java/org/jclouds/util/PatternsTest.java b/core/src/test/java/org/jclouds/util/PatternsTest.java index 95a51772da..852ece5485 100644 --- a/core/src/test/java/org/jclouds/util/PatternsTest.java +++ b/core/src/test/java/org/jclouds/util/PatternsTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "jclouds.PatternsTest") +@Test(groups = "unit") public class PatternsTest { public void testJSON_STRING_PATTERN1() { diff --git a/core/src/test/java/org/jclouds/util/ProvidersTest.java b/core/src/test/java/org/jclouds/util/ProvidersTest.java new file mode 100644 index 0000000000..fadfecab8e --- /dev/null +++ b/core/src/test/java/org/jclouds/util/ProvidersTest.java @@ -0,0 +1,42 @@ +/** + * + * 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.util; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.rest.Providers; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ProvidersTest { + + @Test + public void testSupportedProviders() { + Iterable providers = Providers.getSupportedProviders(); + assertEquals(Sets.newLinkedHashSet(providers), ImmutableSet. of()); + } + +} diff --git a/core/src/test/java/org/jclouds/util/Strings2Test.java b/core/src/test/java/org/jclouds/util/Strings2Test.java new file mode 100644 index 0000000000..f13937a7a6 --- /dev/null +++ b/core/src/test/java/org/jclouds/util/Strings2Test.java @@ -0,0 +1,51 @@ +/** + * + * 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.util; + +import static org.testng.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; + +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class Strings2Test { + + public void testIsEncoded() { + assert Strings2.isUrlEncoded("/read-tests/%73%6f%6d%65%20%66%69%6c%65"); + assert !Strings2.isUrlEncoded("/read-tests/ tep"); + } + + public void testNoDoubleEncode() { + assertEquals(Strings2.urlEncode("/read-tests/%73%6f%6d%65%20%66%69%6c%65", '/'), + "/read-tests/%73%6f%6d%65%20%66%69%6c%65"); + assertEquals(Strings2.urlEncode("/read-tests/ tep", '/'), "/read-tests/%20tep"); + } + + public void testReplaceTokens() throws UnsupportedEncodingException { + assertEquals(Strings2.replaceTokens("hello {where}", ImmutableMap.of("where", "world")), "hello world"); + } + +} diff --git a/core/src/test/java/org/jclouds/util/UtilsTest.java b/core/src/test/java/org/jclouds/util/Throwables2Test.java similarity index 51% rename from core/src/test/java/org/jclouds/util/UtilsTest.java rename to core/src/test/java/org/jclouds/util/Throwables2Test.java index 8cb21bba54..ab54c99202 100644 --- a/core/src/test/java/org/jclouds/util/UtilsTest.java +++ b/core/src/test/java/org/jclouds/util/Throwables2Test.java @@ -21,13 +21,12 @@ package org.jclouds.util; import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.jclouds.util.Throwables2.getFirstThrowableOfType; +import static org.jclouds.util.Throwables2.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; -import java.util.Map; import java.util.concurrent.TimeoutException; -import org.jclouds.domain.Credentials; import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpResponseException; import org.jclouds.rest.AuthorizationException; @@ -35,107 +34,135 @@ import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Ordering; -import com.google.common.collect.Sets; import com.google.inject.ProvisionException; import com.google.inject.spi.Message; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "jclouds.UtilsTest") -public class UtilsTest { - public void testRenameKeyWhenNotFound() { - Map nothing = ImmutableMap.of(); - assertEquals(Utils.renameKey(nothing, "foo", "bar"), nothing); - } - - public void testRenameKeyWhenFound() { - Map nothing = ImmutableMap.of("foo", "bar"); - assertEquals(Utils.renameKey(nothing, "foo", "bar"), ImmutableMap.of("bar", "bar")); - } - - public void testOverridingCredentialsWhenOverridingIsNull() { - Credentials defaultCredentials = new Credentials("foo", "bar"); - Credentials overridingCredentials = null; - assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), defaultCredentials); - } - - public void testOverridingCredentialsWhenOverridingLoginIsNull() { - Credentials defaultCredentials = new Credentials("foo", "bar"); - Credentials overridingCredentials = new Credentials(null, "baz"); - assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials( - "foo", "baz")); - } - - public void testOverridingCredentialsWhenOverridingCredentialIsNull() { - Credentials defaultCredentials = new Credentials("foo", "bar"); - Credentials overridingCredentials = new Credentials("fooble", null); - assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials( - "fooble", "bar")); - } - - public void testOverridingCredentialsWhenOverridingCredentialsAreNull() { - Credentials defaultCredentials = new Credentials("foo", "bar"); - Credentials overridingCredentials = new Credentials(null, null); - assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials( - "foo", "bar")); - } +@Test +public class Throwables2Test { public void testGetCause() { AuthorizationException aex = createMock(AuthorizationException.class); Message message = new Message(ImmutableList.of(), "test", aex); ProvisionException pex = new ProvisionException(ImmutableSet.of(message)); - assertEquals(Utils.getFirstThrowableOfType(pex, AuthorizationException.class), aex); + assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex); } public void testGetFirstThrowableOfTypeOuter() { AuthorizationException aex = createMock(AuthorizationException.class); - assertEquals(Utils.getFirstThrowableOfType(aex, AuthorizationException.class), aex); + assertEquals(getFirstThrowableOfType(aex, AuthorizationException.class), aex); } public void testGetFirstThrowableOfTypeInner() { AuthorizationException aex = createMock(AuthorizationException.class); Message message = new Message(ImmutableList.of(), "test", aex); ProvisionException pex = new ProvisionException(ImmutableSet.of(message)); - assertEquals(Utils.getFirstThrowableOfType(pex, AuthorizationException.class), aex); + assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex); } public void testGetFirstThrowableOfTypeFail() { TimeoutException aex = createMock(TimeoutException.class); Message message = new Message(ImmutableList.of(), "test", aex); ProvisionException pex = new ProvisionException(ImmutableSet.of(message)); - assertEquals(Utils.getFirstThrowableOfType(pex, AuthorizationException.class), null); + assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null); } public void testGetFirstThrowableOfTypeWhenCauseIsNull() { Message message = new Message(ImmutableList.of(), "test", null); ProvisionException pex = new ProvisionException(ImmutableSet.of(message)); - assertEquals(Utils.getFirstThrowableOfType(pex, AuthorizationException.class), null); - } - - public void testReplaceTokens() throws UnsupportedEncodingException { - assertEquals(Utils.replaceTokens("hello {where}", ImmutableMap.of("where", "world")), "hello world"); - } - - public void testMultiMax() { - Iterable values = ImmutableList.of("1", "2", "2", "3", "3"); - assertEquals(Utils.multiMax(Ordering.natural(), values), ImmutableList.of("3", "3")); - } - - public void testMultiMax1() { - Iterable values = ImmutableList.of("1", "2", "2", "3"); - assertEquals(Utils.multiMax(Ordering.natural(), values), ImmutableList.of("3")); + assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null); } @Test - public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); - assertEquals(Sets.newLinkedHashSet(providers), ImmutableSet. of()); + public void testReturnExceptionThatsInList() throws Exception { + Exception e = new TestException(); + assertEquals(returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] { TestException.class }, e), + e); + assertEquals( + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] { TestException.class }, + new RuntimeException(e)), e); } + @Test(expectedExceptions = TestException.class) + public void testThrowExceptionNotInList() throws Exception { + Exception e = new TestException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, e); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testPropagateStandardExceptionIllegalStateException() throws Exception { + Exception e = new IllegalStateException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testPropagateStandardExceptionIllegalArgumentException() throws Exception { + Exception e = new IllegalArgumentException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); + } + + @Test(expectedExceptions = UnsupportedOperationException.class) + public void testPropagateStandardExceptionUnsupportedOperationException() throws Exception { + Exception e = new UnsupportedOperationException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testPropagateStandardExceptionAuthorizationException() throws Exception { + Exception e = new AuthorizationException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void testPropagateStandardExceptionResourceNotFoundException() throws Exception { + Exception e = new ResourceNotFoundException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testPropagateStandardExceptionIllegalStateExceptionNestedInHttpResponseException() throws Exception { + Exception e = new IllegalStateException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException("goo", + createNiceMock(HttpCommand.class), null, e)); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testPropagateStandardExceptionIllegalArgumentExceptionNestedInHttpResponseException() throws Exception { + Exception e = new IllegalArgumentException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException("goo", + createNiceMock(HttpCommand.class), null, e)); + } + + @Test(expectedExceptions = UnsupportedOperationException.class) + public void testPropagateStandardExceptionUnsupportedOperationExceptionNestedInHttpResponseException() + throws Exception { + Exception e = new UnsupportedOperationException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException("goo", + createNiceMock(HttpCommand.class), null, e)); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testPropagateStandardExceptionAuthorizationExceptionNestedInHttpResponseException() throws Exception { + Exception e = new AuthorizationException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException("goo", + createNiceMock(HttpCommand.class), null, e)); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void testPropagateStandardExceptionResourceNotFoundExceptionNestedInHttpResponseException() throws Exception { + Exception e = new ResourceNotFoundException(); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException("goo", + createNiceMock(HttpCommand.class), null, e)); + } + + @Test(expectedExceptions = HttpResponseException.class) + public void testPropagateStandardExceptionHttpResponseException() throws Exception { + Exception e = new HttpResponseException("goo", createNiceMock(HttpCommand.class), null); + returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); + } static class TestException extends Exception { /** @@ -145,92 +172,4 @@ public class UtilsTest { } - @Test - public void testReturnExceptionThatsInList() throws Exception { - Exception e = new TestException(); - assertEquals( - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] { TestException.class }, e), - e); - assertEquals(Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause( - new Class[] { TestException.class }, new RuntimeException(e)), e); - } - - @Test(expectedExceptions = TestException.class) - public void testThrowExceptionNotInList() throws Exception { - Exception e = new TestException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, e); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testPropagateStandardExceptionIllegalStateException() throws Exception { - Exception e = new IllegalStateException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testPropagateStandardExceptionIllegalArgumentException() throws Exception { - Exception e = new IllegalArgumentException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); - } - - @Test(expectedExceptions = UnsupportedOperationException.class) - public void testPropagateStandardExceptionUnsupportedOperationException() throws Exception { - Exception e = new UnsupportedOperationException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testPropagateStandardExceptionAuthorizationException() throws Exception { - Exception e = new AuthorizationException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); - } - - @Test(expectedExceptions = ResourceNotFoundException.class) - public void testPropagateStandardExceptionResourceNotFoundException() throws Exception { - Exception e = new ResourceNotFoundException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testPropagateStandardExceptionIllegalStateExceptionNestedInHttpResponseException() throws Exception { - Exception e = new IllegalStateException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException( - "goo", createNiceMock(HttpCommand.class), null, e)); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testPropagateStandardExceptionIllegalArgumentExceptionNestedInHttpResponseException() throws Exception { - Exception e = new IllegalArgumentException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException( - "goo", createNiceMock(HttpCommand.class), null, e)); - } - - @Test(expectedExceptions = UnsupportedOperationException.class) - public void testPropagateStandardExceptionUnsupportedOperationExceptionNestedInHttpResponseException() - throws Exception { - Exception e = new UnsupportedOperationException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException( - "goo", createNiceMock(HttpCommand.class), null, e)); - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testPropagateStandardExceptionAuthorizationExceptionNestedInHttpResponseException() throws Exception { - Exception e = new AuthorizationException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException( - "goo", createNiceMock(HttpCommand.class), null, e)); - } - - @Test(expectedExceptions = ResourceNotFoundException.class) - public void testPropagateStandardExceptionResourceNotFoundExceptionNestedInHttpResponseException() throws Exception { - Exception e = new ResourceNotFoundException(); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new HttpResponseException( - "goo", createNiceMock(HttpCommand.class), null, e)); - } - - @Test(expectedExceptions = HttpResponseException.class) - public void testPropagateStandardExceptionHttpResponseException() throws Exception { - Exception e = new HttpResponseException("goo", createNiceMock(HttpCommand.class), null); - Utils.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause(new Class[] {}, new RuntimeException(e)); - } - } diff --git a/demos/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java index eac5f3be42..72d610f9a1 100644 --- a/demos/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ b/demos/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java @@ -19,7 +19,7 @@ package org.jclouds.demo.tweetstore.functions; -import static org.jclouds.util.Utils.toStringAndClose; +import static org.jclouds.util.Strings2.toStringAndClose; import javax.annotation.Resource; diff --git a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java index 74289ff97a..aab00aed42 100644 --- a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java @@ -43,7 +43,7 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.AddTweetsControllerTest") +@Test(groups = "unit") public class AddTweetsControllerTest { Map createServices(String container) throws InterruptedException, diff --git a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java index abc0d9c05a..af23168422 100644 --- a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java @@ -23,7 +23,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; -import static org.jclouds.util.Utils.toStringAndClose; +import static org.jclouds.util.Strings2.toStringAndClose; import static org.testng.Assert.assertEquals; import java.io.IOException; @@ -50,7 +50,7 @@ import com.google.common.collect.ImmutableMap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.StoreTweetsControllerTest") +@Test(groups = "unit") public class StoreTweetsControllerTest { Twitter createTwitter() { diff --git a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java index 347a02bc5b..a20322dc1e 100644 --- a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java @@ -37,7 +37,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.KeyToStoredTweetStatusTest") +@Test(groups = "unit") public class KeyToStoredTweetStatusTest { BlobMap createMap() throws InterruptedException, ExecutionException { diff --git a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java index faf131cc17..173deeccd6 100644 --- a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java @@ -40,7 +40,7 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.ServiceToStoredTweetStatuses") +@Test(groups = "unit") public class ServiceToStoredTweetStatusesTest { Map createServices(String container) throws InterruptedException, diff --git a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java index 77a693d46c..6e3490ccd5 100644 --- a/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ b/demos/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java @@ -38,7 +38,7 @@ import org.jclouds.blobstore.BlobStoreContextFactory; import org.jclouds.demo.tweetstore.config.SpringServletConfig; import org.jclouds.demo.tweetstore.controller.StoreTweetsController; import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @@ -61,7 +61,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "functionalTests") +@Test(groups = "live", sequential = true) public class TweetStoreLiveTest { GoogleDevServer server; @@ -161,7 +161,7 @@ public class TweetStoreLiveTest { @Test public void shouldPass() throws InterruptedException, IOException { InputStream i = url.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Welcome") >= 0 : string; } @@ -180,7 +180,7 @@ public class TweetStoreLiveTest { connection.addRequestProperty("X-AppEngine-QueueName", "twitter"); connection.addRequestProperty("context", context); InputStream i = connection.getInputStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Done!") >= 0 : string; connection.disconnect(); } @@ -196,7 +196,7 @@ public class TweetStoreLiveTest { public void testSerial() throws InterruptedException, IOException { URL gurl = new URL(url, "/tweets/get"); InputStream i = gurl.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Tweets in Clouds") >= 0 : string; } @@ -204,7 +204,7 @@ public class TweetStoreLiveTest { public void testParallel() throws InterruptedException, IOException { URL gurl = new URL(url, "/tweets/get"); InputStream i = gurl.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Tweets in Clouds") >= 0 : string; } } diff --git a/demos/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java index eac5f3be42..72d610f9a1 100644 --- a/demos/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ b/demos/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java @@ -19,7 +19,7 @@ package org.jclouds.demo.tweetstore.functions; -import static org.jclouds.util.Utils.toStringAndClose; +import static org.jclouds.util.Strings2.toStringAndClose; import javax.annotation.Resource; diff --git a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java index 019550afd8..b406d1f5d6 100644 --- a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java @@ -43,7 +43,7 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.AddTweetsControllerTest") +@Test(groups = "unit") public class AddTweetsControllerTest { Map createServices(String container) throws InterruptedException, diff --git a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java index abc0d9c05a..af23168422 100644 --- a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java @@ -23,7 +23,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; -import static org.jclouds.util.Utils.toStringAndClose; +import static org.jclouds.util.Strings2.toStringAndClose; import static org.testng.Assert.assertEquals; import java.io.IOException; @@ -50,7 +50,7 @@ import com.google.common.collect.ImmutableMap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.StoreTweetsControllerTest") +@Test(groups = "unit") public class StoreTweetsControllerTest { Twitter createTwitter() { diff --git a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java index 843afd5fa2..05a406bcf2 100644 --- a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java @@ -37,7 +37,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.KeyToStoredTweetStatusTest") +@Test(groups = "unit") public class KeyToStoredTweetStatusTest { BlobMap createMap() throws InterruptedException, ExecutionException { diff --git a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java index faf131cc17..173deeccd6 100644 --- a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java @@ -40,7 +40,7 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "tweetstore.ServiceToStoredTweetStatuses") +@Test(groups = "unit") public class ServiceToStoredTweetStatusesTest { Map createServices(String container) throws InterruptedException, diff --git a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java index 1ac1f1d10f..d613dda664 100755 --- a/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ b/demos/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java @@ -39,7 +39,7 @@ import org.jclouds.demo.tweetstore.config.GuiceServletConfig; import org.jclouds.demo.tweetstore.controller.StoreTweetsController; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @@ -62,7 +62,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "functionalTests") +@Test(groups = "live", sequential = true) public class TweetStoreLiveTest { GoogleDevServer server; @@ -166,7 +166,7 @@ public class TweetStoreLiveTest { @Test public void shouldPass() throws InterruptedException, IOException { InputStream i = url.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Welcome") >= 0 : string; } @@ -185,7 +185,7 @@ public class TweetStoreLiveTest { connection.addRequestProperty("X-AppEngine-QueueName", "twitter"); connection.addRequestProperty("context", context); InputStream i = connection.getInputStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Done!") >= 0 : string; connection.disconnect(); } @@ -201,7 +201,7 @@ public class TweetStoreLiveTest { public void testSerial() throws InterruptedException, IOException { URL gurl = new URL(url, "/tweets/get"); InputStream i = gurl.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Tweets in Clouds") >= 0 : string; } @@ -209,7 +209,7 @@ public class TweetStoreLiveTest { public void testParallel() throws InterruptedException, IOException { URL gurl = new URL(url, "/tweets/get"); InputStream i = gurl.openStream(); - String string = Utils.toStringAndClose(i); + String string = Strings2.toStringAndClose(i); assert string.indexOf("Tweets in Clouds") >= 0 : string; } } diff --git a/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java b/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java index 006565b8c6..00e556d757 100644 --- a/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java +++ b/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java @@ -50,12 +50,13 @@ public class BindDriveDataToPlainTextString implements Binder { this.createDriveRequestToMap = createDriveRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(payload instanceof DriveData, "this binder is only valid for DriveData!"); DriveData create = DriveData.class.cast(payload); Map map = createDriveRequestToMap.apply(create); request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + return request; } } diff --git a/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java b/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java index 9db28769f3..067b9be9e3 100644 --- a/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java +++ b/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java @@ -50,12 +50,13 @@ public class BindDriveToPlainTextString implements Binder { this.createDriveRequestToMap = createDriveRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(payload instanceof Drive, "this binder is only valid for Drive!"); Drive create = Drive.class.cast(payload); Map map = createDriveRequestToMap.apply(create); request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + return request; } } diff --git a/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindServerToPlainTextString.java b/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindServerToPlainTextString.java index ba5cfe4895..b36f5c39b5 100644 --- a/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindServerToPlainTextString.java +++ b/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindServerToPlainTextString.java @@ -50,12 +50,13 @@ public class BindServerToPlainTextString implements Binder { this.createServerRequestToMap = createServerRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(payload instanceof Server, "this binder is only valid for Server!"); Server create = Server.class.cast(payload); Map map = createServerRequestToMap.apply(create); request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + return request; } } diff --git a/elasticstack/src/main/java/org/jclouds/elasticstack/compute/config/ElasticStackComputeServiceContextModule.java b/elasticstack/src/main/java/org/jclouds/elasticstack/compute/config/ElasticStackComputeServiceContextModule.java index 604b8ac3fa..8c702ede2c 100644 --- a/elasticstack/src/main/java/org/jclouds/elasticstack/compute/config/ElasticStackComputeServiceContextModule.java +++ b/elasticstack/src/main/java/org/jclouds/elasticstack/compute/config/ElasticStackComputeServiceContextModule.java @@ -29,7 +29,6 @@ import javax.inject.Singleton; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.config.ComputeServiceAdapterContextModule; -import org.jclouds.compute.config.JCloudsNativeComputeServiceAdapterContextModule.IdentityFunction; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; @@ -51,9 +50,10 @@ import org.jclouds.elasticstack.domain.Server; import org.jclouds.elasticstack.domain.ServerInfo; import org.jclouds.elasticstack.domain.WellKnownImage; import org.jclouds.elasticstack.predicates.DriveClaimed; +import org.jclouds.functions.IdentityFunction; import org.jclouds.json.Json; import org.jclouds.predicates.RetryablePredicate; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; import com.google.common.base.Predicate; @@ -128,7 +128,7 @@ public class ElasticStackComputeServiceContextModule @Provides protected Map provideImages(Json json) throws IOException { List wellKnowns = json.fromJson( - Utils.toStringAndClose(getClass().getResourceAsStream("/preinstalled_images.json")), + Strings2.toStringAndClose(getClass().getResourceAsStream("/preinstalled_images.json")), new TypeLiteral>() { }.getType()); return Maps.uniqueIndex(wellKnowns, new Function() { diff --git a/elasticstack/src/main/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandler.java b/elasticstack/src/main/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandler.java index d578b7318f..52ff8c3968 100644 --- a/elasticstack/src/main/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandler.java +++ b/elasticstack/src/main/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandler.java @@ -31,7 +31,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Throwables; import com.google.common.io.Closeables; @@ -57,11 +57,11 @@ public class ElasticStackErrorHandler implements HttpErrorHandler { Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try { - message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(), + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: - if ((command.getRequest().getEndpoint().getPath().endsWith("/info")) + if ((command.getCurrentRequest().getEndpoint().getPath().endsWith("/info")) || (message != null && message.indexOf("could not be found") != -1)) exception = new ResourceNotFoundException(message, exception); else @@ -71,7 +71,7 @@ public class ElasticStackErrorHandler implements HttpErrorHandler { exception = new AuthorizationException(message, exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; @@ -93,7 +93,7 @@ public class ElasticStackErrorHandler implements HttpErrorHandler { if (response.getPayload() == null) return null; try { - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } catch (IOException e) { throw new RuntimeException(e); } finally { diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java index 195c0380cc..90e9722f34 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java @@ -50,7 +50,6 @@ import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -59,23 +58,24 @@ import com.google.common.collect.Iterables; import com.google.inject.TypeLiteral; /** - * Tests annotation parsing of {@code ElasticStackAsyncClient} + * Tests behavior of {@code ElasticStackAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "elasticstack.ElasticStackAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ElasticStackAsyncClientTest") public class ElasticStackAsyncClientTest extends RestClientTest { public void testListServers() throws SecurityException, NoSuchMethodException, IOException { Method method = ElasticStackAsyncClient.class.getMethod("listServers"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/list HTTP/1.1"); // for example, using basic authentication, we should get "only one" @@ -94,7 +94,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -109,7 +109,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/uuid/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -125,7 +125,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, BindServerToPlainTextStringTest.SERVER); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/create HTTP/1.1"); @@ -142,7 +142,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, BindServerToPlainTextStringTest.SERVER); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/create/stopped HTTP/1.1"); @@ -159,7 +159,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + HttpRequest httpRequest = processor.createRequest(method, "100", BindServerToPlainTextStringTest.SERVER); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/100/set HTTP/1.1"); @@ -176,7 +176,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/uuid/destroy HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -192,7 +192,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/uuid/start HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -208,7 +208,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/uuid/stop HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -224,7 +224,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/uuid/shutdown HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -240,7 +240,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/servers/uuid/reset HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -256,15 +256,15 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/list HTTP/1.1"); // for example, using basic authentication, we should get "only one" @@ -283,7 +283,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -298,7 +298,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/uuid/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -314,7 +314,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, new CreateDriveRequest.Builder().name("foo").size(10000l).build()); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/create HTTP/1.1"); @@ -331,7 +331,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + HttpRequest httpRequest = processor.createRequest(method, "100", new DriveData.Builder().name("foo").size(10000l).tags(ImmutableList.of("production", "candy")).build()); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/set HTTP/1.1"); @@ -348,7 +348,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + HttpRequest httpRequest = processor.createRequest(method, "uuid"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/uuid/destroy HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -364,7 +364,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", "200"); + HttpRequest httpRequest = processor.createRequest(method, "100", "200"); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/200/image/100 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); @@ -381,7 +381,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", "200", + HttpRequest httpRequest = processor.createRequest(method, "100", "200", ImageConversionType.GUNZIP); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/200/image/100/gunzip HTTP/1.1"); @@ -398,7 +398,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", 1024, 2048); + HttpRequest httpRequest = processor.createRequest(method, "100", 1024, 2048); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/read/1024/2048 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/octet-stream\n"); @@ -413,7 +413,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + HttpRequest httpRequest = processor.createRequest(method, "100", Payloads.newStringPayload("foo")); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/write HTTP/1.1"); @@ -429,7 +429,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + HttpRequest httpRequest = processor.createRequest(method, "100", Payloads.newStringPayload("foo"), 2048); assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/write/2048 HTTP/1.1"); diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java index 9704ed8e69..2472ebd78a 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java @@ -54,7 +54,7 @@ import org.jclouds.rest.RestContext; import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @@ -72,7 +72,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", testName = "elasticstack.ElasticStackClientLiveTest") +@Test(groups = "live") public class ElasticStackClientLiveTest { protected long driveSize = 1 * 1024 * 1024 * 1024l; @@ -351,7 +351,7 @@ public class ElasticStackClientLiveTest { public void testWeCanReadAndWriteToDrive() throws IOException { drive2 = client.createDrive(new CreateDriveRequest.Builder().name(prefix + "2").size(1 * 1024 * 1024l).build()); client.writeDrive(drive2.getUuid(), Payloads.newStringPayload("foo")); - assertEquals(Utils.toStringAndClose(client.readDrive(drive2.getUuid(), 0, 3).getInput()), "foo"); + assertEquals(Strings2.toStringAndClose(client.readDrive(drive2.getUuid(), 0, 3).getInput()), "foo"); } @Test(dependsOnMethods = "testWeCanReadAndWriteToDrive") @@ -366,7 +366,7 @@ public class ElasticStackClientLiveTest { assert driveNotClaimed.apply(drive2) : client.getDriveInfo(drive2.getUuid()); System.err.println("after image; drive 2" + client.getDriveInfo(drive2.getUuid())); System.err.println("after image; drive 3" + client.getDriveInfo(drive3.getUuid())); - assertEquals(Utils.toStringAndClose(client.readDrive(drive3.getUuid(), 0, 3).getInput()), "foo"); + assertEquals(Strings2.toStringAndClose(client.readDrive(drive3.getUuid(), 0, 3).getInput()), "foo"); } finally { client.destroyDrive(drive2.getUuid()); client.destroyDrive(drive3.getUuid()); diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java index 1abd4ec256..99723833a7 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.elasticstack; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "elasticstack") : providers; assert Iterables.contains(providers, "elastichosts-lon-p") : providers; assert Iterables.contains(providers, "elastichosts-lon-b") : providers; diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java index 20067174f0..b1c7b620ab 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java @@ -33,7 +33,7 @@ import org.jclouds.elasticstack.domain.DriveData; import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; import org.jclouds.elasticstack.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -82,7 +82,7 @@ public class BindDriveDataToPlainTextStringTest { FN.bindToRequest(request, input); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); assertEquals(request.getPayload().getRawContent(), - Utils.toStringAndClose(BindDriveDataToPlainTextStringTest.class.getResourceAsStream("/drive_data.txt"))); + Strings2.toStringAndClose(BindDriveDataToPlainTextStringTest.class.getResourceAsStream("/drive_data.txt"))); } } \ No newline at end of file diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java index 6482fa87bf..8ed385b2c2 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java @@ -34,7 +34,7 @@ import org.jclouds.elasticstack.domain.DriveData; import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; import org.jclouds.elasticstack.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -84,7 +84,7 @@ public class BindDriveToPlainTextStringTest { FN.bindToRequest(request, input); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); assertEquals(request.getPayload().getRawContent(), - Utils.toStringAndClose(BindDriveToPlainTextStringTest.class + Strings2.toStringAndClose(BindDriveToPlainTextStringTest.class .getResourceAsStream("/create_drive.txt"))); } diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindServerToPlainTextStringTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindServerToPlainTextStringTest.java index d6fb33314d..3fb7bb89ed 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindServerToPlainTextStringTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindServerToPlainTextStringTest.java @@ -34,7 +34,7 @@ import org.jclouds.elasticstack.domain.Server; import org.jclouds.elasticstack.domain.VNC; import org.jclouds.elasticstack.functions.ServerToMap; import org.jclouds.http.HttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Function; @@ -54,7 +54,7 @@ public class BindServerToPlainTextStringTest { public static String CREATED_SERVER; static { try { - CREATED_SERVER = Utils.toStringAndClose(BindServerToPlainTextStringTest.class + CREATED_SERVER = Strings2.toStringAndClose(BindServerToPlainTextStringTest.class .getResourceAsStream("/create_server.txt")); } catch (IOException e) { CREATED_SERVER = null; diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java index 23679b5306..3e4473d11f 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java @@ -28,7 +28,7 @@ import org.jclouds.elasticstack.domain.ClaimType; import org.jclouds.elasticstack.domain.DriveInfo; import org.jclouds.elasticstack.domain.DriveMetrics; import org.jclouds.elasticstack.domain.DriveStatus; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; @@ -76,7 +76,7 @@ public class MapToDriveInfoTest { public void testComplete() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/drive.txt"))).get(0); + Strings2.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/drive.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), ONE); diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java index e3e28a1955..c65addfe66 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java @@ -35,7 +35,7 @@ import org.jclouds.elasticstack.domain.ServerMetrics; import org.jclouds.elasticstack.domain.ServerStatus; import org.jclouds.elasticstack.domain.VNC; import org.jclouds.elasticstack.functions.MapToDevices.DeviceToId; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; @@ -119,7 +119,7 @@ public class MapToServerInfoTest { public void testComplete() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/servers.txt"))).get(0); + Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/servers.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), ONE); @@ -154,7 +154,7 @@ public class MapToServerInfoTest { public void testNew() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/new_server.txt"))).get(0); + Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/new_server.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), NEW); diff --git a/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java b/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java index e7165d0144..20b3d28bfc 100644 --- a/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java +++ b/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java @@ -34,7 +34,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.inject.Guice; @@ -105,11 +105,11 @@ public class ElasticStackErrorHandlerTest { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); - HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils + HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Strings2 .toInputStream(content))); response.getPayload().getContentMetadata().setContentType(contentType); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); diff --git a/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCHttpCommandExecutorService.java b/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCHttpCommandExecutorService.java index e1b3c4e44f..eef40dbb56 100644 --- a/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCHttpCommandExecutorService.java +++ b/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCHttpCommandExecutorService.java @@ -42,6 +42,7 @@ import org.jclouds.http.internal.BaseHttpCommandExecutorService; import org.jclouds.http.internal.HttpWire; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; +import org.jclouds.rest.internal.RestAnnotationProcessor; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; @@ -58,9 +59,9 @@ public class ApacheHCHttpCommandExecutorService extends BaseHttpCommandExecutorS @Inject ApacheHCHttpCommandExecutorService(HttpUtils utils, - @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, - DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, - DelegatingErrorHandler errorHandler, HttpWire wire, HttpClient client) { + @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, + DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, + DelegatingErrorHandler errorHandler, HttpWire wire, HttpClient client) { super(utils, ioWorkerExecutor, retryHandler, ioRetryHandler, errorHandler, wire); this.client = client; } @@ -89,18 +90,18 @@ public class ApacheHCHttpCommandExecutorService extends BaseHttpCommandExecutorS logger.warn(e, "couldn't receive payload for request: %s", nativeRequest.getRequestLine()); throw e; } - HttpResponse response = new HttpResponse(apacheResponse.getStatusLine().getStatusCode(), apacheResponse - .getStatusLine().getReasonPhrase(), payload); Multimap headers = LinkedHashMultimap.create(); for (Header header : apacheResponse.getAllHeaders()) { headers.put(header.getName(), header.getValue()); } - utils.setPayloadPropertiesFromHeaders(headers, response); - return response; + if (payload != null) + payload.getContentMetadata().setPropertiesFromHttpHeaders(headers); + return new HttpResponse(apacheResponse.getStatusLine().getStatusCode(), apacheResponse.getStatusLine() + .getReasonPhrase(), payload, RestAnnotationProcessor.filterOutContentHeaders(headers)); } private org.apache.http.HttpResponse executeRequest(HttpUriRequest nativeRequest) throws IOException, - ClientProtocolException { + ClientProtocolException { URI endpoint = URI.create(nativeRequest.getRequestLine().getUri()); HttpHost host = new HttpHost(endpoint.getHost(), endpoint.getPort(), endpoint.getScheme()); org.apache.http.HttpResponse nativeResponse = client.execute(host, nativeRequest); diff --git a/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCUtils.java b/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCUtils.java index 7cdb2062fd..fce58a2ce8 100644 --- a/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCUtils.java +++ b/extensions/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCUtils.java @@ -131,7 +131,7 @@ public class ApacheHCUtils { apacheRequest.setEntity(nStringEntity); } else if (payload instanceof FilePayload) { apacheRequest.setEntity(new FileEntity((File) payload.getRawContent(), payload.getContentMetadata() - .getContentType())); + .getContentType())); } else if (payload instanceof ByteArrayPayload) { ByteArrayEntity Entity = new ByteArrayEntity((byte[]) payload.getRawContent()); Entity.setContentType(payload.getContentMetadata().getContentType()); diff --git a/extensions/bouncycastle/src/test/java/org/jclouds/encryption/bouncycastle/BouncyCastleCryptoTest.java b/extensions/bouncycastle/src/test/java/org/jclouds/encryption/bouncycastle/BouncyCastleCryptoTest.java index 5379bb6db6..500c698bdd 100644 --- a/extensions/bouncycastle/src/test/java/org/jclouds/encryption/bouncycastle/BouncyCastleCryptoTest.java +++ b/extensions/bouncycastle/src/test/java/org/jclouds/encryption/bouncycastle/BouncyCastleCryptoTest.java @@ -33,7 +33,8 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "performance", sequential = true, testName = "jclouds.BouncyCastleCryptoTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "BouncyCastleCryptoTest") public class BouncyCastleCryptoTest extends CryptoTest { @BeforeTest diff --git a/extensions/gae/src/main/java/org/jclouds/gae/AsyncGaeHttpCommandExecutorService.java b/extensions/gae/src/main/java/org/jclouds/gae/AsyncGaeHttpCommandExecutorService.java index d9e9f80f6d..155f317ea4 100644 --- a/extensions/gae/src/main/java/org/jclouds/gae/AsyncGaeHttpCommandExecutorService.java +++ b/extensions/gae/src/main/java/org/jclouds/gae/AsyncGaeHttpCommandExecutorService.java @@ -22,7 +22,6 @@ package org.jclouds.gae; import static com.google.common.base.Throwables.propagate; import static org.jclouds.http.HttpUtils.checkRequestHasContentLengthOrChunkedEncoding; import static org.jclouds.http.HttpUtils.wirePayloadIfEnabled; -import static org.jclouds.util.Utils.getFirstThrowableOfType; import java.io.IOException; import java.util.concurrent.ExecutorService; @@ -47,6 +46,7 @@ import org.jclouds.http.handlers.DelegatingErrorHandler; import org.jclouds.http.handlers.DelegatingRetryHandler; import org.jclouds.http.internal.HttpWire; import org.jclouds.logging.Logger; +import org.jclouds.util.Throwables2; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.URLFetchService; @@ -79,9 +79,9 @@ public class AsyncGaeHttpCommandExecutorService implements HttpCommandExecutorSe @Inject public AsyncGaeHttpCommandExecutorService(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, - URLFetchService urlFetchService, ConvertToGaeRequest convertToGaeRequest, - ConvertToJcloudsResponse convertToJcloudsResponse, DelegatingRetryHandler retryHandler, - IOExceptionRetryHandler ioRetryHandler, DelegatingErrorHandler errorHandler, HttpUtils utils, HttpWire wire) { + URLFetchService urlFetchService, ConvertToGaeRequest convertToGaeRequest, + ConvertToJcloudsResponse convertToJcloudsResponse, DelegatingRetryHandler retryHandler, + IOExceptionRetryHandler ioRetryHandler, DelegatingErrorHandler errorHandler, HttpUtils utils, HttpWire wire) { this.service = service; this.urlFetchService = urlFetchService; this.convertToGaeRequest = convertToGaeRequest; @@ -96,10 +96,10 @@ public class AsyncGaeHttpCommandExecutorService implements HttpCommandExecutorSe public HTTPRequest filterLogAndConvertRe(HttpRequest request) { for (HttpRequestFilter filter : request.getFilters()) { - filter.filter(request); + request = filter.filter(request); } checkRequestHasContentLengthOrChunkedEncoding(request, - "After filtering, the request has niether chunked encoding nor content length: " + request); + "After filtering, the request has niether chunked encoding nor content length: " + request); logger.debug("Sending request %s: %s", request.hashCode(), request.getRequestLine()); wirePayloadIfEnabled(wire, request); HTTPRequest nativeRequest = convertToGaeRequest.apply(request); @@ -110,17 +110,18 @@ public class AsyncGaeHttpCommandExecutorService implements HttpCommandExecutorSe @Override public ListenableFuture submit(final HttpCommand command) { - HTTPRequest nativeRequest = filterLogAndConvertRe(command.getRequest()); + HTTPRequest nativeRequest = filterLogAndConvertRe(command.getCurrentRequest()); ListenableFuture response = Futures.compose(urlFetchService.fetchAsync(nativeRequest), - convertToJcloudsResponse, service); + convertToJcloudsResponse, service); return Futures.compose(response, new Function() { @Override public HttpResponse apply(HttpResponse response) { try { - logger.debug("Receiving response %s: %s", command.getRequest().hashCode(), response.getStatusLine()); + logger.debug("Receiving response %s: %s", command.getCurrentRequest().hashCode(), + response.getStatusLine()); utils.logResponse(headerLog, response, "<<"); if (response.getPayload() != null && wire.enabled()) wire.input(response); @@ -133,7 +134,7 @@ public class AsyncGaeHttpCommandExecutorService implements HttpCommandExecutorSe } return response; } catch (Exception e) { - IOException ioe = getFirstThrowableOfType(e, IOException.class); + IOException ioe = Throwables2.getFirstThrowableOfType(e, IOException.class); if (ioe != null && ioRetryHandler.shouldRetryRequest(command, ioe)) { try { return submit(command).get(); @@ -143,7 +144,7 @@ public class AsyncGaeHttpCommandExecutorService implements HttpCommandExecutorSe } } else { command.setException(new HttpResponseException(e.getMessage() + " connecting to " - + command.getRequest().getRequestLine(), command, null, e)); + + command.getCurrentRequest().getRequestLine(), command, null, e)); return response; } } finally { diff --git a/extensions/gae/src/main/java/org/jclouds/gae/ConvertToGaeRequest.java b/extensions/gae/src/main/java/org/jclouds/gae/ConvertToGaeRequest.java index 00adfecf24..929d493b4a 100644 --- a/extensions/gae/src/main/java/org/jclouds/gae/ConvertToGaeRequest.java +++ b/extensions/gae/src/main/java/org/jclouds/gae/ConvertToGaeRequest.java @@ -42,7 +42,6 @@ import com.google.appengine.api.urlfetch.HTTPMethod; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.repackaged.com.google.common.base.Throwables; import com.google.common.base.Function; -import com.google.common.collect.LinkedHashMultimap; /** * @@ -98,9 +97,9 @@ public class ConvertToGaeRequest implements Function { } finally { closeQuietly(input); } - LinkedHashMultimap map = LinkedHashMultimap.create(); - HttpUtils.addContentHeadersFromMetadata(request.getPayload().getContentMetadata(), map); - for (Entry header : map.entries()) { + + for (Entry header : HttpUtils.getContentHeadersFromMetadata( + request.getPayload().getContentMetadata()).entries()) { gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } else { diff --git a/extensions/gae/src/main/java/org/jclouds/gae/ConvertToJcloudsResponse.java b/extensions/gae/src/main/java/org/jclouds/gae/ConvertToJcloudsResponse.java index 1fd96ea67a..4000b9cbcd 100644 --- a/extensions/gae/src/main/java/org/jclouds/gae/ConvertToJcloudsResponse.java +++ b/extensions/gae/src/main/java/org/jclouds/gae/ConvertToJcloudsResponse.java @@ -19,13 +19,12 @@ package org.jclouds.gae; -import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.http.HttpResponse; -import org.jclouds.http.HttpUtils; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; +import org.jclouds.rest.internal.RestAnnotationProcessor; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPResponse; @@ -39,17 +38,11 @@ import com.google.common.collect.Multimap; */ @Singleton public class ConvertToJcloudsResponse implements Function { - private final HttpUtils utils; - - @Inject - ConvertToJcloudsResponse(HttpUtils utils) { - this.utils = utils; - } @Override public HttpResponse apply(HTTPResponse gaeResponse) { - Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse - .getContent()) : null; + Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) + : null; Multimap headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { @@ -58,8 +51,10 @@ public class ConvertToJcloudsResponse implements Function) in).get()); + Strings2.toStringAndClose(((ListenableFuture) in).get()); } catch (InterruptedException e) { Throwables.propagate(e); } catch (ExecutionException e) { @@ -157,7 +157,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override public String toString() { return "[count=" + count + ", createFutures=" + createFutures + ", futuresConsumed=" + futuresConsumed - + ", futuresReady=" + futuresReady + ", who=" + who + "]"; + + ", futuresReady=" + futuresReady + ", who=" + who + "]"; } } @@ -173,7 +173,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC results.createFutures = System.currentTimeMillis() - start; start = System.currentTimeMillis(); Map exceptions = awaitCompletion(responses, MoreExecutors.sameThreadExecutor(), null, logger, - who); + who); results.futuresReady = System.currentTimeMillis() - start; assert exceptions.size() == 0 : exceptions; start = System.currentTimeMillis(); @@ -186,7 +186,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testKillRobotSlowly() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testKillRobotSlowly(); } @@ -194,7 +194,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testPostAsInputStream() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testPostAsInputStream(); } @@ -210,7 +210,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testPostBinder() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testPostBinder(); } @@ -223,7 +223,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testGetAndParseSax() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetAndParseSax(); } @@ -238,7 +238,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000, dataProvider = "gets") public void testGetStringSynch(String path) throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetStringSynch(path); } @@ -247,7 +247,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, expectedExceptions = UndeclaredThrowableException.class) public void testGetStringRedirect() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetStringRedirect(); } @@ -255,7 +255,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testGetException() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetException(); } @@ -263,7 +263,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testGetStringPermanentRedirect() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetStringPermanentRedirect(); } @@ -271,7 +271,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testGetSynchException() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetSynchException(); } @@ -290,10 +290,18 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC super.testPut(); } + @Override + @Test(enabled = true, invocationCount = 5, timeOut = 3000) + public void testGetStringViaRequest() throws ExecutionException, InterruptedException, + TimeoutException, IOException { + setupApiProxy(); + super.testGetStringViaRequest(); + } + @Override @Test(enabled = true, expectedExceptions = UndeclaredThrowableException.class) public void testPutRedirect() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testPutRedirect(); } @@ -301,7 +309,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testGetStringWithHeader() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testGetStringWithHeader(); } @@ -316,7 +324,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, invocationCount = 5, timeOut = 3000) public void testRequestFilter() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testRequestFilter(); } @@ -347,7 +355,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true) public void testGetBigFile() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { // disabled since test data is too big } @@ -380,7 +388,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC @Override @Test(enabled = true, expectedExceptions = IllegalArgumentException.class) public void testAlternateMethod() throws MalformedURLException, ExecutionException, InterruptedException, - TimeoutException { + TimeoutException { setupApiProxy(); super.testAlternateMethod(); } diff --git a/extensions/gae/src/test/java/org/jclouds/gae/ConvertToGaeRequestTest.java b/extensions/gae/src/test/java/org/jclouds/gae/ConvertToGaeRequestTest.java index 07f888d71e..a3d6bfa0af 100644 --- a/extensions/gae/src/test/java/org/jclouds/gae/ConvertToGaeRequestTest.java +++ b/extensions/gae/src/test/java/org/jclouds/gae/ConvertToGaeRequestTest.java @@ -36,7 +36,7 @@ import org.jclouds.crypto.Crypto; import org.jclouds.encryption.internal.JCECrypto; import org.jclouds.http.HttpRequest; import org.jclouds.io.Payloads; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @@ -45,6 +45,7 @@ import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.repackaged.com.google.common.base.Charsets; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableMultimap; import com.google.common.io.Files; /** @@ -89,8 +90,7 @@ public class ConvertToGaeRequestTest { @Test void testConvertRequestSetsHeaders() throws IOException { - HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint); - request.getHeaders().put("foo", "bar"); + HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint, ImmutableMultimap.of("foo", "bar")); HTTPRequest gaeRequest = req.apply(request); assertEquals(gaeRequest.getHeaders().get(0).getName(), "foo"); assertEquals(gaeRequest.getHeaders().get(0).getValue(), "bar"); @@ -117,7 +117,7 @@ public class ConvertToGaeRequestTest { @Test void testConvertRequestInputStreamContent() throws IOException { HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint); - request.setPayload(Utils.toInputStream("hoot!")); + request.setPayload(Strings2.toInputStream("hoot!")); request.getPayload().getContentMetadata().setContentLength(5l); testHoot(request); } @@ -156,7 +156,8 @@ public class ConvertToGaeRequestTest { for (HTTPHeader header : gaeRequest.getHeaders()) { builder.append(header.getName()).append(": ").append(header.getValue()).append("\n"); } - assertEquals(builder.toString(), "User-Agent: jclouds/1.0 urlfetch/1.3.5\nContent-Type: text/plain\nContent-Length: 5\nContent-MD5: AQIDBA==\n"); + assertEquals(builder.toString(), + "User-Agent: jclouds/1.0 urlfetch/1.3.5\nContent-Type: text/plain\nContent-Length: 5\nContent-MD5: AQIDBA==\n"); assertEquals(new String(gaeRequest.getPayload()), "hoot!"); } } diff --git a/extensions/gae/src/test/java/org/jclouds/gae/ConvertToJcloudsResponseTest.java b/extensions/gae/src/test/java/org/jclouds/gae/ConvertToJcloudsResponseTest.java index 9635074711..f056382add 100644 --- a/extensions/gae/src/test/java/org/jclouds/gae/ConvertToJcloudsResponseTest.java +++ b/extensions/gae/src/test/java/org/jclouds/gae/ConvertToJcloudsResponseTest.java @@ -37,8 +37,7 @@ import javax.ws.rs.core.HttpHeaders; import org.jclouds.crypto.Crypto; import org.jclouds.encryption.internal.JCECrypto; import org.jclouds.http.HttpResponse; -import org.jclouds.http.HttpUtils; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -69,7 +68,7 @@ public class ConvertToJcloudsResponseTest { @BeforeTest void setupClient() throws MalformedURLException { endPoint = URI.create("http://localhost:80/foo"); - req = new ConvertToJcloudsResponse(new HttpUtils(0, 0, 0, 0)); + req = new ConvertToJcloudsResponse(); } @Test @@ -103,7 +102,7 @@ public class ConvertToJcloudsResponseTest { replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); - assertEquals(Utils.toStringAndClose(response.getPayload().getInput()), "hello"); + assertEquals(Strings2.toStringAndClose(response.getPayload().getInput()), "hello"); assertEquals(response.getHeaders().size(), 0); assertEquals(response.getPayload().getContentMetadata().getContentType(), "text/xml"); } diff --git a/extensions/joda/src/test/java/org/jclouds/date/joda/JodaDateServiceTest.java b/extensions/joda/src/test/java/org/jclouds/date/joda/JodaDateServiceTest.java index dfd082aea0..bc8a10f81e 100755 --- a/extensions/joda/src/test/java/org/jclouds/date/joda/JodaDateServiceTest.java +++ b/extensions/joda/src/test/java/org/jclouds/date/joda/JodaDateServiceTest.java @@ -39,7 +39,8 @@ import com.google.inject.Injector; * @author Adrian Cole * @author James Murty */ -@Test(sequential = true, timeOut = 2 * 60 * 1000, testName = "core.JodaDateServiceTest") +//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "performance", sequential = true, timeOut = 2 * 60 * 1000, testName = "JodaDateServiceTest") public class JodaDateServiceTest extends DateServiceTest { @Override @BeforeTest diff --git a/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/JschSshClient.java b/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/JschSshClient.java index 83f3b54838..7bf9421d95 100644 --- a/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/JschSshClient.java +++ b/extensions/ssh/jsch/src/main/java/org/jclouds/ssh/jsch/JschSshClient.java @@ -48,7 +48,7 @@ import org.jclouds.net.IPSocket; import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; @@ -275,7 +275,7 @@ public class JschSshClient implements SshClient { executor.setErrStream(error); try { executor.connect(); - String outputString = Utils.toStringAndClose(executor.getInputStream()); + String outputString = Strings2.toStringAndClose(executor.getInputStream()); String errorString = error.toString(); int errorStatus = executor.getExitStatus(); int i = 0; 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 a594f1cab7..fea5c89e17 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 @@ -19,8 +19,6 @@ package org.jclouds.ssh.jsch.config; -import static org.jclouds.util.Utils.isPrivateKeyCredential; - import javax.inject.Named; import org.jclouds.Constants; @@ -32,6 +30,7 @@ import org.jclouds.predicates.SocketOpen; import org.jclouds.ssh.ConfiguresSshClient; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.jsch.JschSshClient; +import org.jclouds.util.CredentialUtils; import com.google.inject.AbstractModule; import com.google.inject.Inject; @@ -79,7 +78,7 @@ public class JschSshClientModule extends AbstractModule { @Override public SshClient create(IPSocket socket, Credentials credentials) { - return isPrivateKeyCredential(credentials) ? create(socket, credentials.identity, + return CredentialUtils.isPrivateKeyCredential(credentials) ? create(socket, credentials.identity, credentials.credential.getBytes()) : create(socket, credentials.identity, credentials.credential); } } diff --git a/extensions/ssh/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java b/extensions/ssh/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java index 921f7a98e3..787a3c89e7 100644 --- a/extensions/ssh/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java +++ b/extensions/ssh/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java @@ -33,7 +33,7 @@ import org.jclouds.net.IPSocket; import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @@ -45,7 +45,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "live", testName = "ssh.JschSshClientLiveTest") +@Test(groups = "live") public class JschSshClientLiveTest { protected static final String sshHost = System.getProperty("test.ssh.host", "localhost"); protected static final String sshPort = System.getProperty("test.ssh.port", "22"); @@ -112,7 +112,7 @@ public class JschSshClientLiveTest { SshClient connection; if (sshKeyFile != null && !sshKeyFile.trim().equals("")) { connection = factory.create(new IPSocket(sshHost, port), - new Credentials(sshUser, Utils.toStringAndClose(new FileInputStream(sshKeyFile)))); + new Credentials(sshUser, Strings2.toStringAndClose(new FileInputStream(sshKeyFile)))); } else { connection = factory.create(new IPSocket(sshHost, port), new Credentials(sshUser, sshPass)); } @@ -127,13 +127,13 @@ public class JschSshClientLiveTest { SshClient client = setupClient(); client.put(temp.getAbsolutePath(), Payloads.newStringPayload("rabbit")); Payload input = setupClient().get(temp.getAbsolutePath()); - String contents = Utils.toStringAndClose(input.getInput()); + String contents = Strings2.toStringAndClose(input.getInput()); assertEquals(contents, "rabbit"); } public void testGetEtcPassword() throws IOException { Payload input = setupClient().get("/etc/passwd"); - String contents = Utils.toStringAndClose(input.getInput()); + String contents = Strings2.toStringAndClose(input.getInput()); assert contents.indexOf("root") >= 0 : "no root in " + contents; } diff --git a/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java b/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java index d8622888ac..4b34b760b3 100644 --- a/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java +++ b/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java @@ -463,10 +463,6 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { return 0; } - public HttpRequest getRequest() { - return new HttpRequest("GET", URI.create("http://stub")); - } - public int incrementFailureCount() { return 0; } @@ -475,6 +471,16 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { } + @Override + public HttpRequest getCurrentRequest() { + return new HttpRequest("GET", URI.create("http://stub")); + } + + @Override + public void setCurrentRequest(HttpRequest request) { + + } + }, response); } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindIdsToQueryParams.java b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindIdsToQueryParams.java index a3e459380a..982fc0e917 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindIdsToQueryParams.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindIdsToQueryParams.java @@ -21,7 +21,6 @@ package org.jclouds.gogrid.binders; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.gogrid.reference.GoGridQueryParams.ID_KEY; -import static org.jclouds.http.HttpUtils.addQueryParamTo; import javax.inject.Inject; import javax.inject.Provider; @@ -29,6 +28,7 @@ import javax.inject.Singleton; import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; import com.google.common.collect.ImmutableList; @@ -59,18 +59,18 @@ public class BindIdsToQueryParams implements Binder { * array of String params */ @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { if (checkNotNull(input, "input is null") instanceof Long[]) { Long[] names = (Long[]) input; - addQueryParamTo(request, ID_KEY, ImmutableList.copyOf(names), builder.get()); + request = ModifyRequest.addQueryParam(request, ID_KEY, ImmutableList.copyOf(names), builder.get()); } else if (input instanceof long[]) { long[] names = (long[]) input; - addQueryParamTo(request, ID_KEY, Longs.asList(names), builder.get()); + request = ModifyRequest.addQueryParam(request, ID_KEY, Longs.asList(names), builder.get()); } else { throw new IllegalArgumentException("this binder is only valid for Long[] arguments: " + input.getClass()); } - + return request; } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindNamesToQueryParams.java b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindNamesToQueryParams.java index baa88ba006..f9108f8a4f 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindNamesToQueryParams.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindNamesToQueryParams.java @@ -22,13 +22,13 @@ package org.jclouds.gogrid.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.gogrid.reference.GoGridQueryParams.NAME_KEY; -import static org.jclouds.http.HttpUtils.addQueryParamTo; import javax.inject.Inject; import javax.inject.Provider; import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; import com.google.common.collect.ImmutableList; @@ -58,10 +58,10 @@ public class BindNamesToQueryParams implements Binder { * array of String params */ @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof String[], "this binder is only valid for String[] arguments"); String[] names = (String[]) input; - addQueryParamTo(request, NAME_KEY, ImmutableList.copyOf(names), builder.get()); + return ModifyRequest.addQueryParam(request, NAME_KEY, ImmutableList.copyOf(names), builder.get()); } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindObjectNameToGetJobsRequestQueryParams.java b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindObjectNameToGetJobsRequestQueryParams.java index 87e4417f63..79ee3e3f80 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindObjectNameToGetJobsRequestQueryParams.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindObjectNameToGetJobsRequestQueryParams.java @@ -22,13 +22,13 @@ package org.jclouds.gogrid.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.gogrid.reference.GoGridQueryParams.OBJECT_KEY; -import static org.jclouds.http.HttpUtils.addQueryParamTo; import javax.inject.Inject; import javax.inject.Provider; import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; /** @@ -50,12 +50,12 @@ public class BindObjectNameToGetJobsRequestQueryParams implements Binder { * href="http://wiki.gogrid.com/wiki/index.php/API:grid.job.list/>. */ @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof String, - "this binder is only valid for String arguments"); + "this binder is only valid for String arguments"); String serverName = (String) input; - addQueryParamTo(request, OBJECT_KEY, serverName, builder.get()); + return ModifyRequest.addQueryParam(request, OBJECT_KEY, serverName, builder.get()); } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindRealIpPortPairsToQueryParams.java b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindRealIpPortPairsToQueryParams.java index 869282f311..263bdf9394 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindRealIpPortPairsToQueryParams.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindRealIpPortPairsToQueryParams.java @@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.jclouds.gogrid.reference.GoGridQueryParams.REAL_IP_LIST_KEY; -import static org.jclouds.http.HttpUtils.addQueryParamTo; import java.util.List; @@ -33,6 +32,7 @@ import javax.ws.rs.core.UriBuilder; import org.jclouds.gogrid.domain.IpPortPair; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; /** @@ -52,7 +52,7 @@ public class BindRealIpPortPairsToQueryParams implements Binder { @SuppressWarnings( { "unchecked" }) @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof List, "this binder is only valid for a List argument"); @@ -65,11 +65,12 @@ public class BindRealIpPortPairsToQueryParams implements Binder { "There must be an IP address defined in Ip object"); checkState(ipPortPair.getPort() > 0, "The port number must be a positive integer"); - addQueryParamTo(request, REAL_IP_LIST_KEY + i + ".ip", ipPortPair.getIp().getIp(), builder + request = ModifyRequest.addQueryParam(request, REAL_IP_LIST_KEY + i + ".ip", ipPortPair.getIp().getIp(), builder .get()); - addQueryParamTo(request, REAL_IP_LIST_KEY + i + ".port", String.valueOf(ipPortPair + request = ModifyRequest.addQueryParam(request, REAL_IP_LIST_KEY + i + ".port", String.valueOf(ipPortPair .getPort()), builder.get()); i++; } + return request; } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindVirtualIpPortPairToQueryParams.java b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindVirtualIpPortPairToQueryParams.java index efcfd1ae0b..43a5b9b2d9 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/binders/BindVirtualIpPortPairToQueryParams.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/binders/BindVirtualIpPortPairToQueryParams.java @@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.jclouds.gogrid.reference.GoGridQueryParams.VIRTUAL_IP_KEY; -import static org.jclouds.http.HttpUtils.addQueryParamTo; import javax.inject.Inject; import javax.inject.Provider; @@ -31,6 +30,7 @@ import javax.ws.rs.core.UriBuilder; import org.jclouds.gogrid.domain.IpPortPair; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; /** @@ -49,7 +49,7 @@ public class BindVirtualIpPortPairToQueryParams implements Binder { } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof IpPortPair, "this binder is only valid for a IpPortPair argument"); @@ -59,8 +59,8 @@ public class BindVirtualIpPortPairToQueryParams implements Binder { checkNotNull(ipPortPair.getIp().getIp(), "There must be an IP address defined in Ip object"); checkState(ipPortPair.getPort() > 0, "The port number must be a positive integer"); - addQueryParamTo(request, VIRTUAL_IP_KEY + "ip", ipPortPair.getIp().getIp(), builder.get()); - addQueryParamTo(request, VIRTUAL_IP_KEY + "port", String.valueOf(ipPortPair.getPort()), + request = ModifyRequest.addQueryParam(request, VIRTUAL_IP_KEY + "ip", ipPortPair.getIp().getIp(), builder.get()); + return ModifyRequest.addQueryParam(request, VIRTUAL_IP_KEY + "port", String.valueOf(ipPortPair.getPort()), builder.get()); } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/filters/SharedKeyLiteAuthentication.java b/gogrid/src/main/java/org/jclouds/gogrid/filters/SharedKeyLiteAuthentication.java index e4dec7fb1a..1f9126f08d 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/filters/SharedKeyLiteAuthentication.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/filters/SharedKeyLiteAuthentication.java @@ -22,8 +22,6 @@ package org.jclouds.gogrid.filters; import static java.lang.String.format; import static org.jclouds.Constants.PROPERTY_CREDENTIAL; import static org.jclouds.Constants.PROPERTY_IDENTITY; -import static org.jclouds.http.HttpUtils.makeQueryLine; -import static org.jclouds.http.HttpUtils.parseQueryToMap; import java.net.URI; @@ -37,6 +35,7 @@ import org.jclouds.date.TimeStamp; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpUtils; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.io.InputSuppliers; import org.jclouds.logging.Logger; @@ -66,23 +65,24 @@ public class SharedKeyLiteAuthentication implements HttpRequestFilter { this.utils = utils; } - public void filter(HttpRequest request) { + @Override + public HttpRequest filter(HttpRequest request) { String toSign = createStringToSign(); String signatureMd5 = getMd5For(toSign); String query = request.getEndpoint().getQuery(); - Multimap decodedParams = parseQueryToMap(query); + Multimap decodedParams = ModifyRequest.parseQueryToMap(query); decodedParams.replaceValues("sig", ImmutableSet.of(signatureMd5)); decodedParams.replaceValues("api_key", ImmutableSet.of(apiKey)); - String updatedQuery = makeQueryLine(decodedParams, null); + String updatedQuery = ModifyRequest.makeQueryLine(decodedParams, null); String requestBasePart = request.getEndpoint().toASCIIString(); String updatedEndpoint = requestBasePart.substring(0, requestBasePart.indexOf("?") + 1) + updatedQuery; - request.setEndpoint(URI.create(updatedEndpoint)); - + request = request.toBuilder().endpoint(URI.create(updatedEndpoint)).build(); utils.logRequest(signatureLog, request, "<<"); + return request; } private String createStringToSign() { diff --git a/gogrid/src/main/java/org/jclouds/gogrid/mock/HttpCommandMock.java b/gogrid/src/main/java/org/jclouds/gogrid/mock/HttpCommandMock.java index 8571e90ec9..01fa6f97ad 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/mock/HttpCommandMock.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/mock/HttpCommandMock.java @@ -55,7 +55,7 @@ public class HttpCommandMock implements HttpCommand { } @Override - public HttpRequest getRequest() { + public HttpRequest getCurrentRequest() { return new HttpRequest("GET", URI.create("http://localhost")); } @@ -67,4 +67,9 @@ public class HttpCommandMock implements HttpCommand { public Exception getException() { return null; } + + @Override + public void setCurrentRequest(HttpRequest request) { + + } } diff --git a/gogrid/src/test/java/org/jclouds/gogrid/GoGridAsyncClientTest.java b/gogrid/src/test/java/org/jclouds/gogrid/GoGridAsyncClientTest.java index 25ea2982c8..d5c5cff12c 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/GoGridAsyncClientTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/GoGridAsyncClientTest.java @@ -30,11 +30,12 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code GoGridClient} + * Tests behavior of {@code GoGridAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "ec2.GoGridClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "GoGridAsyncClientTest") public class GoGridAsyncClientTest extends BaseGoGridAsyncClientTest { private GoGridAsyncClient asyncClient; diff --git a/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java b/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java index 16ef3dea14..e9b86f85f8 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java @@ -82,7 +82,7 @@ import com.google.inject.Module; * * @author Oleksiy Yarmula */ -@Test(enabled = true, groups = "live", testName = "gogrid.GoGridLiveTest") +@Test(enabled = true, groups = "live") public class GoGridLiveTestDisabled { private GoGridClient client; diff --git a/gogrid/src/test/java/org/jclouds/gogrid/ProvidersInPropertiesTest.java b/gogrid/src/test/java/org/jclouds/gogrid/ProvidersInPropertiesTest.java index 08d04635c9..ed98fd0931 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/ProvidersInPropertiesTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.gogrid; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "gogrid") : providers; } diff --git a/gogrid/src/test/java/org/jclouds/gogrid/binders/BindIdsToQueryParamsTest.java b/gogrid/src/test/java/org/jclouds/gogrid/binders/BindIdsToQueryParamsTest.java index 839feb604b..4e12dfb844 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/binders/BindIdsToQueryParamsTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/binders/BindIdsToQueryParamsTest.java @@ -52,7 +52,7 @@ public class BindIdsToQueryParamsTest { }); - binder.bindToRequest(request, new Long[] { 123L, 456L }); + request = binder.bindToRequest(request, new Long[] { 123L, 456L }); assertEquals(request.getRequestLine(), "GET http://momma/?id=123&id=456 HTTP/1.1"); } @@ -70,7 +70,7 @@ public class BindIdsToQueryParamsTest { }); - binder.bindToRequest(request, new long[] { 123L, 456L }); + request = binder.bindToRequest(request, new long[] { 123L, 456L }); assertEquals(request.getRequestLine(), "GET http://momma/?id=123&id=456 HTTP/1.1"); } diff --git a/gogrid/src/test/java/org/jclouds/gogrid/binders/BindNamesToQueryParamsTest.java b/gogrid/src/test/java/org/jclouds/gogrid/binders/BindNamesToQueryParamsTest.java index a1c9748f66..f864d25236 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/binders/BindNamesToQueryParamsTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/binders/BindNamesToQueryParamsTest.java @@ -53,7 +53,7 @@ public class BindNamesToQueryParamsTest { }); - binder.bindToRequest(request, input); + request = binder.bindToRequest(request, input); assertEquals(request.getRequestLine(), "GET http://momma/?name=hello&name=world HTTP/1.1"); } diff --git a/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java b/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java index 195e1f4abe..aa51ea2bae 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java @@ -35,7 +35,7 @@ import org.testng.annotations.Test; /** * @author Oleksiy Yarmula */ -@Test(groups = "live", enabled = true, sequential = true, testName = "gogrid.GoGridComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class GoGridComputeServiceLiveTest extends BaseComputeServiceLiveTest { public GoGridComputeServiceLiveTest() { provider = "gogrid"; diff --git a/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridTemplateBuilderLiveTest.java b/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridTemplateBuilderLiveTest.java index 57f881899b..e2c6d5e6d5 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridTemplateBuilderLiveTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridTemplateBuilderLiveTest.java @@ -36,7 +36,7 @@ import com.google.common.base.Predicate; * * @author Adrian Cole */ -@Test(groups = "live", testName = "gogrid.GoGridTemplateBuilderLiveTest") +@Test(groups = "live") public class GoGridTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public GoGridTemplateBuilderLiveTest() { diff --git a/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java b/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java index dc5478829d..10f64eea05 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "gogrid.GoGridComputeServiceContextModuleTest") +@Test(groups = "unit") public class GoGridComputeServiceContextModuleTest { public void testAllStatusCovered() { diff --git a/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java b/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java index 35fc6f5f52..fee7c07498 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java @@ -55,7 +55,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "gogrid.ServerToNodeMetadataTest") +@Test(groups = "unit") public class ServerToNodeMetadataTest { @SuppressWarnings("unchecked") diff --git a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java index 8f66232c2e..2b288cd7c7 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java @@ -48,7 +48,7 @@ import com.google.inject.Provides; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "gogrid.ParseCredentialsFromJsonResponseTest") +@Test(groups = "unit") public class ParseCredentialsFromJsonResponseTest { @Test(expectedExceptions = IllegalStateException.class) diff --git a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseJobsFromJsonResponseTest.java b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseJobsFromJsonResponseTest.java index 79750bb345..7b31e564ac 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseJobsFromJsonResponseTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseJobsFromJsonResponseTest.java @@ -52,7 +52,7 @@ import com.google.inject.Provides; /** * @author Oleksiy Yarmula */ -@Test(groups = "unit", testName = "gogrid.ParseJobsFromJsonResponseTest") +@Test(groups = "unit") public class ParseJobsFromJsonResponseTest { @Test diff --git a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseLoadBalancersFromJsonResponseTest.java b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseLoadBalancersFromJsonResponseTest.java index c75b1c745b..905102b097 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseLoadBalancersFromJsonResponseTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseLoadBalancersFromJsonResponseTest.java @@ -55,7 +55,7 @@ import com.google.inject.Provides; /** * @author Oleksiy Yarmula */ -@Test(groups = "unit", testName = "gogrid.ParseLoadBalancersFromJsonResponseTest") +@Test(groups = "unit") public class ParseLoadBalancersFromJsonResponseTest { @Test diff --git a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponseTest.java b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponseTest.java index c208d4480e..222d79d657 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponseTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponseTest.java @@ -48,7 +48,7 @@ import com.google.inject.Provides; /** * @author Oleksiy Yarmula */ -@Test(groups = "unit", testName = "gogrid.ParseServerNameToCredentialsMapFromJsonResponseTest") +@Test(groups = "unit") public class ParseServerNameToCredentialsMapFromJsonResponseTest { @Test diff --git a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServersFromJsonResponseTest.java b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServersFromJsonResponseTest.java index eb574604a3..0566147ed6 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServersFromJsonResponseTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServersFromJsonResponseTest.java @@ -58,7 +58,7 @@ import com.google.inject.Provides; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "gogrid.ParseServersFromJsonResponseTest") +@Test(groups = "unit") public class ParseServersFromJsonResponseTest { @Test @@ -92,7 +92,7 @@ public class ParseServersFromJsonResponseTest { @Provides @Singleton - @SuppressWarnings( { "unused", "unchecked" }) + @SuppressWarnings( { "unused", "rawtypes" }) public Map provideCustomAdapterBindings() { Map bindings = Maps.newHashMap(); bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter()); diff --git a/gogrid/src/test/java/org/jclouds/gogrid/services/BaseGoGridAsyncClientTest.java b/gogrid/src/test/java/org/jclouds/gogrid/services/BaseGoGridAsyncClientTest.java index a1df9e142b..9a830f71d7 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/services/BaseGoGridAsyncClientTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/services/BaseGoGridAsyncClientTest.java @@ -32,6 +32,7 @@ import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; +import org.testng.annotations.Test; import com.google.common.base.Supplier; import com.google.inject.Module; @@ -40,6 +41,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ +@Test(groups = "unit") public abstract class BaseGoGridAsyncClientTest extends RestClientTest { @Override protected void checkFilters(HttpRequest request) { diff --git a/gogrid/src/test/java/org/jclouds/gogrid/services/GridImageAsyncClientTest.java b/gogrid/src/test/java/org/jclouds/gogrid/services/GridImageAsyncClientTest.java index 45a662451d..6b94309084 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/services/GridImageAsyncClientTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/services/GridImageAsyncClientTest.java @@ -27,7 +27,7 @@ import org.jclouds.gogrid.domain.ServerImageType; import org.jclouds.gogrid.functions.ParseImageFromJsonResponse; import org.jclouds.gogrid.functions.ParseImageListFromJsonResponse; import org.jclouds.gogrid.options.GetImageListOptions; -import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.http.HttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -35,16 +35,21 @@ import com.google.common.collect.Iterables; import com.google.inject.TypeLiteral; /** + * Tests behavior of {@code GridImageAsyncClient} + * * @author Oleksiy Yarmula */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "GridImageAsyncClientTest") public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest { @Test public void testGetImageListWithOptions() throws NoSuchMethodException, IOException { Method method = GridImageAsyncClient.class.getMethod("getImageList", GetImageListOptions[].class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, - new GetImageListOptions().onlyPublic().setState(ServerImageState.AVAILABLE).setType( - ServerImageType.WEB_APPLICATION_SERVER)); + HttpRequest httpRequest = processor.createRequest( + method, + new GetImageListOptions().onlyPublic().setState(ServerImageState.AVAILABLE) + .setType(ServerImageType.WEB_APPLICATION_SERVER)); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/list?v=1.5&" + "isPublic=true&image.state=Available&" + "image.type=Web%20Server HTTP/1.1"); @@ -56,7 +61,7 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "name1", "name2"); + HttpRequest httpRequest = processor.createRequest(method, "name1", "name2"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/get?v=1.5&" + "name=name1&name=name2 HTTP/1.1"); @@ -80,7 +85,7 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "imageName", "newDesc"); + HttpRequest httpRequest = processor.createRequest(method, "imageName", "newDesc"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&" + "image=imageName&description=newDesc HTTP/1.1"); @@ -103,7 +108,7 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "imageName", - "newFriendlyName"); + HttpRequest httpRequest = processor.createRequest(method, "imageName", "newFriendlyName"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&" + "image=imageName&friendlyName=newFriendlyName HTTP/1.1"); @@ -127,7 +131,7 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest { @Test public void testGetIpListWithOptions() throws NoSuchMethodException, IOException { Method method = GridIpAsyncClient.class.getMethod("getIpList", GetIpListOptions[].class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new GetIpListOptions() + HttpRequest httpRequest = processor.createRequest(method, new GetIpListOptions() .onlyUnassigned().onlyWithType(IpType.PUBLIC)); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&" @@ -53,7 +57,7 @@ public class GridIpAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Assigned HTTP/1.1"); @@ -76,7 +80,7 @@ public class GridIpAsyncClientTest extends BaseGoGridAsyncClientTest { @Test public void testGetJobListWithOptions() throws NoSuchMethodException, IOException { Method method = GridJobAsyncClient.class.getMethod("getJobList", GetJobListOptions[].class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, new GetJobListOptions.Builder().create().withStartDate(new Date(1267385381770L)).withEndDate( new Date(1267385382770L)).onlyForObjectType(ObjectType.VIRTUAL_SERVER).onlyForState( JobState.PROCESSING)); @@ -58,7 +62,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/list?v=1.5 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); @@ -81,7 +85,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "MyServer"); + HttpRequest httpRequest = processor.createRequest(method, "MyServer"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/list?v=1.5&" + "object=MyServer HTTP/1.1"); @@ -93,7 +97,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, 123L, 456L); + HttpRequest httpRequest = processor.createRequest(method, 123L, 456L); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/get?v=1.5&" + "id=123&id=456 HTTP/1.1"); @@ -116,7 +120,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest { @Test public void testGetLoadBalancerList() throws NoSuchMethodException, IOException { Method method = GridLoadBalancerAsyncClient.class.getMethod("getLoadBalancerList"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); @@ -57,7 +61,7 @@ public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "BalanceIt", + HttpRequest httpRequest = processor.createRequest(method, "BalanceIt", new IpPortPair(new Ip("127.0.0.1"), 80), Arrays.asList(new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(new Ip("127.0.0.1"), 9090)), new AddLoadBalancerOptions.Builder().create( LoadBalancerType.LEAST_CONNECTED, LoadBalancerPersistenceType.SSL_STICKY)); @@ -87,7 +91,7 @@ public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, 1l, Arrays + HttpRequest httpRequest = processor.createRequest(method, 1l, Arrays .asList(new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(new Ip("127.0.0.1"), 9090))); assertRequestLineEquals( @@ -116,7 +120,7 @@ public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "BalanceIt", + HttpRequest httpRequest = processor.createRequest(method, "BalanceIt", Arrays.asList(new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(new Ip("127.0.0.1"), 9090))); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" @@ -142,7 +146,7 @@ public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, "My Load Balancer", "My Load Balancer 2"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" @@ -167,7 +171,7 @@ public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, 55L); + HttpRequest httpRequest = processor.createRequest(method, 55L); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" + "delete?v=1.5&id=55 HTTP/1.1"); @@ -191,7 +195,7 @@ public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest { @Test public void testGetServerListNoOptions() throws NoSuchMethodException, IOException { Method method = GridServerAsyncClient.class.getMethod("getServerList", GetServerListOptions[].class); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/list?v=1.5 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); @@ -61,7 +61,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, + HttpRequest httpRequest = processor.createRequest(method, new GetServerListOptions.Builder().onlySandboxServers()); assertRequestLineEquals(httpRequest, @@ -85,7 +85,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "server1"); + HttpRequest httpRequest = processor.createRequest(method, "server1"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?v=1.5&name=server1 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); @@ -107,7 +107,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, 123L); + HttpRequest httpRequest = processor.createRequest(method, 123L); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?v=1.5&id=123 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); @@ -129,7 +129,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "serverName", "img55", + HttpRequest httpRequest = processor.createRequest(method, "serverName", "img55", "memory", "127.0.0.1"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/add?v=1.5&" @@ -154,7 +154,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "serverName", "img55", + HttpRequest httpRequest = processor.createRequest(method, "serverName", "img55", "memory", "127.0.0.1", new AddServerOptions().asSandboxType().withDescription("fooy")); assertRequestLineEquals( @@ -181,7 +181,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "PowerServer", + HttpRequest httpRequest = processor.createRequest(method, "PowerServer", PowerCommand.RESTART); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/power?v=1.5&" @@ -206,7 +206,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, "PowerServer"); + HttpRequest httpRequest = processor.createRequest(method, "PowerServer"); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/delete?v=1.5&" + "name=PowerServer " + "HTTP/1.1"); @@ -229,7 +229,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/common/lookup/list?v=1.5&lookup=server.ram " + "HTTP/1.1"); @@ -252,7 +252,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest httpRequest = processor.createRequest(method, 1); + HttpRequest httpRequest = processor.createRequest(method, 1); assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/support/grid/password/get?v=1.5&id=1 HTTP/1.1"); diff --git a/rackspace/src/main/java/org/jclouds/rackspace/RackspaceAuthAsyncClient.java b/rackspace/src/main/java/org/jclouds/rackspace/RackspaceAuthAsyncClient.java index 99e45cdc9a..7f65d76302 100755 --- a/rackspace/src/main/java/org/jclouds/rackspace/RackspaceAuthAsyncClient.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/RackspaceAuthAsyncClient.java @@ -57,7 +57,6 @@ public interface RackspaceAuthAsyncClient { } @GET - @Path("") @ResponseParser(ParseAuthenticationResponseFromHeaders.class) ListenableFuture authenticate(@HeaderParam(RackspaceHeaders.AUTH_USER) String user, @HeaderParam(RackspaceHeaders.AUTH_KEY) String key); diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/CloudFilesAsyncClient.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/CloudFilesAsyncClient.java index cf2f057f6c..a634d9a3a4 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/CloudFilesAsyncClient.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/CloudFilesAsyncClient.java @@ -45,7 +45,7 @@ import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.http.options.GetOptions; import org.jclouds.rackspace.CloudFiles; import org.jclouds.rackspace.CloudFilesCDN; -import org.jclouds.rackspace.cloudfiles.binders.BindCFObjectToPayload; +import org.jclouds.rackspace.cloudfiles.binders.BindCFObjectMetadataToRequest; import org.jclouds.rackspace.cloudfiles.domain.AccountMetadata; import org.jclouds.rackspace.cloudfiles.domain.CFObject; import org.jclouds.rackspace.cloudfiles.domain.ContainerCDNMetadata; @@ -233,7 +233,7 @@ public interface CloudFilesAsyncClient { @ResponseParser(ParseETagHeader.class) ListenableFuture putObject( @PathParam("container") String container, - @PathParam("name") @ParamParser(ObjectName.class) @BinderParam(BindCFObjectToPayload.class) CFObject object); + @PathParam("name") @ParamParser(ObjectName.class) @BinderParam(BindCFObjectMetadataToRequest.class) CFObject object); /** * @see CloudFilesClient#getObject diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequest.java similarity index 68% rename from rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayload.java rename to rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequest.java index 05a02016b3..96a177e6d7 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequest.java @@ -20,6 +20,7 @@ package org.jclouds.rackspace.cloudfiles.binders; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; import javax.inject.Singleton; @@ -27,35 +28,41 @@ import javax.ws.rs.core.MediaType; import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rackspace.cloudfiles.blobstore.functions.ObjectToBlob; import org.jclouds.rackspace.cloudfiles.domain.CFObject; import org.jclouds.rest.Binder; @Singleton -public class BindCFObjectToPayload implements Binder { +public class BindCFObjectMetadataToRequest implements Binder { private final BindUserMetadataToHeadersWithPrefix mdBinder; private final ObjectToBlob object2Blob; @Inject - public BindCFObjectToPayload(ObjectToBlob object2Blob, BindUserMetadataToHeadersWithPrefix mdBinder) { + public BindCFObjectMetadataToRequest(ObjectToBlob object2Blob, BindUserMetadataToHeadersWithPrefix mdBinder) { this.mdBinder = mdBinder; this.object2Blob = object2Blob; } - public void bindToRequest(HttpRequest request, Object payload) { - CFObject object = (CFObject) payload; + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof CFObject, "this binder is only valid for CFObject!"); + checkNotNull(request, "request"); + + CFObject object = (CFObject) input; if (object.getPayload().getContentMetadata().getContentType() == null) object.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM); if (object.getPayload().getContentMetadata().getContentLength() != null - && object.getPayload().getContentMetadata().getContentLength() >= 0) { + && object.getPayload().getContentMetadata().getContentLength() >= 0) { checkArgument(object.getPayload().getContentMetadata().getContentLength() <= 5l * 1024 * 1024 * 1024, - "maximum size for put object is 5GB"); + "maximum size for put object is 5GB"); } else { // Enable "chunked"/"streamed" data, where the size needn't be known in advance. - request.getHeaders().put("Transfer-Encoding", "chunked"); + request = ModifyRequest.replaceHeader(request, "Transfer-Encoding", "chunked"); } - mdBinder.bindToRequest(request, object2Blob.apply(object)); + request = mdBinder.bindToRequest(request, object2Blob.apply(object)); + return request; } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataFromHeaders.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataFromHeaders.java index 7fc74188ca..04928d0047 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataFromHeaders.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataFromHeaders.java @@ -38,7 +38,7 @@ import com.google.common.base.Function; * @author James Murty */ public class ParseContainerCDNMetadataFromHeaders implements - Function, InvocationContext { + Function, InvocationContext { private HttpRequest request; diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectFromHeadersAndHttpContent.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectFromHeadersAndHttpContent.java index cecbd5b473..ccf05ca512 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectFromHeadersAndHttpContent.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectFromHeadersAndHttpContent.java @@ -36,7 +36,7 @@ import com.google.common.base.Function; * @author Adrian Cole */ public class ParseObjectFromHeadersAndHttpContent implements Function, - InvocationContext { + InvocationContext { private final ParseObjectInfoFromHeaders infoParser; private final CFObject.Factory objectProvider; diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeaders.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeaders.java index 3bc1bffd27..738a5f4329 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeaders.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeaders.java @@ -40,7 +40,7 @@ import com.google.common.base.Function; * @author Adrian Cole */ public class ParseObjectInfoFromHeaders implements Function, - InvocationContext { + InvocationContext { private final ParseSystemAndUserMetadataFromHeaders blobMetadataParser; private final ResourceToObjectInfo blobToObjectInfo; diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoListFromJsonResponse.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoListFromJsonResponse.java index 04a99f72f1..aaf5fcdb38 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoListFromJsonResponse.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoListFromJsonResponse.java @@ -51,7 +51,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -public class ParseObjectInfoListFromJsonResponse extends ParseJson> implements InvocationContext { +public class ParseObjectInfoListFromJsonResponse extends ParseJson> implements InvocationContext { private GeneratedHttpRequest request; @@ -64,10 +64,10 @@ public class ParseObjectInfoListFromJsonResponse extends ParseJson apply(InputStream stream) { checkState(request != null, "request should be initialized at this point"); checkState(request.getArgs() != null, "request.getArgs() should be initialized at this point"); - checkArgument(request.getArgs()[0] instanceof String, "arg[0] must be a container name"); - checkArgument(request.getArgs()[1] instanceof ListContainerOptions[], + checkArgument(request.getArgs().get(0) instanceof String, "arg[0] must be a container name"); + checkArgument(request.getArgs().get(1) instanceof ListContainerOptions[], "arg[1] must be an array of ListContainerOptions"); - ListContainerOptions[] optionsList = (ListContainerOptions[]) request.getArgs()[1]; + ListContainerOptions[] optionsList = (ListContainerOptions[]) request.getArgs().get(1); ListContainerOptions options = optionsList.length > 0 ? optionsList[0] : ListContainerOptions.NONE; Type listType = new TypeToken>() { }.getType(); diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ReturnTrueOn404FalseOn409.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ReturnTrueOn404FalseOn409.java index d547d6f573..91f70f4d37 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ReturnTrueOn404FalseOn409.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/functions/ReturnTrueOn404FalseOn409.java @@ -22,10 +22,11 @@ package org.jclouds.rackspace.cloudfiles.functions; import static com.google.common.base.Predicates.in; import static com.google.common.collect.ImmutableSet.of; import static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; + import com.google.common.base.Function; @Singleton diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponse.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponse.java index d79b86be03..3ecf223c68 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponse.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponse.java @@ -35,7 +35,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * This will parse and set an appropriate exception on the command object. @@ -60,8 +60,8 @@ public class ParseCloudFilesErrorFromHttpResponse implements HttpErrorHandler { exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String path = command.getRequest().getEndpoint().getPath(); + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = CONTAINER_PATH.matcher(path); if (matcher.find()) { exception = new ContainerNotFoundException(matcher.group(1), content); @@ -83,7 +83,7 @@ public class ParseCloudFilesErrorFromHttpResponse implements HttpErrorHandler { String parseErrorFromContentOrNull(HttpCommand command, HttpResponse response) { if (response.getPayload() != null) { try { - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } catch (IOException e) { logger.warn(e, "exception reading error from response", response); } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayload.java index e398236f48..87c6b8e8af 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayload.java @@ -40,14 +40,14 @@ import com.google.common.collect.ImmutableMap; public class BindAdminPassToJsonPayload extends BindToJsonPayload { @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { throw new IllegalStateException("Change Admin Pass is a PUT operation"); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { checkArgument(toBind instanceof String, "this binder is only valid for Strings!"); - super.bindToRequest(request, ImmutableMap.of("server", ImmutableMap.of("adminPass", - checkNotNull(toBind, "adminPass")))); + return super.bindToRequest(request, + ImmutableMap.of("server", ImmutableMap.of("adminPass", checkNotNull(toBind, "adminPass")))); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindBackupScheduleToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindBackupScheduleToJsonPayload.java index c0303d7f2c..0e81998403 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindBackupScheduleToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindBackupScheduleToJsonPayload.java @@ -40,15 +40,15 @@ import com.google.common.collect.ImmutableMap; public class BindBackupScheduleToJsonPayload extends BindToJsonPayload { @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { throw new IllegalStateException( "Replace Backup Schedule needs an BackupSchedule object, not a Map"); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { checkArgument(toBind instanceof BackupSchedule, "this binder is only valid for BackupSchedules!"); - super.bindToRequest(request, ImmutableMap.of("backupSchedule", toBind)); + return super.bindToRequest(request, ImmutableMap.of("backupSchedule", toBind)); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindConfirmResizeToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindConfirmResizeToJsonPayload.java index 8247022ca5..0e7f70b52d 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindConfirmResizeToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindConfirmResizeToJsonPayload.java @@ -31,8 +31,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindConfirmResizeToJsonPayload implements Binder { - - public void bindToRequest(HttpRequest request, Object toBind) { + @Override + public R bindToRequest(R request, Object toBind) { request.setPayload("{\"confirmResize\":null}"); + return request; } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayload.java index bd68902eae..3cd5af4159 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayload.java @@ -51,15 +51,15 @@ public class BindCreateImageToJsonPayload extends BindToJsonPayload { } @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { CreateImageRequest createRequest = new CreateImageRequest(Integer .parseInt(checkNotNull(postParams.get("serverId"))), checkNotNull(postParams .get("imageName"))); - super.bindToRequest(request, ImmutableMap.of("image", createRequest)); + return super.bindToRequest(request, ImmutableMap.of("image", createRequest)); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { throw new IllegalArgumentException("image is needs parameters"); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayload.java index d5099d7a93..7b28bc8b26 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayload.java @@ -41,14 +41,14 @@ import com.google.common.collect.ImmutableMap; public class BindRebootTypeToJsonPayload extends BindToJsonPayload { @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { throw new IllegalStateException("Reboot doesn't take map parameters"); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { checkArgument(toBind instanceof RebootType, "this binder is only valid for RebootTypes!"); - super.bindToRequest(request, ImmutableMap.of("reboot", ImmutableMap.of("type", checkNotNull( + return super.bindToRequest(request, ImmutableMap.of("reboot", ImmutableMap.of("type", checkNotNull( toBind, "type")))); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindResizeFlavorToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindResizeFlavorToJsonPayload.java index f5678f0047..213694114c 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindResizeFlavorToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindResizeFlavorToJsonPayload.java @@ -40,14 +40,14 @@ import com.google.common.collect.ImmutableMap; public class BindResizeFlavorToJsonPayload extends BindToJsonPayload { @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { throw new IllegalStateException("Resize doesn't take map parameters"); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { checkArgument(toBind instanceof Integer, "this binder is only valid for integers!"); - super.bindToRequest(request, ImmutableMap.of("resize", ImmutableMap.of("flavorId", + return super.bindToRequest(request, ImmutableMap.of("resize", ImmutableMap.of("flavorId", (Integer) checkNotNull(toBind, "flavorId")))); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRevertResizeToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRevertResizeToJsonPayload.java index 39639dba0b..08ad3fec25 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRevertResizeToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindRevertResizeToJsonPayload.java @@ -31,8 +31,9 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindRevertResizeToJsonPayload implements Binder { - - public void bindToRequest(HttpRequest request, Object toBind) { + @Override + public R bindToRequest(R request, Object toBind) { request.setPayload("{\"revertResize\":null}"); + return request; } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayload.java index 69e61d1ae5..ec64d7733f 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayload.java @@ -40,14 +40,14 @@ import com.google.common.collect.ImmutableMap; public class BindServerNameToJsonPayload extends BindToJsonPayload { @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { throw new IllegalStateException("Change Server Name is a PUT operation"); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { checkArgument(toBind instanceof String, "this binder is only valid for Strings!"); - super.bindToRequest(request, ImmutableMap.of("server", ImmutableMap.of("name", checkNotNull( + return super.bindToRequest(request, ImmutableMap.of("server", ImmutableMap.of("name", checkNotNull( toBind, "name")))); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindSharedIpGroupToJsonPayload.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindSharedIpGroupToJsonPayload.java index 0d3b232088..b7f4ab79e3 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindSharedIpGroupToJsonPayload.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/binders/BindSharedIpGroupToJsonPayload.java @@ -50,17 +50,17 @@ public class BindSharedIpGroupToJsonPayload extends BindToJsonPayload { } @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { ShareIpRequest createRequest = new ShareIpRequest(Integer.parseInt(checkNotNull(postParams .get("sharedIpGroupId")))); if (Boolean.parseBoolean(checkNotNull(postParams.get("configureServer")))) { createRequest.configureServer = new Boolean(true); } - super.bindToRequest(request, ImmutableMap.of("shareIp", createRequest)); + return super.bindToRequest(request, ImmutableMap.of("shareIp", createRequest)); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { throw new IllegalStateException("shareIp is needs parameters"); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/handlers/ParseCloudServersErrorFromHttpResponse.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/handlers/ParseCloudServersErrorFromHttpResponse.java index e1d74a6828..354d7923c8 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/handlers/ParseCloudServersErrorFromHttpResponse.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/handlers/ParseCloudServersErrorFromHttpResponse.java @@ -34,7 +34,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * This will parse and set an appropriate exception on the command object. @@ -58,8 +58,8 @@ public class ParseCloudServersErrorFromHttpResponse implements HttpErrorHandler exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String path = command.getRequest().getEndpoint().getPath(); + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = RESOURCE_PATTERN.matcher(path); String message; if (matcher.find()) { @@ -86,7 +86,7 @@ public class ParseCloudServersErrorFromHttpResponse implements HttpErrorHandler String parseErrorFromContentOrNull(HttpCommand command, HttpResponse response) { if (response.getPayload() != null) { try { - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } catch (IOException e) { logger.warn(e, "exception reading error from response", response); } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptions.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptions.java index 24323d8531..c3a80656b2 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptions.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptions.java @@ -92,7 +92,7 @@ public class CreateServerOptions extends BindToJsonPayload { private String publicIp; @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present"), Integer.parseInt(checkNotNull(postParams .get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull( @@ -108,7 +108,7 @@ public class CreateServerOptions extends BindToJsonPayload { server.addresses.getPublicAddresses().add(publicIp); server.addresses.setPrivateAddresses(null); } - bindToRequest(request, ImmutableMap.of("server", server)); + return bindToRequest(request, ImmutableMap.of("server", server)); } /** diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java index 3b5af4042a..a3d7f6ba19 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java @@ -53,14 +53,14 @@ public class CreateSharedIpGroupOptions extends BindToJsonPayload { } @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams .get("name")), serverId); - super.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest)); + return super.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest)); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { throw new IllegalStateException("CreateSharedIpGroup is a POST operation"); } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptions.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptions.java index dea7d2576c..8b89f4b108 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptions.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptions.java @@ -39,15 +39,15 @@ public class RebuildServerOptions extends BindToJsonPayload { Integer imageId; @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { Map image = Maps.newHashMap(); if (imageId != null) image.put("imageId", imageId); - super.bindToRequest(request, ImmutableMap.of("rebuild", image)); + return super.bindToRequest(request, ImmutableMap.of("rebuild", image)); } @Override - public void bindToRequest(HttpRequest request, Object toBind) { + public R bindToRequest(R request, Object toBind) { throw new IllegalStateException("RebuildServer is a POST operation"); } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/filters/AddTimestampQuery.java b/rackspace/src/main/java/org/jclouds/rackspace/filters/AddTimestampQuery.java index 129de95d2f..47f3bc3db9 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/filters/AddTimestampQuery.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/filters/AddTimestampQuery.java @@ -19,8 +19,6 @@ package org.jclouds.rackspace.filters; -import static org.jclouds.http.HttpUtils.addQueryParamTo; - import java.util.Date; import javax.inject.Inject; @@ -32,6 +30,7 @@ import org.jclouds.date.TimeStamp; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.utils.ModifyRequest; import com.google.common.base.Supplier; @@ -52,8 +51,9 @@ public class AddTimestampQuery implements HttpRequestFilter { this.dateProvider = dateProvider; } - public void filter(HttpRequest request) throws HttpException { - addQueryParamTo(request, "now", dateProvider.get().getTime() + "", builder.get()); + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.addQueryParam(request, "now", dateProvider.get().getTime() + "", builder.get()); } } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/filters/AuthenticateRequest.java b/rackspace/src/main/java/org/jclouds/rackspace/filters/AuthenticateRequest.java index 1b0b042cde..82adf4d2d5 100755 --- a/rackspace/src/main/java/org/jclouds/rackspace/filters/AuthenticateRequest.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/filters/AuthenticateRequest.java @@ -19,14 +19,13 @@ package org.jclouds.rackspace.filters; -import java.util.Collections; - import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rackspace.Authentication; import org.jclouds.rackspace.reference.RackspaceHeaders; @@ -48,9 +47,9 @@ public class AuthenticateRequest implements HttpRequestFilter { this.authTokenProvider = authTokenProvider; } - public void filter(HttpRequest request) throws HttpException { - request.getHeaders().replaceValues(RackspaceHeaders.AUTH_TOKEN, - Collections.singletonList(authTokenProvider.get())); + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.replaceHeader(request, RackspaceHeaders.AUTH_TOKEN, authTokenProvider.get()); } } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/functions/ParseAuthenticationResponseFromHeaders.java b/rackspace/src/main/java/org/jclouds/rackspace/functions/ParseAuthenticationResponseFromHeaders.java index 40f231364e..c17f7bea90 100755 --- a/rackspace/src/main/java/org/jclouds/rackspace/functions/ParseAuthenticationResponseFromHeaders.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/functions/ParseAuthenticationResponseFromHeaders.java @@ -48,7 +48,7 @@ import com.google.common.base.Objects; * @author Adrian Cole */ public class ParseAuthenticationResponseFromHeaders implements Function, - InvocationContext { + InvocationContext { public static final class AuthenticationResponseImpl implements AuthenticationResponse { @@ -136,7 +136,7 @@ public class ParseAuthenticationResponseFromHeaders implements Function providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "cloudfiles") : providers; assert Iterables.contains(providers, "cloudservers") : providers; } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/RackspaceAuthAsyncClientTest.java b/rackspace/src/test/java/org/jclouds/rackspace/RackspaceAuthAsyncClientTest.java index b1ab128f4b..daeeebdba7 100755 --- a/rackspace/src/test/java/org/jclouds/rackspace/RackspaceAuthAsyncClientTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/RackspaceAuthAsyncClientTest.java @@ -38,11 +38,12 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code JaxrsAnnotationProcessor} + * Tests behavior of {@code RackspaceAuthAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rackspace.RackspaceAuthentication") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "RackspaceAuthAsyncClientTest") public class RackspaceAuthAsyncClientTest extends RestClientTest { public void testAuthenticate() throws SecurityException, NoSuchMethodException, IOException { diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java index e64e9e7a32..37fdba714a 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java @@ -47,7 +47,7 @@ import org.jclouds.rackspace.cloudfiles.domain.MutableObjectInfoWithMetadata; import org.jclouds.rackspace.cloudfiles.domain.ObjectInfo; import org.jclouds.rackspace.cloudfiles.options.ListCdnContainerOptions; import org.jclouds.rackspace.cloudfiles.options.ListContainerOptions; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Predicate; @@ -59,7 +59,7 @@ import com.google.common.collect.Maps; * * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudfiles.CloudFilesClientLiveTest") +@Test(groups = "live") public class CloudFilesClientLiveTest extends BaseBlobStoreIntegrationTest { public CloudFilesClient getApi() { @@ -327,7 +327,7 @@ public class CloudFilesClientLiveTest extends BaseBlobStoreIntegrationTest { assert getApi().getObject(containerName, "non-existent-object") == null; // Test GET of object (including updated metadata) CFObject getBlob = getApi().getObject(containerName, object.getInfo().getName()); - assertEquals(Utils.toStringAndClose(getBlob.getPayload().getInput()), data); + assertEquals(Strings2.toStringAndClose(getBlob.getPayload().getInput()), data); // TODO assertEquals(getBlob.getName(), // object.getMetadata().getName()); assertEquals(getBlob.getInfo().getBytes(), new Long(data.length())); @@ -372,7 +372,7 @@ public class CloudFilesClientLiveTest extends BaseBlobStoreIntegrationTest { GetOptions.Builder.ifETagMatches(newEtag)); assertEquals(getBlob.getInfo().getHash(), CryptoStreams.hex(newEtag)); getBlob = getApi().getObject(containerName, object.getInfo().getName(), GetOptions.Builder.startAt(8)); - assertEquals(Utils.toStringAndClose(getBlob.getPayload().getInput()), data.substring(8)); + assertEquals(Strings2.toStringAndClose(getBlob.getPayload().getInput()), data.substring(8)); } finally { returnContainer(containerName); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequestTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequestTest.java new file mode 100644 index 0000000000..dad78e69b4 --- /dev/null +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectMetadataToRequestTest.java @@ -0,0 +1,155 @@ +/** + * + * 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.rackspace.cloudfiles.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.net.URI; +import java.util.Properties; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.http.HttpRequest; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.rackspace.cloudfiles.CloudFilesAsyncClient; +import org.jclouds.rackspace.cloudfiles.domain.CFObject; +import org.jclouds.rest.RestClientTest; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.rest.RestContextSpec; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; +import com.google.inject.TypeLiteral; + +/** + * Tests behavior of {@code BindCFObjectMetadataToRequest} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "BindCFObjectMetadataToRequestTest") +public class BindCFObjectMetadataToRequestTest extends RestClientTest { + + @Test + public void testPassWithMinimumDetailsAndPayload5GB() { + CFObject object = injector.getInstance(CFObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5 * 1024 * 1024 * 1024l); + object.setPayload(payload); + object.getInfo().setName("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindCFObjectMetadataToRequest binder = injector.getInstance(BindCFObjectMetadataToRequest.class); + + assertEquals(binder.bindToRequest(request, object), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build()); + } + + @Test + public void testExtendedPropertiesBind() { + CFObject object = injector.getInstance(CFObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5 * 1024 * 1024 * 1024l); + object.setPayload(payload); + object.getInfo().setName("foo"); + object.getInfo().getMetadata().putAll(ImmutableMap.of("foo", "bar")); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindCFObjectMetadataToRequest binder = injector.getInstance(BindCFObjectMetadataToRequest.class); + + assertEquals( + binder.bindToRequest(request, object), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")) + .headers(ImmutableMultimap.of("X-Object-Meta-foo", "bar")).build()); + } + + public void testNoContentLengthIsChunked() { + CFObject object = injector.getInstance(CFObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(null); + object.setPayload(payload); + object.getInfo().setName("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindCFObjectMetadataToRequest binder = injector.getInstance(BindCFObjectMetadataToRequest.class); + + assertEquals( + binder.bindToRequest(request, object), + HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")) + .headers(ImmutableMultimap.of("Transfer-Encoding", "chunked")).build()); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNoNameIsBad() { + CFObject object = injector.getInstance(CFObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5368709120000l); + object.setPayload(payload); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindCFObjectMetadataToRequest binder = injector.getInstance(BindCFObjectMetadataToRequest.class); + binder.bindToRequest(request, object); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testOver5GBIsBad() { + CFObject object = injector.getInstance(CFObject.Factory.class).create(null); + Payload payload = Payloads.newStringPayload(""); + payload.getContentMetadata().setContentLength(5 * 1024 * 1024 * 1024l + 1); + object.setPayload(payload); + object.getInfo().setName("foo"); + + HttpRequest request = HttpRequest.builder().method("PUT").endpoint(URI.create("http://localhost")).build(); + BindCFObjectMetadataToRequest binder = injector.getInstance(BindCFObjectMetadataToRequest.class); + binder.bindToRequest(request, object); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testMustBeCFObject() { + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + injector.getInstance(BindCFObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); + } + + @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) + public void testNullIsBad() { + BindCFObjectMetadataToRequest binder = injector.getInstance(BindCFObjectMetadataToRequest.class); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + binder.bindToRequest(request, null); + } + + @Override + protected void checkFilters(HttpRequest request) { + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + public RestContextSpec createContextSpec() { + return new RestContextFactory().createContextSpec("cloudfiles", "identity", "credential", new Properties()); + } +} \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayloadTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayloadTest.java deleted file mode 100644 index 5fd002c162..0000000000 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/binders/BindCFObjectToPayloadTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * - * 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.rackspace.cloudfiles.binders; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.http.HttpRequest; -import org.jclouds.io.MutableContentMetadata; -import org.jclouds.io.Payload; -import org.jclouds.rackspace.cloudfiles.blobstore.functions.ObjectToBlob; -import org.jclouds.rackspace.cloudfiles.domain.CFObject; -import org.jclouds.rackspace.cloudfiles.domain.MutableObjectInfoWithMetadata; -import org.testng.annotations.Test; - -import com.google.common.collect.Multimap; - -/** - * Tests behavior of {@code BindCFObjectToPayload} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "cloudfiles.BindCFObjectToPayloadTest") -public class BindCFObjectToPayloadTest { - @Test - public void testPassWithMinimumDetailsAndPayload5GB() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - ObjectToBlob object2Blob = createMock(ObjectToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - CFObject object = createMock(CFObject.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableObjectInfoWithMetadata md = createMock(MutableObjectInfoWithMetadata.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(content.getContentType()).andReturn(null).atLeastOnce(); - content.setContentType(MediaType.APPLICATION_OCTET_STREAM); - expect(content.getContentLength()).andReturn(5368709120l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindCFObjectToPayload binder = new BindCFObjectToPayload(object2Blob, mdBinder); - - binder.bindToRequest(request, object); - - verify(payload); - verify(content); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } - - @SuppressWarnings("unchecked") - @Test - public void testChunkedBind() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - ObjectToBlob object2Blob = createMock(ObjectToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - CFObject object = createMock(CFObject.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableObjectInfoWithMetadata md = createMock(MutableObjectInfoWithMetadata.class); - Multimap headers = createMock(Multimap.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(content.getContentType()).andReturn(null).atLeastOnce(); - content.setContentType(MediaType.APPLICATION_OCTET_STREAM); - expect(content.getContentLength()).andReturn(null).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(request.getHeaders()).andReturn(headers).atLeastOnce(); - expect(headers.put("Transfer-Encoding", "chunked")).andReturn(true); - - replay(headers); - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindCFObjectToPayload binder = new BindCFObjectToPayload(object2Blob, mdBinder); - - binder.bindToRequest(request, object); - - verify(headers); - verify(content); - verify(payload); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testOver5GBIsBad() { - - BindUserMetadataToHeadersWithPrefix mdBinder = createMock(BindUserMetadataToHeadersWithPrefix.class); - ObjectToBlob object2Blob = createMock(ObjectToBlob.class); - HttpRequest request = createMock(HttpRequest.class); - CFObject object = createMock(CFObject.class); - Payload payload = createMock(Payload.class); - Blob blob = createMock(Blob.class); - MutableObjectInfoWithMetadata md = createMock(MutableObjectInfoWithMetadata.class); - MutableContentMetadata content = createMock(MutableContentMetadata.class); - - expect(payload.getContentMetadata()).andReturn(content).atLeastOnce(); - expect(object.getPayload()).andReturn(payload).atLeastOnce(); - expect(content.getContentType()).andReturn(null).atLeastOnce(); - content.setContentType(MediaType.APPLICATION_OCTET_STREAM); - expect(content.getContentLength()).andReturn(5368709121l).atLeastOnce(); - expect(object2Blob.apply(object)).andReturn(blob); - mdBinder.bindToRequest(request, blob); - expect(object.getInfo()).andReturn(md).atLeastOnce(); - - replay(payload); - replay(content); - replay(mdBinder); - replay(object2Blob); - replay(request); - replay(object); - replay(blob); - replay(md); - - BindCFObjectToPayload bindCFObjectToPayload = new BindCFObjectToPayload(object2Blob, mdBinder); - - bindCFObjectToPayload.bindToRequest(request, object); - - verify(payload); - verify(content); - verify(mdBinder); - verify(object2Blob); - verify(request); - verify(object); - verify(blob); - verify(md); - - } -} diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobRequestSignerTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobRequestSignerTest.java index 704853ce62..978cdb6480 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobRequestSignerTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobRequestSignerTest.java @@ -41,7 +41,13 @@ import org.testng.annotations.Test; import com.google.inject.Module; import com.google.inject.TypeLiteral; -@Test(groups = "unit", testName = "cloudfiles.CloudFilesBlobRequestSignerTest") +/** + * Tests behavior of {@code CloudFilesBlobRequestSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CloudFilesBlobRequestSignerTest") public class CloudFilesBlobRequestSignerTest extends RestClientTest { private BlobRequestSigner signer; diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobIntegrationLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobIntegrationLiveTest.java index b03fd323a7..d242c43333 100755 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobIntegrationLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobIntegrationLiveTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudfiles.CloudFilesBlobIntegrationTest") +@Test(groups = "live") public class CloudFilesBlobIntegrationLiveTest extends BaseBlobIntegrationTest { @Override diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java index 6a24dc9ee2..9ab2caa2ba 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "cloudfiles.CloudFilesBlobLiveTest") +@Test(groups = { "live" }) public class CloudFilesBlobLiveTest extends BaseBlobLiveTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobMapIntegrationLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobMapIntegrationLiveTest.java index 852e2adad6..f6340f3164 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobMapIntegrationLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobMapIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudfiles.CloudFilesBlobMapIntegrationTest") +@Test(groups = "live") public class CloudFilesBlobMapIntegrationLiveTest extends BaseBlobMapIntegrationTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java index 513a9f52f4..0747b4e302 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "cloudfiles.CloudFilesBlobSignerLiveTest") +@Test(groups = { "live" }) public class CloudFilesBlobSignerLiveTest extends BaseBlobSignerLiveTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerIntegrationLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerIntegrationLiveTest.java index e8fe19b56e..e869c1145e 100755 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerIntegrationLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerIntegrationLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudfiles.CloudFilesContainerIntegrationTest") +@Test(groups = "live") public class CloudFilesContainerIntegrationLiveTest extends BaseContainerIntegrationTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerLiveTest.java index b703db14fc..dd995eded5 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesContainerLiveTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; * @author James Murty * @author Adrian Cole */ -@Test(groups = { "live" }, testName = "cloudfiles.CloudFilesContainerLiveTest") +@Test(groups = { "live" }) public class CloudFilesContainerLiveTest extends BaseContainerLiveTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesInputStreamMapIntegrationLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesInputStreamMapIntegrationLiveTest.java index 9476766cab..fb16c2ad85 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesInputStreamMapIntegrationLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesInputStreamMapIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudfiles.CloudFilesInputStreamMapIntegrationTest") +@Test(groups = "live") public class CloudFilesInputStreamMapIntegrationLiveTest extends BaseInputStreamMapIntegrationTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesServiceIntegrationLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesServiceIntegrationLiveTest.java index fe131526e3..c20d2e04c2 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesServiceIntegrationLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/blobstore/integration/CloudFilesServiceIntegrationLiveTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudfiles.CloudFilesServiceIntegrationTest") +@Test(groups = "live") public class CloudFilesServiceIntegrationLiveTest extends BaseServiceIntegrationTest { } \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/domain/internal/ParseObjectInfoListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/domain/internal/ParseObjectInfoListFromJsonResponseTest.java index 194867d49c..e2870921e6 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/domain/internal/ParseObjectInfoListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/domain/internal/ParseObjectInfoListFromJsonResponseTest.java @@ -37,16 +37,17 @@ import org.jclouds.rackspace.config.RackspaceParserModule; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.inject.Guice; import com.google.inject.Injector; /** - * Tests behavior of {@code ParseObjectInfoListFromJsonResponseTest} + * Tests behavior of {@code ParseObjectInfoListFromJsonResponse} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudfiles.ParseObjectInfoListFromJsonResponseTest") +@Test(groups = "unit") public class ParseObjectInfoListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); @@ -70,8 +71,8 @@ public class ParseObjectInfoListFromJsonResponseTest { expects.add(two); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); ListContainerOptions options = new ListContainerOptions(); - expect(request.getArgs()).andReturn(new Object[] { "containter", new ListContainerOptions[] { options } }) - .atLeastOnce(); + expect(request.getArgs()).andReturn( + ImmutableList. of("containter", new ListContainerOptions[] { options })).atLeastOnce(); replay(request); ParseObjectInfoListFromJsonResponse parser = i.getInstance(ParseObjectInfoListFromJsonResponse.class); parser.setContext(request); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseAuthenticationResponseFromHeadersTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseAuthenticationResponseFromHeadersTest.java index 15c3fc5af1..83bb877b97 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseAuthenticationResponseFromHeadersTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseAuthenticationResponseFromHeadersTest.java @@ -33,6 +33,7 @@ import org.jclouds.rackspace.RackspaceAuthAsyncClient.AuthenticationResponse; import org.jclouds.rackspace.functions.ParseAuthenticationResponseFromHeaders; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableMultimap; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; @@ -44,7 +45,7 @@ import com.sun.jersey.api.uri.UriBuilderImpl; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudfiles.ParseAuthenticationResponseFromHeadersTest") +@Test(groups = "unit") public class ParseAuthenticationResponseFromHeadersTest { Injector i = Guice.createInjector(new AbstractModule() { @@ -63,10 +64,8 @@ public class ParseAuthenticationResponseFromHeadersTest { HttpRequest request = new HttpRequest("GET", URI.create("http://realhost:11000/v1.0")); parser.setContext(request); - HttpResponse response = new HttpResponse(204, "No Content", null); - response.getHeaders().put("X-Auth-Token", "token"); - response.getHeaders().put("X-Storage-Token", "token"); - response.getHeaders().put("X-Storage-Url", "http://127.0.0.1:8080/v1/token"); + HttpResponse response = new HttpResponse(204, "No Content", null, ImmutableMultimap. of( + "X-Auth-Token", "token", "X-Storage-Token", "token", "X-Storage-Url", "http://127.0.0.1:8080/v1/token")); AuthenticationResponse md = parser.apply(response); assertEquals( diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java index 8dd80b28cf..2059764ac3 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java @@ -45,7 +45,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudfiles.ParseContainerCDNMetadataListFromJsonResponseTest") +@Test(groups = "unit") public class ParseContainerCDNMetadataListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerListFromJsonResponseTest.java index 0bfaa5e4d9..581519277e 100755 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseContainerListFromJsonResponseTest.java @@ -30,7 +30,7 @@ import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; import org.jclouds.rackspace.cloudfiles.domain.ContainerMetadata; import org.jclouds.rackspace.config.RackspaceParserModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; @@ -44,13 +44,13 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudfiles.ParseContainerListFromJsonResponse") +@Test(groups = "unit") public class ParseContainerListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); @Test public void testApplyInputStream() { - InputStream is = Utils + InputStream is = Strings2 .toInputStream("[ {\"name\":\"test_container_1\",\"count\":2,\"bytes\":78}, {\"name\":\"test_container_2\",\"count\":1,\"bytes\":17} ] "); List expects = ImmutableList.of(new ContainerMetadata("test_container_1", 2, 78), diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeadersTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeadersTest.java index 48e493e887..11ff4d842e 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeadersTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/functions/ParseObjectInfoFromHeadersTest.java @@ -34,6 +34,8 @@ import org.jclouds.rackspace.cloudfiles.domain.MutableObjectInfoWithMetadata; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMultimap; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; @@ -44,7 +46,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudfiles.ParseObjectInfoFromHeadersTest") +@Test(groups = "unit") public class ParseObjectInfoFromHeadersTest { Injector i = Guice.createInjector(new AbstractModule() { @@ -60,17 +62,16 @@ public class ParseObjectInfoFromHeadersTest { public void testEtagCaseIssue() { ParseObjectInfoFromHeaders parser = i.getInstance(ParseObjectInfoFromHeaders.class); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new String[] { "container", "key" }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList. of("container", "key")).atLeastOnce(); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/test")).atLeastOnce(); replay(request); parser.setContext(request); - HttpResponse response = new HttpResponse(200, "ok", Payloads.newStringPayload("")); - response.getPayload().getContentMetadata().setContentType("text/plain"); - response.getHeaders().put("Last-Modified", "Fri, 12 Jun 2007 13:40:18 GMT"); - response.getHeaders().put("Content-Length", "0"); + HttpResponse response = new HttpResponse(200, "ok", Payloads.newStringPayload(""), + ImmutableMultimap. of("Last-Modified", "Fri, 12 Jun 2007 13:40:18 GMT", "Content-Length", + "0", "Etag", "feb1")); - response.getHeaders().put("Etag", "feb1"); + response.getPayload().getContentMetadata().setContentType("text/plain"); MutableObjectInfoWithMetadata md = parser.apply(response); assertNotNull(md.getHash()); } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponseTest.java index bebbd38916..f35347702a 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/handlers/ParseCloudFilesErrorFromHttpResponseTest.java @@ -15,7 +15,7 @@ import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; /** @@ -65,11 +65,11 @@ public class ParseCloudFilesErrorFromHttpResponseTest { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); - HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils + HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Strings2 .toInputStream(content))); response.getPayload().getContentMetadata().setContentType(contentType); - expect(command.getRequest()).andReturn(request).atLeastOnce(); + expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersAsyncClientTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersAsyncClientTest.java index 03776e66d5..dddbe22e11 100755 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersAsyncClientTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersAsyncClientTest.java @@ -68,11 +68,12 @@ import com.google.inject.Module; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code CloudServersClient} + * Tests behavior of {@code CloudServersAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.CloudServersClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CloudServersAsyncClientTest") public class CloudServersAsyncClientTest extends RestClientTest { private static final Class listOptionsVarargsClass = new ListOptions[] {}.getClass(); private static final Class createServerOptionsVarargsClass = new CreateServerOptions[] {} diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersClientLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersClientLiveTest.java index b45b7c1deb..b1ee1b4572 100755 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersClientLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersClientLiveTest.java @@ -59,7 +59,7 @@ import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshException; import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @@ -77,7 +77,7 @@ import com.google.inject.Module; * @author Adrian Cole */ // disabled [Web Hosting #129069 -@Test(groups = "live", sequential = true, testName = "cloudservers.CloudServersClientLiveTest") +@Test(groups = "live", sequential = true) public class CloudServersClientLiveTest { protected CloudServersClient client; @@ -412,7 +412,7 @@ public class CloudServersClientLiveTest { try { client.connect(); Payload etcPasswd = client.get("/etc/jclouds.txt"); - String etcPasswdContents = Utils.toStringAndClose(etcPasswd.getInput()); + String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput()); assertEquals("rackspace", etcPasswdContents.trim()); } finally { if (client != null) diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayloadTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayloadTest.java index 098968accc..24d5788c97 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayloadTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindAdminPassToJsonPayloadTest.java @@ -39,7 +39,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.BindAdminPassToJsonPayloadTest") +@Test(groups = "unit") public class BindAdminPassToJsonPayloadTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayloadTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayloadTest.java index 165d137c88..f8406d6b3f 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayloadTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindCreateImageToJsonPayloadTest.java @@ -39,7 +39,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.BindCreateImageToJsonPayloadTest") +@Test(groups = "unit") public class BindCreateImageToJsonPayloadTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayloadTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayloadTest.java index 7a81aa9a7e..a21a12ae25 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayloadTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindRebootTypeToJsonPayloadTest.java @@ -40,7 +40,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.BindRebootTypeToJsonPayloadTest") +@Test(groups = "unit") public class BindRebootTypeToJsonPayloadTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayloadTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayloadTest.java index 77cf16f79a..82a7dbd281 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayloadTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/binders/BindServerNameToJsonPayloadTest.java @@ -39,7 +39,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.BindServerNameToJsonPayloadTest") +@Test(groups = "unit") public class BindServerNameToJsonPayloadTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersComputeServiceLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersComputeServiceLiveTest.java index ad757b5826..dabd03c862 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersComputeServiceLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersComputeServiceLiveTest.java @@ -42,7 +42,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "cloudservers.CloudServersComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class CloudServersComputeServiceLiveTest extends BaseComputeServiceLiveTest { public CloudServersComputeServiceLiveTest() { provider = "cloudservers"; diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersTemplateBuilderLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersTemplateBuilderLiveTest.java index 8152a48dc7..bfa07c5d5c 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersTemplateBuilderLiveTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersTemplateBuilderLiveTest.java @@ -30,7 +30,7 @@ import com.google.common.base.Predicate; * * @author Adrian Cole */ -@Test(groups = "live", testName = "cloudservers.CloudServersTemplateBuilderLiveTest") +@Test(groups = "live") public class CloudServersTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public CloudServersTemplateBuilderLiveTest() { diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java index ea4e0f0d0f..fd1c9015ec 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.CloudServersComputeServiceContextModuleTest") +@Test(groups = "unit") public class CloudServersComputeServiceContextModuleTest { public void testAllStatusCovered() { diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java index 99c4fb9bd5..960a34b73a 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java @@ -40,7 +40,7 @@ import com.google.inject.Guice; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.CloudServersImageToImageTest") +@Test(groups = "unit") public class CloudServersImageToImageTest { @Test diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java index 15dcf01811..71ca2e0af6 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java @@ -40,7 +40,7 @@ import com.google.common.collect.ImmutableList; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.FlavorToHardwareTest") +@Test(groups = "unit") public class FlavorToHardwareTest { Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java index 9c38daec90..f963e6c654 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java @@ -54,7 +54,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ServerToNodeMetadataTest") +@Test(groups = "unit") public class ServerToNodeMetadataTest { Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/domain/ServerTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/domain/ServerTest.java index 320b2be85a..7be1362aac 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/domain/ServerTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/domain/ServerTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.CreateImageBinderTest") +@Test(groups = "unit") public class ServerTest { public void testStatusDoesntAffectEquals() { Server server1 = new Server(1, "hello"); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseAddressesFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseAddressesFromJsonResponseTest.java index 636f8733c4..c1c6f8ddc4 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseAddressesFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseAddressesFromJsonResponseTest.java @@ -44,7 +44,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseAddressesFromJsonResponseTest") +@Test(groups = "unit") public class ParseAddressesFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseBackupScheduleFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseBackupScheduleFromJsonResponseTest.java index dfb82e5bf2..4789c5c21a 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseBackupScheduleFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseBackupScheduleFromJsonResponseTest.java @@ -44,7 +44,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseBackupScheduleFromJsonResponseTest") +@Test(groups = "unit") public class ParseBackupScheduleFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java index 0b7e4922ba..cc86b85f9d 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java @@ -42,7 +42,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseFlavorFromJsonResponseTest") +@Test(groups = "unit") public class ParseFlavorFromJsonResponseTest { public void test() { Flavor response = parseFlavor(); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorListFromJsonResponseTest.java index 51b2b0136f..1c68567b6f 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorListFromJsonResponseTest.java @@ -40,11 +40,11 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code ParseFlavorListFromJsonResponseTest} + * Tests behavior of {@code ParseFlavorListFromJsonResponse} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudFlavors.ParseFlavorListFromJsonResponseTest") +@Test(groups = "unit") public class ParseFlavorListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java index 39f692cacb..3bf39c67f5 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java @@ -44,7 +44,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseImageFromJsonResponseTest") +@Test(groups = "unit") public class ParseImageFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageListFromJsonResponseTest.java index b9bd7def15..6f4b0dabfd 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageListFromJsonResponseTest.java @@ -42,11 +42,11 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code ParseImageListFromJsonResponseTest} + * Tests behavior of {@code ParseImageListFromJsonResponse} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudImages.ParseImageListFromJsonResponseTest") +@Test(groups = "unit") public class ParseImageListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); DateService dateService = i.getInstance(DateService.class); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseInetAddressListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseInetAddressListFromJsonResponseTest.java index 759dc32124..f0182c4cae 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseInetAddressListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseInetAddressListFromJsonResponseTest.java @@ -43,7 +43,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseInetAddressListFromJsonResponseTest") +@Test(groups = "unit") public class ParseInetAddressListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java index 2345c5a406..05493d5f94 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java @@ -43,11 +43,11 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code ParseServerFromJsonResponseTest} + * Tests behavior of {@code ParseServerFromJsonResponse} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseServerFromJsonResponseTest") +@Test(groups = "unit") public class ParseServerFromJsonResponseTest { public void testApplyInputStreamDetails() throws UnknownHostException { diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerListFromJsonResponseTest.java index 3fb9d0b1e8..27eb40355b 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerListFromJsonResponseTest.java @@ -44,11 +44,11 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code ParseServerListFromJsonResponseTest} + * Tests behavior of {@code ParseServerListFromJsonResponse} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseServerListFromJsonResponseTest") +@Test(groups = "unit") public class ParseServerListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupFromJsonResponseTest.java index 81a8c95c9e..5ebb0ae136 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupFromJsonResponseTest.java @@ -43,7 +43,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.ParseSharedIpGroupFromJsonResponseTest") +@Test(groups = "unit") public class ParseSharedIpGroupFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupListFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupListFromJsonResponseTest.java index 1f2e1b6b46..69c7a75923 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupListFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseSharedIpGroupListFromJsonResponseTest.java @@ -40,11 +40,11 @@ import com.google.inject.Key; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code ParseSharedIpGroupListFromJsonResponseTest} + * Tests behavior of {@code ParseSharedIpGroupListFromJsonResponse} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudSharedIpGroups.ParseSharedIpGroupListFromJsonResponseTest") +@Test(groups = "unit") public class ParseSharedIpGroupListFromJsonResponseTest { Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptionsTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptionsTest.java index 0b03267fe8..7c35953a5a 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptionsTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateServerOptionsTest.java @@ -41,7 +41,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.CreateServerOptionsTest") +@Test(groups = "unit") public class CreateServerOptionsTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptionsTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptionsTest.java index a5c598f5da..95d6ecadc5 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptionsTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptionsTest.java @@ -39,7 +39,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudsharedIpGroups.CreateSharedIpGroupOptionsTest") +@Test(groups = "unit") public class CreateSharedIpGroupOptionsTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/ListOptionsTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/ListOptionsTest.java index 95e3c7b3fe..94c1b73b9a 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/ListOptionsTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/ListOptionsTest.java @@ -36,7 +36,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rackspace.ListOptionsTest") +@Test(groups = "unit") public class ListOptionsTest { public void testWithDetails() { diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptionsTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptionsTest.java index 1994947865..174d9d153b 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptionsTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/options/RebuildServerOptionsTest.java @@ -39,7 +39,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudsharedIpGroups.RebuildServerOptionsTest") +@Test(groups = "unit") public class RebuildServerOptionsTest { Injector injector = Guice.createInjector(new GsonModule()); diff --git a/rackspace/src/test/java/org/jclouds/rackspace/filters/AddTimestampQueryTest.java b/rackspace/src/test/java/org/jclouds/rackspace/filters/AddTimestampQueryTest.java index 324656e5cd..461631919b 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/filters/AddTimestampQueryTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/filters/AddTimestampQueryTest.java @@ -38,7 +38,7 @@ import com.sun.jersey.api.uri.UriBuilderImpl; * @author Adrian Cole */ -@Test(groups = "unit", testName = "rackspace.AddTimestampQueryTest") +@Test(groups = "unit") public class AddTimestampQueryTest { @Test @@ -64,10 +64,9 @@ public class AddTimestampQueryTest { }); - filter.filter(request); + request = filter.filter(request); - assertEquals(request.getRequestLine(), String.format("GET http://momma/?now=%s HTTP/1.1", - date.getTime())); + assertEquals(request.getRequestLine(), String.format("GET http://momma/?now=%s HTTP/1.1", date.getTime())); } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/options/BaseListOptionsTest.java b/rackspace/src/test/java/org/jclouds/rackspace/options/BaseListOptionsTest.java index b43e4724a5..f8ff0b76cd 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/options/BaseListOptionsTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/options/BaseListOptionsTest.java @@ -35,7 +35,7 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rackspace.ListOptionsTest") +@Test(groups = "unit") public class BaseListOptionsTest { public void testChangesSince() { diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/CreateServerOptions.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/CreateServerOptions.java index 63351de27f..f406270565 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/CreateServerOptions.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/CreateServerOptions.java @@ -33,29 +33,29 @@ import org.jclouds.rimuhosting.miro.domain.MetaData; /** * @author Ivan Meredith */ -public class CreateServerOptions extends RimuHostingJsonBinder{ - +public class CreateServerOptions extends RimuHostingJsonBinder { + private String password; private List metaData = new ArrayList(); - + @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { String name = checkNotNull(postParams.get("name")); String imageId = checkNotNull(postParams.get("imageId")); String planId = checkNotNull(postParams.get("planId")); - //There will be cases when the password is null. + // There will be cases when the password is null. String password = this.password; NewServerData newServerData = new NewServerData(new CreateOptions(name, password, imageId), planId); newServerData.setMetaData(metaData); - bindToRequest(request, newServerData); - } - - public CreateServerOptions withPassword(String password){ + return bindToRequest(request, newServerData); + } + + public CreateServerOptions withPassword(String password) { this.password = password; return this; } - - public CreateServerOptions withMetaData(List metaData){ + + public CreateServerOptions withMetaData(List metaData) { this.metaData = metaData; return this; } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java index fb84d86681..118a754532 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java @@ -33,13 +33,15 @@ import org.jclouds.rest.binders.BindToJsonPayload; * @author Ivan Meredith */ public class RimuHostingJsonBinder extends BindToJsonPayload { - public void bindToRequest(HttpRequest request, Map postParams) { - bindToRequest(request, (Object) postParams); + @Override + public R bindToRequest(R request, Map postParams) { + return bindToRequest(request, (Object) postParams); } - public void bindToRequest(HttpRequest request, Object toBind) { + @Override + public R bindToRequest(R request, Object toBind) { Map test = new HashMap(); test.put("request", toBind); - super.bindToRequest(request, test); + return super.bindToRequest(request, test); } } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingRebootJsonBinder.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingRebootJsonBinder.java index 28402b60f8..5803ad286e 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingRebootJsonBinder.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingRebootJsonBinder.java @@ -19,18 +19,22 @@ package org.jclouds.rimuhosting.miro.binder; -import com.google.common.collect.ImmutableMap; +import java.util.Map; + import org.jclouds.http.HttpRequest; +import com.google.common.collect.ImmutableMap; + /** * Need to PUT a static string - * + * * {"request":{"running_state":"RESTARTING"} - * + * * @author Ivan Meredith */ -public class RimuHostingRebootJsonBinder extends RimuHostingJsonBinder{ - public void bindToRequest(HttpRequest request, Object toBind) { - super.bindToRequest(request,(Object)ImmutableMap.of("running_state", "RESTARTING")); - } +public class RimuHostingRebootJsonBinder extends RimuHostingJsonBinder { + @Override + public R bindToRequest(R request, Map postParams) { + return super.bindToRequest(request, (Object) ImmutableMap.of("running_state", "RESTARTING")); + } } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/filters/RimuHostingAuthentication.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/filters/RimuHostingAuthentication.java index acdbd68fe3..4571c0de3d 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/filters/RimuHostingAuthentication.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/filters/RimuHostingAuthentication.java @@ -21,9 +21,6 @@ package org.jclouds.rimuhosting.miro.filters; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; -import java.util.List; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; @@ -33,6 +30,7 @@ import org.jclouds.Constants; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.utils.ModifyRequest; /** * RimuHosting Authentication is a Authorization Header. @@ -43,16 +41,15 @@ import org.jclouds.http.HttpRequestFilter; */ @Singleton public class RimuHostingAuthentication implements HttpRequestFilter { - private List credentialList; + private final String header; @Inject public RimuHostingAuthentication(@Named(Constants.PROPERTY_IDENTITY) String apikey) { - this.credentialList = Collections.singletonList(String.format("rimuhosting apikey=%s", - checkNotNull(apikey, "apikey"))); + this.header = String.format("rimuhosting apikey=%s", checkNotNull(apikey, "apikey")); } @Override - public void filter(HttpRequest request) throws HttpException { - request.getHeaders().replaceValues(HttpHeaders.AUTHORIZATION, credentialList); + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.replaceHeader(request, HttpHeaders.AUTHORIZATION, header); } } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/functions/ParseRimuHostingException.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/functions/ParseRimuHostingException.java index 1fe0916f1f..83823e52b6 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/functions/ParseRimuHostingException.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/functions/ParseRimuHostingException.java @@ -19,7 +19,7 @@ package org.jclouds.rimuhosting.miro.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.lang.reflect.Type; import java.util.Map; diff --git a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/ProvidersInPropertiesTest.java b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/ProvidersInPropertiesTest.java index cc56b32f8f..4f2b82d178 100644 --- a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/ProvidersInPropertiesTest.java +++ b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.rimuhosting.miro; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "rimuhosting") : providers; } diff --git a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingAsyncClientTest.java b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingAsyncClientTest.java index 7d25b9d32e..9ff421c026 100644 --- a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingAsyncClientTest.java +++ b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingAsyncClientTest.java @@ -40,11 +40,12 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; /** - * Tests annotation parsing of {@code RimuHostingAsyncClient} + * Tests behavior of {@code RimuHostingAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "rimuhosting.RimuHostingAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "RimuHostingAsyncClientTest") public class RimuHostingAsyncClientTest extends RestClientTest { public void testCreateServer() throws SecurityException, NoSuchMethodException, IOException { diff --git a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java index 45fc4a4fb5..5f8cc1d13e 100644 --- a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java +++ b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java @@ -48,7 +48,7 @@ import com.google.inject.Module; * * @author Ivan Meredith */ -@Test(groups = "live", testName = "rimuhosting.RimuHostingClientLiveTest") +@Test(groups = "live") public class RimuHostingClientLiveTest { private RimuHostingClient connection; diff --git a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingComputeServiceLiveTest.java b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingComputeServiceLiveTest.java index 49e6ed4b70..f3ed959f14 100755 --- a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingComputeServiceLiveTest.java +++ b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingComputeServiceLiveTest.java @@ -32,7 +32,7 @@ import org.testng.annotations.Test; /** * @author Ivan Meredith */ -@Test(groups = "live", sequential = true, testName = "rimuhosting.RimuHostingNodeServiceLiveTest") +@Test(groups = "live", sequential = true) public class RimuHostingComputeServiceLiveTest extends BaseComputeServiceLiveTest { public RimuHostingComputeServiceLiveTest() { provider = "rimuhosting"; diff --git a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingTemplateBuilderLiveTest.java b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingTemplateBuilderLiveTest.java index 72256eea09..dbb3c1ee53 100644 --- a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingTemplateBuilderLiveTest.java +++ b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/RimuHostingTemplateBuilderLiveTest.java @@ -30,7 +30,7 @@ import com.google.common.base.Predicate; * * @author Adrian Cole */ -@Test(groups = "live", testName = "rimuhosting.RimuHostingTemplateBuilderLiveTest") +@Test(groups = "live") public class RimuHostingTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public RimuHostingTemplateBuilderLiveTest() { diff --git a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java index 77ff384364..fced1621dc 100644 --- a/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java +++ b/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "rimuhosting.RimuHostingComputeServiceContextModuleTest") +@Test(groups = "unit") public class RimuHostingComputeServiceContextModuleTest { public void testAllStatusCovered() { diff --git a/sandbox/boxdotnet/src/main/java/org/jclouds/boxdotnet/handlers/BoxDotNetErrorHandler.java b/sandbox/boxdotnet/src/main/java/org/jclouds/boxdotnet/handlers/BoxDotNetErrorHandler.java index 0599235e73..461d013b0e 100644 --- a/sandbox/boxdotnet/src/main/java/org/jclouds/boxdotnet/handlers/BoxDotNetErrorHandler.java +++ b/sandbox/boxdotnet/src/main/java/org/jclouds/boxdotnet/handlers/BoxDotNetErrorHandler.java @@ -31,7 +31,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Throwables; import com.google.common.io.Closeables; @@ -51,20 +51,20 @@ public class BoxDotNetErrorHandler implements HttpErrorHandler { // it is important to always read fully and close streams String message = parseMessage(response); Exception exception = message != null ? new HttpResponseException(command, response, message) - : new HttpResponseException(command, response); + : new HttpResponseException(command, response); try { - message = message != null ? message : String.format("%s -> %s", command.getRequest() - .getRequestLine(), response.getStatusLine()); + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), + response.getStatusLine()); switch (response.getStatusCode()) { - case 401: - case 403: - exception = new AuthorizationException(message, exception); - break; - case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - exception = new ResourceNotFoundException(message, exception); - } - break; + case 401: + case 403: + exception = new AuthorizationException(message, exception); + break; + case 404: + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + exception = new ResourceNotFoundException(message, exception); + } + break; } } finally { if (response.getPayload() != null) @@ -77,7 +77,7 @@ public class BoxDotNetErrorHandler implements HttpErrorHandler { if (response.getPayload() == null) return null; try { - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } catch (IOException e) { throw new RuntimeException(e); } finally { diff --git a/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java b/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java index 8703f49368..4835ab9735 100644 --- a/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java +++ b/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetAsyncClientTest.java @@ -45,26 +45,25 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "boxdotnet.BoxDotNetAsyncClientTest") +@Test(groups = "unit") public class BoxDotNetAsyncClientTest extends RestClientTest { public void testList() throws SecurityException, NoSuchMethodException, IOException { Method method = BoxDotNetAsyncClient.class.getMethod("list"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1"); // for example, using basic authentication, we should get "only one" // header - assertNonPayloadHeadersEqual(httpRequest, - "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); + assertNonPayloadHeadersEqual(httpRequest, "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); assertPayloadEquals(httpRequest, null, null, false); // TODO: insert expected response class, which probably extends ParseJson diff --git a/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetClientLiveTest.java b/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetClientLiveTest.java index 14f2eca60d..83e0981ec0 100644 --- a/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetClientLiveTest.java +++ b/sandbox/boxdotnet/src/test/java/org/jclouds/boxdotnet/BoxDotNetClientLiveTest.java @@ -39,7 +39,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", testName = "boxdotnet.BoxDotNetClientLiveTest") +@Test(groups = "live") public class BoxDotNetClientLiveTest { private BoxDotNetClient connection; diff --git a/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/compute/options/IBMDeveloperCloudTemplateOptions.java b/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/compute/options/IBMDeveloperCloudTemplateOptions.java index b5aef5c003..027c88f116 100644 --- a/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/compute/options/IBMDeveloperCloudTemplateOptions.java +++ b/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/compute/options/IBMDeveloperCloudTemplateOptions.java @@ -26,7 +26,7 @@ import java.util.Arrays; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.io.Payload; -import org.jclouds.util.Utils; +import org.jclouds.util.Preconditions2; /** * Contains options supported in the {@code ComputeService#runNode} operation on the "ibmdev" @@ -58,7 +58,7 @@ public class IBMDeveloperCloudTemplateOptions extends TemplateOptions { public IBMDeveloperCloudTemplateOptions keyPair(String keyPair) { checkNotNull(keyPair, "use noKeyPair option to request boot without a keypair"); checkState(!noKeyPair, "you cannot specify both options keyPair and noKeyPair"); - Utils.checkNotEmpty(keyPair, "keypair must be non-empty"); + Preconditions2.checkNotEmpty(keyPair, "keypair must be non-empty"); this.keyPair = keyPair; return this; } diff --git a/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/config/IBMDeveloperCloudParserModule.java b/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/config/IBMDeveloperCloudParserModule.java index 3d121554d2..5910e10cd1 100644 --- a/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/config/IBMDeveloperCloudParserModule.java +++ b/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/config/IBMDeveloperCloudParserModule.java @@ -23,10 +23,8 @@ import java.lang.reflect.Type; import java.net.URI; import java.util.Map; -import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.Constants; import org.jclouds.http.HttpUtils; import org.jclouds.json.config.GsonModule.DateAdapter; import org.jclouds.json.config.GsonModule.LongDateAdapter; @@ -58,7 +56,6 @@ public class IBMDeveloperCloudParserModule extends AbstractModule { @Provides @Singleton - @Named(Constants.PROPERTY_GSON_ADAPTERS) public Map provideCustomAdapterBindings(CurlyBraceCapableURIAdapter adapter) { return ImmutableMap. of(URI.class, adapter); } diff --git a/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/handlers/IBMDeveloperCloudErrorHandler.java b/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/handlers/IBMDeveloperCloudErrorHandler.java index 9a0f657723..073aeba3eb 100644 --- a/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/handlers/IBMDeveloperCloudErrorHandler.java +++ b/sandbox/ibmdev/src/main/java/org/jclouds/ibmdev/handlers/IBMDeveloperCloudErrorHandler.java @@ -33,7 +33,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; /** * This will parse and set an appropriate exception on the command object. @@ -52,7 +52,7 @@ public class IBMDeveloperCloudErrorHandler implements HttpErrorHandler { // it is important to always read fully and close streams String message = parseMessage(response); exception = message != null ? new HttpResponseException(command, response, message) : exception; - message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(), + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: @@ -63,7 +63,7 @@ public class IBMDeveloperCloudErrorHandler implements HttpErrorHandler { exception = new AuthorizationException(message, exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; @@ -87,6 +87,6 @@ public class IBMDeveloperCloudErrorHandler implements HttpErrorHandler { public String parseMessage(HttpResponse response) throws IOException { if (response.getPayload() == null) return null; - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } } \ No newline at end of file diff --git a/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/IBMDeveloperCloudAsyncClientTest.java b/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/IBMDeveloperCloudAsyncClientTest.java index e73691f7ad..a433310872 100644 --- a/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/IBMDeveloperCloudAsyncClientTest.java +++ b/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/IBMDeveloperCloudAsyncClientTest.java @@ -54,7 +54,6 @@ import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -72,7 +71,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1"); @@ -80,8 +79,8 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1"); @@ -118,7 +117,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1"); @@ -136,7 +135,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1", + HttpRequest httpRequest = processor.createRequest(method, "1", Image.Visibility.PUBLIC); assertRequestLineEquals(httpRequest, @@ -154,7 +153,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1"); @@ -171,7 +170,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/requests/1 HTTP/1.1"); @@ -188,7 +187,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); @@ -206,7 +205,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1", new Date( + HttpRequest httpRequest = processor.createRequest(method, "1", new Date( 123215235l)); assertRequestLineEquals(httpRequest, @@ -224,7 +223,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); @@ -241,7 +240,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1", + HttpRequest httpRequest = processor.createRequest(method, "1", new RestartInstanceOptions().authorizePublicKey("keyName")); assertRequestLineEquals(httpRequest, @@ -259,7 +258,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1", + HttpRequest httpRequest = processor.createRequest(method, "1", "imageName", "imageDescription"); assertRequestLineEquals(httpRequest, @@ -277,7 +276,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); @@ -294,7 +293,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1"); @@ -311,7 +310,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1"); @@ -328,7 +327,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "key"); + HttpRequest httpRequest = processor.createRequest(method, "key"); assertRequestLineEquals(httpRequest, "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1"); @@ -345,7 +344,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "key", + HttpRequest httpRequest = processor.createRequest(method, "key", "publicbits"); assertRequestLineEquals(httpRequest, @@ -363,7 +362,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "key", + HttpRequest httpRequest = processor.createRequest(method, "key", "publicbits"); assertRequestLineEquals(httpRequest, @@ -382,7 +381,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "key", true); + HttpRequest httpRequest = processor.createRequest(method, "key", true); assertRequestLineEquals(httpRequest, "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1"); @@ -399,7 +398,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1"); @@ -416,7 +415,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1"); @@ -433,7 +432,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1"); @@ -451,13 +450,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "location", + HttpRequest httpRequest = processor.createRequest(method, "location", "name", "format", "size", "offering"); assertRequestLineEquals(httpRequest, "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); - assertPayloadEquals(httpRequest, "location=location&format=format&name=name&size=size&offeringID=offering", + assertPayloadEquals(httpRequest, "location=location&format=format&name=name&offeringID=offering&size=size", "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, httpRequest, ParseVolumeFromJson.class); @@ -471,7 +470,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1", "name", + HttpRequest httpRequest = processor.createRequest(method, "1", "name", "22", "instanceType"); assertRequestLineEquals(httpRequest, @@ -490,7 +489,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "location", + HttpRequest httpRequest = processor.createRequest(method, "location", "name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO") .mountVolume("2", "/mnt").configurationData( ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password", "myPassword2", @@ -514,7 +513,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1"); @@ -531,7 +530,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations HTTP/1.1"); @@ -548,7 +547,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations/1 HTTP/1.1"); @@ -565,7 +564,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1"); @@ -583,7 +582,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1", "offering"); + HttpRequest httpRequest = processor.createRequest(method, "1", "offering"); assertRequestLineEquals(httpRequest, "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1"); @@ -600,7 +599,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "1"); + HttpRequest httpRequest = processor.createRequest(method, "1"); assertRequestLineEquals(httpRequest, "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses/1 HTTP/1.1"); @@ -617,7 +616,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/storage HTTP/1.1"); @@ -633,7 +632,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/address HTTP/1.1"); diff --git a/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/ProvidersInPropertiesTest.java b/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/ProvidersInPropertiesTest.java index 255b152a54..84e8a63cd0 100644 --- a/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/ProvidersInPropertiesTest.java +++ b/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.ibmdev; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "ibmdev") : providers; } diff --git a/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/compute/IBMDeveloperCloudTemplateBuilderLiveTest.java b/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/compute/IBMDeveloperCloudTemplateBuilderLiveTest.java index d4681621ce..6262c130bc 100644 --- a/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/compute/IBMDeveloperCloudTemplateBuilderLiveTest.java +++ b/sandbox/ibmdev/src/test/java/org/jclouds/ibmdev/compute/IBMDeveloperCloudTemplateBuilderLiveTest.java @@ -1,8 +1,8 @@ package org.jclouds.ibmdev.compute; import org.jclouds.compute.BaseTemplateBuilderLiveTest; -import org.jclouds.compute.OsFamilyVersion64Bit; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.os.OsFamilyVersion64Bit; import org.testng.annotations.Test; import com.google.common.base.Predicate; diff --git a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java index 8bac5ef16a..1cc5cae6e6 100644 --- a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java +++ b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java @@ -17,7 +17,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "libvirt.LibvirtComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class LibvirtComputeServiceLiveTest extends BaseComputeServiceLiveTest { public LibvirtComputeServiceLiveTest() { provider = "libvirt"; diff --git a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtExperimentLiveTest.java b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtExperimentLiveTest.java index 9431fb6a52..6f4647025d 100644 --- a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtExperimentLiveTest.java +++ b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtExperimentLiveTest.java @@ -35,7 +35,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", testName = "libvirt.LibvirtExperimentLiveTest") +@Test(groups = "live") public class LibvirtExperimentLiveTest { protected String provider = "libvirt"; protected String identity; diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/PCSAsyncClient.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/PCSAsyncClient.java index 2103b5a9e4..00399b723d 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/PCSAsyncClient.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/PCSAsyncClient.java @@ -97,8 +97,7 @@ public interface PCSAsyncClient { @Path("/contents") @Endpoint(RootContainer.class) @Produces("application/vnd.csp.container-info+xml") - ListenableFuture createContainer( - @BinderParam(BindContainerNameToXmlPayload.class) String container); + ListenableFuture createContainer(@BinderParam(BindContainerNameToXmlPayload.class) String container); /** * @see PCSAsyncClient#createContainer @@ -106,7 +105,7 @@ public interface PCSAsyncClient { @POST @Path("/contents") ListenableFuture createContainer(@EndpointParam URI parent, - @BinderParam(BindContainerNameToXmlPayload.class) String container); + @BinderParam(BindContainerNameToXmlPayload.class) String container); /** * @see PCSAsyncClient#deleteContainer @@ -121,7 +120,7 @@ public interface PCSAsyncClient { @POST @Path("/contents") ListenableFuture uploadFile(@EndpointParam URI container, - @BinderParam(BindPCSFileToMultipartForm.class) PCSFile object); + @BinderParam(BindPCSFileToMultipartForm.class) PCSFile object); /** * @see PCSAsyncClient#createFile @@ -129,15 +128,14 @@ public interface PCSAsyncClient { @POST @Path("/contents") ListenableFuture createFile(@EndpointParam URI container, - @BinderParam(BindFileInfoToXmlPayload.class) PCSFile object); + @BinderParam(BindFileInfoToXmlPayload.class) PCSFile object); /** * @see PCSAsyncClient#uploadBlock */ @PUT @Path("/content") - ListenableFuture uploadBlock(@EndpointParam URI file, PCSFile object, - PutBlockOptions... options); + ListenableFuture uploadBlock(@EndpointParam URI file, PCSFile object, PutBlockOptions... options); /** * @see PCSAsyncClient#deleteFile @@ -168,8 +166,8 @@ public interface PCSAsyncClient { */ @PUT @Path("/metadata/{key}") - ListenableFuture putMetadataItem(@EndpointParam URI resource, - @PathParam("key") String key, @BinderParam(BindToStringPayload.class) String value); + ListenableFuture putMetadataItem(@EndpointParam URI resource, @PathParam("key") String key, + @BinderParam(BindToStringPayload.class) String value); /** * @see PCSAsyncClient#addMetadataItemToMap @@ -177,6 +175,6 @@ public interface PCSAsyncClient { @GET @ResponseParser(AddMetadataItemIntoMap.class) @Path("/metadata/{key}") - ListenableFuture addMetadataItemToMap(@EndpointParam URI resource, - @PathParam("key") String key, Map map); + ListenableFuture addMetadataItemToMap(@EndpointParam URI resource, @PathParam("key") String key, + Map map); } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayload.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayload.java index 5387dec68a..606bdfd784 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayload.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayload.java @@ -31,9 +31,10 @@ import org.jclouds.rest.Binder; */ @Singleton public class BindContainerNameToXmlPayload implements Binder { - - public void bindToRequest(HttpRequest request, Object toBind) { - String container = String.format("%s", toBind); + @Override + public R bindToRequest(R request, Object input) { + String container = String.format("%s", input); request.setPayload(container); + return request; } } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayload.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayload.java index 7c48017f58..3ae1cbc174 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayload.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayload.java @@ -20,30 +20,32 @@ package org.jclouds.mezeo.pcs2.binders; import java.io.File; -import java.util.Collections; +import javax.inject.Singleton; import javax.ws.rs.core.HttpHeaders; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.rest.Binder; +import com.google.common.collect.ImmutableMultimap; + /** * * @author Adrian Cole * */ +@Singleton public class BindFileInfoToXmlPayload implements Binder { - public void bindToRequest(HttpRequest request, Object toBind) { - PCSFile blob = (PCSFile) toBind; - String file = String.format( - "%s%sfalse", - new File(blob.getMetadata().getName()).getName(), blob.getMetadata().getMimeType()); + @Override + public R bindToRequest(R request, Object input) { + PCSFile blob = (PCSFile) input; + String file = String.format("%s%sfalse", + new File(blob.getMetadata().getName()).getName(), blob.getMetadata().getMimeType()); request.setPayload(file); - request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH, - Collections.singletonList(file.getBytes().length + "")); - request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, - Collections.singletonList("application/vnd.csp.file-info+xml")); + return ModifyRequest.replaceHeaders(request, ImmutableMultimap. of(HttpHeaders.CONTENT_LENGTH, + file.getBytes().length + "", HttpHeaders.CONTENT_TYPE, "application/vnd.csp.file-info+xml")); } } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindPCSFileToMultipartForm.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindPCSFileToMultipartForm.java index 737cece252..d9efc5d6d4 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindPCSFileToMultipartForm.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/binders/BindPCSFileToMultipartForm.java @@ -42,11 +42,12 @@ public class BindPCSFileToMultipartForm implements Binder { this.file2Blob = file2Blob; } - public void bindToRequest(HttpRequest request, Object payload) { - PCSFile file = (PCSFile) payload; - checkNotNull(file.getPayload().getContentLength(), "contentLength"); - checkArgument(file.getPayload().getContentLength() <= 2l * 1024 * 1024 * 1024, - "maximum size for POST request is 2GB"); - blobBinder.bindToRequest(request, file2Blob.apply(file)); + @Override + public R bindToRequest(R request, Object input) { + PCSFile file = (PCSFile) input; + checkNotNull(file.getPayload().getContentMetadata().getContentLength(), "contentLength"); + checkArgument(file.getPayload().getContentMetadata().getContentLength() <= 2l * 1024 * 1024 * 1024, + "maximum size for POST request is 2GB"); + return blobBinder.bindToRequest(request, file2Blob.apply(file)); } } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/BlobToFileInfo.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/BlobToFileInfo.java index 792668f5c5..153711d547 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/BlobToFileInfo.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/BlobToFileInfo.java @@ -32,14 +32,15 @@ import com.google.common.base.Function; */ @Singleton public class BlobToFileInfo implements Function { + @Override public MutableFileInfo apply(BlobMetadata base) { MutableFileInfo to = new MutableFileInfoImpl(); to.setUrl(base.getUri()); - to.setMimeType(base.getContentType()); + to.setMimeType(base.getContentMetadata().getContentType()); to.setName(base.getName()); to.setModified(base.getLastModified()); - if (base.getSize() != null) - to.setBytes(base.getSize()); + if (base.getContentMetadata().getContentLength() != null) + to.setBytes(base.getContentMetadata().getContentLength()); return to; } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/FileInfoToBlobMetadata.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/FileInfoToBlobMetadata.java index e346ea34db..a5af524c9b 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/FileInfoToBlobMetadata.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/blobstore/functions/FileInfoToBlobMetadata.java @@ -27,7 +27,7 @@ import org.jclouds.blobstore.domain.MutableBlobMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl; import org.jclouds.mezeo.pcs2.domain.FileInfo; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Function; @@ -38,19 +38,20 @@ import com.google.common.base.Function; public class FileInfoToBlobMetadata implements Function { public static final Pattern OBJECTS_PATTERN = Pattern.compile(".*objects/"); + @Override public MutableBlobMetadata apply(FileInfo from) { MutableBlobMetadata to = new MutableBlobMetadataImpl(); if (from.getUrl() != null) { - to.setId(Utils.replaceAll(from.getUrl().getPath(), OBJECTS_PATTERN, "")); + to.setId(Strings2.replaceAll(from.getUrl().getPath(), OBJECTS_PATTERN, "")); } to.setUri(from.getUrl()); to.setName(from.getName()); if (from.getMimeType() != null) - to.setContentType(from.getMimeType()); + to.getContentMetadata().setContentType(from.getMimeType()); if (from.getModified() != null) to.setLastModified(from.getModified()); if (from.getBytes() != null) - to.setSize(from.getBytes()); + to.getContentMetadata().setContentLength(from.getBytes()); to.setType(StorageType.BLOB); return to; } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/domain/PCSFile.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/domain/PCSFile.java index 82c3b587be..1a0a65df8f 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/domain/PCSFile.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/domain/PCSFile.java @@ -19,10 +19,11 @@ package org.jclouds.mezeo.pcs2.domain; +import javax.annotation.Nullable; + import org.jclouds.io.PayloadEnclosing; import com.google.common.collect.Multimap; -import com.google.inject.internal.Nullable; /** * diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/AddMetadataItemIntoMap.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/AddMetadataItemIntoMap.java index fe3ddef2e2..d442d2b2c3 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/AddMetadataItemIntoMap.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/AddMetadataItemIntoMap.java @@ -38,7 +38,7 @@ import com.google.common.base.Function; * * @author Adrian Cole */ -public class AddMetadataItemIntoMap implements Function, InvocationContext { +public class AddMetadataItemIntoMap implements Function, InvocationContext { ReturnStringIf2xx returnIf200; private GeneratedHttpRequest request; @@ -48,9 +48,7 @@ public class AddMetadataItemIntoMap implements Function, Inv } @SuppressWarnings("unchecked") - public Void apply(HttpResponse from) - - { + public Void apply(HttpResponse from) { checkState(request.getArgs() != null, "args should be initialized at this point"); Map map = null; String key = null; @@ -69,8 +67,7 @@ public class AddMetadataItemIntoMap implements Function, Inv @Override public AddMetadataItemIntoMap 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/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnFalseIfContainerNotFound.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnFalseIfContainerNotFound.java index a79a18db56..398435181e 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnFalseIfContainerNotFound.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnFalseIfContainerNotFound.java @@ -19,7 +19,7 @@ package org.jclouds.mezeo.pcs2.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; @@ -34,6 +34,7 @@ import com.google.common.base.Function; @Singleton public class ReturnFalseIfContainerNotFound implements Function { + @Override public Boolean apply(Exception from) { if (from instanceof ContainerNotFoundException) { return false; diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnTrueIfContainerAlreadyExists.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnTrueIfContainerAlreadyExists.java index dd5b058e37..b2b04f45d5 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnTrueIfContainerAlreadyExists.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/functions/ReturnTrueIfContainerAlreadyExists.java @@ -19,7 +19,7 @@ package org.jclouds.mezeo.pcs2.functions; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import javax.inject.Singleton; @@ -33,7 +33,7 @@ import com.google.common.base.Function; */ @Singleton public class ReturnTrueIfContainerAlreadyExists implements Function { - + @Override public Boolean apply(Exception from) { if (from instanceof HttpResponseException) { HttpResponseException responseException = (HttpResponseException) from; diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/ContainerHandler.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/ContainerHandler.java index f4e06e6892..0d07104e9b 100755 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/ContainerHandler.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/ContainerHandler.java @@ -36,7 +36,7 @@ import org.jclouds.mezeo.pcs2.domain.ResourceInfo; import org.jclouds.mezeo.pcs2.domain.internal.ContainerInfoImpl; import org.jclouds.mezeo.pcs2.domain.internal.ContainerListImpl; import org.jclouds.mezeo.pcs2.domain.internal.FileInfoImpl; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.xml.sax.Attributes; import org.xml.sax.SAXException; @@ -174,7 +174,7 @@ public class ContainerHandler extends ParseSax.HandlerWithResult } else if (qName.equals("metadata-item")) { int index = attributes.getIndex("xlink:href"); if (index != -1) { - String key = Utils.replaceAll(attributes.getValue(index), METADATA_PATTERN, ""); + String key = Strings2.replaceAll(attributes.getValue(index), METADATA_PATTERN, ""); metadataItems.put(key.toLowerCase(), URI.create(attributes.getValue(index))); } } diff --git a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/FileHandler.java b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/FileHandler.java index 79552d5dcc..e99c4f70fd 100644 --- a/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/FileHandler.java +++ b/sandbox/mezeo/pcs2/core/src/main/java/org/jclouds/mezeo/pcs2/xml/FileHandler.java @@ -30,7 +30,7 @@ import org.jclouds.date.DateService; import org.jclouds.http.functions.ParseSax; import org.jclouds.mezeo.pcs2.domain.FileInfoWithMetadata; import org.jclouds.mezeo.pcs2.domain.internal.FileInfoWithMetadataImpl; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.xml.sax.Attributes; import org.xml.sax.SAXException; @@ -88,7 +88,7 @@ public class FileHandler extends ParseSax.HandlerWithResult { } @Override - public ContextSpec createContextSpec() { + public RestContextSpec createContextSpec() { Properties properties = new Properties(); properties.setProperty("pcs.apiversion", "foo"); properties.setProperty("pcs.endpoint", "http://goo"); diff --git a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSClientLiveTest.java b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSClientLiveTest.java index 2c08101aa5..460c9a0286 100644 --- a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSClientLiveTest.java +++ b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSClientLiveTest.java @@ -36,7 +36,6 @@ import java.util.concurrent.TimeoutException; import javax.inject.Provider; import javax.ws.rs.core.UriBuilder; -import org.jboss.resteasy.specimpl.UriBuilderImpl; import org.jclouds.blobstore.KeyNotFoundException; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; @@ -48,13 +47,14 @@ import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.ResourceInfo; import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContextFactory; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.inject.Module; +import com.sun.jersey.api.uri.UriBuilderImpl; /** * Tests behavior of {@code PCSDiscovery} @@ -194,7 +194,7 @@ public class PCSClientLiveTest { } // Test GET of object (including updated metadata) InputStream file = connection.downloadFile(objectURI); - assertEquals(Utils.toStringAndClose(file), data); + assertEquals(Strings2.toStringAndClose(file), data); validateFileInfoAndNameIsInMetadata(container, objectURI, "object", new Long(data.length())); try { @@ -226,7 +226,7 @@ public class PCSClientLiveTest { validateFileInfoAndNameIsInMetadata(container, objectURI, name, new Long(data.length())); file = connection.downloadFile(objectURI); - assertEquals(Utils.toStringAndClose(file), data); + assertEquals(Strings2.toStringAndClose(file), data); // change data in an existing file data = "Here is my datum"; @@ -235,7 +235,7 @@ public class PCSClientLiveTest { validateFileInfoAndNameIsInMetadata(container, objectURI, name, new Long(data.length())); file = connection.downloadFile(objectURI); - assertEquals(Utils.toStringAndClose(file), data); + assertEquals(Strings2.toStringAndClose(file), data); connection.deleteFile(objectURI); connection.deleteContainer(container); diff --git a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSCloudTest.java b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSCloudTest.java index 67770ddd1d..6a588b30a1 100644 --- a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSCloudTest.java +++ b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/PCSCloudTest.java @@ -31,7 +31,7 @@ import org.jclouds.http.functions.ParseSax; import org.jclouds.mezeo.pcs2.PCSCloudAsyncClient.Response; import org.jclouds.mezeo.pcs2.xml.CloudXlinkHandler; import org.jclouds.rest.RestClientTest; -import org.jclouds.rest.RestContextFactory.ContextSpec; +import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -67,7 +67,7 @@ public class PCSCloudTest extends RestClientTest { } @Override - public ContextSpec createContextSpec() { + public RestContextSpec createContextSpec() { return contextSpec("test", "http://localhost:8080", "1", "identity", "credential", PCSCloudClient.class, PCSCloudAsyncClient.class); } diff --git a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/ProvidersInPropertiesTest.java b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/ProvidersInPropertiesTest.java index 11fdbda58c..b993293b42 100644 --- a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/ProvidersInPropertiesTest.java +++ b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.mezeo.pcs2; import org.jclouds.blobstore.util.BlobStoreUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "pcs") : providers; } diff --git a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayloadTest.java b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayloadTest.java index 7bc0a3fe18..7415aa581f 100644 --- a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayloadTest.java +++ b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindContainerNameToXmlPayloadTest.java @@ -40,9 +40,9 @@ public class BindContainerNameToXmlPayloadTest { binder.bindToRequest(request, "foo"); assertEquals(request.getPayload().getRawContent(), "foo"); - assertEquals(request.getPayload().getContentLength(), new Long( + assertEquals(request.getPayload().getContentMetadata().getContentLength(), new Long( "foo".getBytes().length)); - assertEquals(request.getPayload().getContentType(), "application/unknown"); + assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/unknown"); } } diff --git a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayloadTest.java b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayloadTest.java index 345e60258a..b537542f86 100644 --- a/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayloadTest.java +++ b/sandbox/mezeo/pcs2/core/src/test/java/org/jclouds/mezeo/pcs2/binders/BindFileInfoToXmlPayloadTest.java @@ -39,25 +39,21 @@ import com.google.inject.Guice; */ @Test(groups = "unit", testName = "pcs2.BindFileInfoToXmlPayloadTest") public class BindFileInfoToXmlPayloadTest { - PCSFile.Factory factory = Guice.createInjector(new PCSObjectModule()).getInstance( - PCSFile.Factory.class); + PCSFile.Factory factory = Guice.createInjector(new PCSObjectModule()).getInstance(PCSFile.Factory.class); public void test() { BindFileInfoToXmlPayload binder = new BindFileInfoToXmlPayload(); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); PCSFile file = factory.create(null); file.getMetadata().setName("foo"); - binder.bindToRequest(request, file); + request = binder.bindToRequest(request, file); + assertEquals(request.getPayload().getRawContent(), + "fooapplication/octet-streamfalse"); assertEquals( - request.getPayload().getRawContent(), - "fooapplication/octet-streamfalse"); - assertEquals( - request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), - "fooapplication/octet-streamfalse" - .getBytes().length - + ""); - assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE), - "application/vnd.csp.file-info+xml"); + request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), + "fooapplication/octet-streamfalse" + .getBytes().length + ""); + assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE), "application/vnd.csp.file-info+xml"); } @@ -67,17 +63,14 @@ public class BindFileInfoToXmlPayloadTest { PCSFile file = factory.create(null); file.getMetadata().setName("subdir/foo"); - binder.bindToRequest(request, file); + request = binder.bindToRequest(request, file); + assertEquals(request.getPayload().getRawContent(), + "fooapplication/octet-streamfalse"); assertEquals( - request.getPayload().getRawContent(), - "fooapplication/octet-streamfalse"); - assertEquals( - request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), - "fooapplication/octet-streamfalse" - .getBytes().length - + ""); - assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE), - "application/vnd.csp.file-info+xml"); + request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), + "fooapplication/octet-streamfalse" + .getBytes().length + ""); + assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE), "application/vnd.csp.file-info+xml"); } } diff --git a/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java b/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java index a99212590b..f423e77d5c 100644 --- a/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java +++ b/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java @@ -19,6 +19,33 @@ package org.jclouds.http.ning; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Throwables.propagate; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map.Entry; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpCommandExecutorService; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.handlers.DelegatingErrorHandler; +import org.jclouds.http.handlers.DelegatingRetryHandler; +import org.jclouds.http.internal.BaseHttpCommandExecutorService; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.io.payloads.FilePayload; +import org.jclouds.rest.internal.RestAnnotationProcessor; + import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.LinkedHashMultimap; @@ -32,31 +59,6 @@ import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import com.ning.http.client.Response; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpRequestFilter; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.HttpUtils; -import org.jclouds.http.handlers.DelegatingErrorHandler; -import org.jclouds.http.handlers.DelegatingRetryHandler; -import org.jclouds.http.internal.BaseHttpCommandExecutorService; -import org.jclouds.io.Payload; -import org.jclouds.io.Payloads; -import org.jclouds.io.payloads.FilePayload; - -import javax.inject.Singleton; -import javax.ws.rs.core.HttpHeaders; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Throwables.propagate; /** * Todo Write me @@ -76,8 +78,8 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic @Inject public NingHttpCommandExecutorService(AsyncHttpClient client, ConvertToNingRequest convertToNingRequest, - ConvertToJCloudsResponse convertToJCloudsResponse, DelegatingRetryHandler retryHandler, - DelegatingErrorHandler errorHandler) { + ConvertToJCloudsResponse convertToJCloudsResponse, DelegatingRetryHandler retryHandler, + DelegatingErrorHandler errorHandler) { this.client = client; this.convertToNingRequest = convertToNingRequest; this.convertToJCloudsResponse = convertToJCloudsResponse; @@ -89,7 +91,7 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic public ListenableFuture submit(HttpCommand command) { try { for (;;) { - Future responseF = client.executeRequest(convertToNingRequest.apply(command.getRequest())); + Future responseF = client.executeRequest(convertToNingRequest.apply(command.getCurrentRequest())); final HttpResponse httpResponse = convertToJCloudsResponse.apply(responseF.get()); int statusCode = httpResponse.getStatusCode(); if (statusCode >= 300) { @@ -125,7 +127,7 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic @Singleton public static class ConvertToNingRequest implements Function { - public Request apply(HttpRequest request) { + public Request apply(HttpRequest request) { for (HttpRequestFilter filter : request.getFilters()) { filter.filter(request); @@ -138,22 +140,22 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic boolean chunked = "chunked".equals(request.getFirstHeaderOrNull("Transfer-Encoding")); if (request.getPayload().getContentMetadata().getContentMD5() != null) - builder.addHeader("Content-MD5", CryptoStreams.base64(request.getPayload().getContentMetadata() - .getContentMD5())); + builder.addHeader("Content-MD5", + CryptoStreams.base64(request.getPayload().getContentMetadata().getContentMD5())); if (request.getPayload().getContentMetadata().getContentType() != null) builder.addHeader(HttpHeaders.CONTENT_TYPE, request.getPayload().getContentMetadata().getContentType()); if (request.getPayload().getContentMetadata().getContentLanguage() != null) builder.addHeader(HttpHeaders.CONTENT_LANGUAGE, request.getPayload().getContentMetadata() - .getContentLanguage()); + .getContentLanguage()); if (request.getPayload().getContentMetadata().getContentEncoding() != null) builder.addHeader(HttpHeaders.CONTENT_ENCODING, request.getPayload().getContentMetadata() - .getContentEncoding()); + .getContentEncoding()); if (request.getPayload().getContentMetadata().getContentDisposition() != null) builder.addHeader("Content-Disposition", request.getPayload().getContentMetadata() - .getContentDisposition()); + .getContentDisposition()); if (!chunked) { Long length = checkNotNull(request.getPayload().getContentMetadata().getContentLength(), - "payload.getContentLength"); + "payload.getContentLength"); builder.addHeader(HttpHeaders.CONTENT_LENGTH, length.toString()); } setPayload(builder, payload); @@ -171,23 +173,17 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic return builder.build(); } - void setPayload(RequestBuilder requestBuilder, Payload payload) { - if (payload instanceof FilePayload) { - requestBuilder.setBody(((FilePayload) payload).getRawContent()); - } else { - requestBuilder.setBody(payload.getInput()); - } - } + void setPayload(RequestBuilder requestBuilder, Payload payload) { + if (payload instanceof FilePayload) { + requestBuilder.setBody(((FilePayload) payload).getRawContent()); + } else { + requestBuilder.setBody(payload.getInput()); + } + } } @Singleton public static class ConvertToJCloudsResponse implements Function { - private final HttpUtils utils; - - @Inject - ConvertToJCloudsResponse(HttpUtils utils) { - this.utils = utils; - } public HttpResponse apply(Response nativeResponse) { @@ -201,14 +197,14 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic } Payload payload = in != null ? Payloads.newInputStreamPayload(in) : null; - HttpResponse response = new HttpResponse(nativeResponse.getStatusCode(), nativeResponse.getStatusText(), - payload); Multimap headers = LinkedHashMultimap.create(); for (Entry> header : nativeResponse.getHeaders()) { headers.putAll(header.getKey(), header.getValue()); } - utils.setPayloadPropertiesFromHeaders(headers, response); - return response; + if (payload != null) + payload.getContentMetadata().setPropertiesFromHttpHeaders(headers); + return new HttpResponse(nativeResponse.getStatusCode(), nativeResponse.getStatusText(), payload, + RestAnnotationProcessor.filterOutContentHeaders(headers)); } } } diff --git a/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java b/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java index 7fe8eb1774..d30cd30a66 100644 --- a/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java +++ b/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java @@ -25,18 +25,11 @@ import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT; import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST; import static org.jclouds.Constants.PROPERTY_SO_TIMEOUT; import static org.jclouds.Constants.PROPERTY_USER_THREADS; -import static org.testng.Assert.assertEquals; -import java.io.IOException; -import java.net.MalformedURLException; import java.util.Properties; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; import org.jclouds.http.BaseHttpCommandExecutorServiceIntegrationTest; import org.jclouds.http.ning.config.NingHttpCommandExecutorServiceModule; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import com.google.inject.Module; diff --git a/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParams.java b/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParams.java index 07f9ec5d08..04446adad9 100644 --- a/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParams.java +++ b/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParams.java @@ -21,7 +21,6 @@ package org.jclouds.nirvanix.sdn.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.http.HttpUtils.addQueryParamTo; import java.util.List; import java.util.Map; @@ -33,6 +32,7 @@ import javax.inject.Singleton; import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.rest.Binder; import com.google.common.collect.Lists; @@ -47,14 +47,13 @@ public class BindMetadataToQueryParams implements Binder { } @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Object input) { - checkArgument(checkNotNull(input, "input") instanceof Map, - "this binder is only valid for Maps!"); + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Maps!"); Map userMetadata = (Map) input; List metadata = Lists.newArrayList(); for (Entry entry : userMetadata.entrySet()) { metadata.add(String.format("%s:%s", entry.getKey().toLowerCase(), entry.getValue())); } - addQueryParamTo(request, "metadata", metadata, builder.get()); + return ModifyRequest.addQueryParam(request, "metadata", metadata, builder.get()); } } diff --git a/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequest.java b/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequest.java index a12d0b896b..ebb84b99bf 100644 --- a/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequest.java +++ b/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequest.java @@ -19,8 +19,6 @@ package org.jclouds.nirvanix.sdn.filters; -import static org.jclouds.http.HttpUtils.addQueryParamTo; - import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -32,6 +30,7 @@ import javax.ws.rs.core.UriBuilder; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.nirvanix.sdn.SessionToken; import org.jclouds.nirvanix.sdn.reference.SDNQueryParams; @@ -81,15 +80,15 @@ public class AddSessionTokenToRequest implements HttpRequestFilter { } @Inject - public AddSessionTokenToRequest(@SessionToken Provider authTokenProvider, - Provider builder) { + public AddSessionTokenToRequest(@SessionToken Provider authTokenProvider, Provider builder) { this.builder = builder; this.authTokenProvider = authTokenProvider; authToken = new AtomicReference(); } - public void filter(HttpRequest request) throws HttpException { - addQueryParamTo(request, SDNQueryParams.SESSIONTOKEN, getSessionToken(), builder.get()); + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.addQueryParam(request, SDNQueryParams.SESSIONTOKEN, getSessionToken(), builder.get()); } } \ No newline at end of file diff --git a/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPath.java b/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPath.java index aa722a0445..ddc5aa3703 100644 --- a/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPath.java +++ b/sandbox/nirvanix/sdn/core/src/main/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPath.java @@ -19,7 +19,7 @@ package org.jclouds.nirvanix.sdn.filters; -import static org.jclouds.http.HttpUtils.changePathTo; +import java.net.URI; import javax.inject.Inject; import javax.inject.Named; @@ -48,14 +48,15 @@ public class InsertUserContextIntoPath implements HttpRequestFilter { @Inject public InsertUserContextIntoPath(AddSessionTokenToRequest sessionManager, - @Named(SDNConstants.PROPERTY_SDN_APPNAME) String appname, - @Named(SDNConstants.PROPERTY_SDN_USERNAME) String username, Provider builder) { + @Named(SDNConstants.PROPERTY_SDN_APPNAME) String appname, + @Named(SDNConstants.PROPERTY_SDN_USERNAME) String username, Provider builder) { this.builder = builder; this.sessionManager = sessionManager; this.pathPrefix = String.format("/%s/%s/", appname, username); } - public void filter(HttpRequest request) throws HttpException { + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { String sessionToken = sessionManager.getSessionToken(); int prefixIndex = request.getEndpoint().getPath().indexOf(pathPrefix); String path; @@ -64,7 +65,8 @@ public class InsertUserContextIntoPath implements HttpRequestFilter { } else { // replace token path = "/" + sessionToken + request.getEndpoint().getPath().substring(prefixIndex); } - changePathTo(request, path, builder.get()); + URI newEndpoint = builder.get().uri(request.getEndpoint()).replacePath(path).build(); + return request.toBuilder().endpoint(newEndpoint).build(); } } \ No newline at end of file diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/ProvidersInPropertiesTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/ProvidersInPropertiesTest.java index b75ed52d19..5b208d25f1 100644 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/ProvidersInPropertiesTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.nirvanix.sdn; import org.jclouds.blobstore.util.BlobStoreUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "sdn") : providers; } diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAsyncClientTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAsyncClientTest.java index 185f3f3022..1ca527241f 100644 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAsyncClientTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAsyncClientTest.java @@ -42,7 +42,7 @@ import org.jclouds.nirvanix.sdn.reference.SDNConstants; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; -import org.jclouds.rest.RestContextFactory.ContextSpec; +import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -184,7 +184,7 @@ public class SDNAsyncClientTest extends RestClientTest { } @Override - public ContextSpec createContextSpec() { + public RestContextSpec createContextSpec() { return new RestContextFactory().createContextSpec("sdn", "user", "password", new Properties()); } } diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthAsyncClientTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthAsyncClientTest.java index b4e3962dc5..1df1dc6c67 100755 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthAsyncClientTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthAsyncClientTest.java @@ -28,7 +28,7 @@ import org.jclouds.http.HttpRequest; import org.jclouds.nirvanix.sdn.SDNAuthenticationLiveTest.SDNAuthClient; import org.jclouds.nirvanix.sdn.functions.ParseSessionTokenFromJsonResponse; import org.jclouds.rest.RestClientTest; -import org.jclouds.rest.RestContextFactory.ContextSpec; +import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -68,7 +68,7 @@ public class SDNAuthAsyncClientTest extends RestClientTest { } @Override - public ContextSpec createContextSpec() { + public RestContextSpec createContextSpec() { return contextSpec("test", "http://localhost:8080", "1", "identity", "credential", SDNAuthClient.class, SDNAuthAsyncClient.class); } diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthenticationLiveTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthenticationLiveTest.java index 08b504bd55..f2f3f083db 100644 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthenticationLiveTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNAuthenticationLiveTest.java @@ -32,7 +32,7 @@ import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.rest.RestContext; -import org.jclouds.rest.RestContextFactory.ContextSpec; +import org.jclouds.rest.RestContextSpec; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -74,7 +74,7 @@ public class SDNAuthenticationLiveTest { identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity"); credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential"); - ContextSpec contextSpec = contextSpec("test", endpoint, "1", identity, + RestContextSpec contextSpec = contextSpec("test", endpoint, "1", identity, credential, SDNAuthClient.class, SDNAuthAsyncClient.class); context = createContextBuilder( diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNClientLiveTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNClientLiveTest.java index 9dd5c20a80..01431f9538 100644 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNClientLiveTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/SDNClientLiveTest.java @@ -83,7 +83,7 @@ public class SDNClientLiveTest { blob.setPayload("value"); Payloads.calculateMD5(blob); - byte[] md5 = blob.getMetadata().getContentMD5(); + byte[] md5 = blob.getMetadata().getContentMetadata().getContentMD5(); connection.upload(uploadInfo.getHost(), uploadInfo.getToken(), containerName, blob); Map metadata = connection.getMetadata(containerName + "/test.txt"); diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParamsTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParamsTest.java index 9d7a844273..3df79ef548 100644 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParamsTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/binders/BindMetadataToQueryParamsTest.java @@ -29,12 +29,12 @@ import javax.inject.Provider; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.UriBuilder; -import org.jboss.resteasy.specimpl.UriBuilderImpl; import org.jclouds.http.HttpRequest; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; +import com.sun.jersey.api.uri.UriBuilderImpl; /** * Tests behavior of {@code BindMetadataToQueryParams} @@ -47,14 +47,14 @@ public class BindMetadataToQueryParamsTest { @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeMap() { BindMetadataToQueryParams binder = new BindMetadataToQueryParams(null); - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"), new char[]{ '/', ':' }); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"), new char[] { '/', ':' }); binder.bindToRequest(request, new File("foo")); } @Test public void testCorrect() throws SecurityException, NoSuchMethodException { - HttpRequest request = new HttpRequest("GET", URI.create("http://momma/"), new char[]{ '/', ':' }); + HttpRequest request = new HttpRequest("GET", URI.create("http://momma/"), new char[] { '/', ':' }); BindMetadataToQueryParams binder = new BindMetadataToQueryParams(new Provider() { @@ -65,7 +65,7 @@ public class BindMetadataToQueryParamsTest { }); - binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")); + request = binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")); assertEquals(request.getRequestLine(), "GET http://momma/?metadata=imagename:foo&metadata=serverid:2 HTTP/1.1"); diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequestTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequestTest.java index 3eb402d386..bb14a5ec4c 100755 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequestTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/AddSessionTokenToRequestTest.java @@ -66,25 +66,24 @@ public class AddSessionTokenToRequestTest { public Object[][] dataProvider() throws SecurityException, NoSuchMethodException { RestAnnotationProcessor factory = injector.getInstance(Key - .get(new TypeLiteral>() { - })); + .get(new TypeLiteral>() { + })); Method method = TestService.class.getMethod("foo", URI.class); return new Object[][] { { factory.createRequest(method, new Object[] { URI.create("https://host:443") }) }, - { factory.createRequest(method, new Object[] { URI.create("https://host/path") }) }, - { factory.createRequest(method, new Object[] { URI.create("https://host/?query") }) + { factory.createRequest(method, new Object[] { URI.create("https://host/path") }) }, + { factory.createRequest(method, new Object[] { URI.create("https://host/?query") }) - } }; + } }; } @Test(dataProvider = "dataProvider") public void testRequests(HttpRequest request) { String token = filter.getSessionToken(); - String query = request.getEndpoint().getQuery(); - filter.filter(request); + request = filter.filter(request); assertEquals(request.getEndpoint().getQuery(), query == null ? "sessionToken=" + token : query + "&sessionToken=" - + token); + + token); } @Test @@ -102,27 +101,26 @@ public class AddSessionTokenToRequestTest { @BeforeClass protected void createFilter() { injector = Guice.createInjector(new RestModule(), new ExecutorServiceModule(MoreExecutors.sameThreadExecutor(), - MoreExecutors.sameThreadExecutor()), new JavaUrlHttpCommandExecutorServiceModule(), - new AbstractModule() { + MoreExecutors.sameThreadExecutor()), new JavaUrlHttpCommandExecutorServiceModule(), new AbstractModule() { - protected void configure() { - bind(DateService.class); - Names.bindProperties(this.binder(), new SDNPropertiesBuilder(new Properties()).credentials( - "appkey/appname/username", "password").build()); - bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() { - public Logger getLogger(String category) { - return Logger.NULL; - } - }); - } + protected void configure() { + bind(DateService.class); + Names.bindProperties(this.binder(), + new SDNPropertiesBuilder(new Properties()).credentials("appkey/appname/username", "password").build()); + bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() { + public Logger getLogger(String category) { + return Logger.NULL; + } + }); + } - @SuppressWarnings("unused") - @SessionToken - @Provides - String authTokenProvider() { - return System.currentTimeMillis() + ""; - } - }); + @SuppressWarnings("unused") + @SessionToken + @Provides + String authTokenProvider() { + return System.currentTimeMillis() + ""; + } + }); filter = injector.getInstance(AddSessionTokenToRequest.class); } diff --git a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPathTest.java b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPathTest.java index 8238f816f9..1258e02428 100644 --- a/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPathTest.java +++ b/sandbox/nirvanix/sdn/core/src/test/java/org/jclouds/nirvanix/sdn/filters/InsertUserContextIntoPathTest.java @@ -32,6 +32,7 @@ import javax.ws.rs.POST; import org.jclouds.concurrent.MoreExecutors; import org.jclouds.concurrent.config.ExecutorServiceModule; +import org.jclouds.http.HttpRequest; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.logging.Logger; import org.jclouds.logging.Logger.LoggerFactory; @@ -39,7 +40,6 @@ import org.jclouds.nirvanix.sdn.SDNPropertiesBuilder; import org.jclouds.nirvanix.sdn.config.SDNAuthRestClientModule; import org.jclouds.rest.annotations.EndpointParam; import org.jclouds.rest.config.RestModule; -import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -62,28 +62,27 @@ public class InsertUserContextIntoPathTest { private static interface TestService { @POST - public void foo(@EndpointParam URI endpoint); + public void foo(@EndpointParam URI endpoint); } public void testRequestInvalid() { - GeneratedHttpRequest request = factory.createRequest(method, URI.create("https://host/path")); - filter.filter(request); - filter.filter(request); + HttpRequest request = factory.createRequest(method, URI.create("https://host/path")); + request = filter.filter(request); + request = filter.filter(request); assertEquals(request.getEndpoint().getPath(), "/token/appname/username/path"); assertEquals(request.getEndpoint().getHost(), "host"); } public void testRequestNoSession() { - GeneratedHttpRequest request = factory.createRequest(method, URI.create("https://host/path")); - filter.filter(request); + HttpRequest request = factory.createRequest(method, URI.create("https://host/path")); + request = filter.filter(request); assertEquals(request.getEndpoint().getPath(), "/token/appname/username/path"); assertEquals(request.getEndpoint().getHost(), "host"); } public void testRequestAlreadyHasSession() { - GeneratedHttpRequest request = factory.createRequest(method, URI - .create("https://host/token/appname/username/path")); - filter.filter(request); + HttpRequest request = factory.createRequest(method, URI.create("https://host/token/appname/username/path")); + request = filter.filter(request); assertEquals(request.getEndpoint().getPath(), "/token/appname/username/path"); assertEquals(request.getEndpoint().getHost(), "host"); } @@ -91,25 +90,24 @@ public class InsertUserContextIntoPathTest { @BeforeClass protected void createFilter() throws SecurityException, NoSuchMethodException { injector = Guice.createInjector(new RestModule(), new ExecutorServiceModule(MoreExecutors.sameThreadExecutor(), - MoreExecutors.sameThreadExecutor()), new JavaUrlHttpCommandExecutorServiceModule(), - new AbstractModule() { + MoreExecutors.sameThreadExecutor()), new JavaUrlHttpCommandExecutorServiceModule(), new AbstractModule() { - protected void configure() { - install(new SDNAuthRestClientModule()); - bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() { - public Logger getLogger(String category) { - return Logger.NULL; - } - }); - AddSessionTokenToRequest sessionManager = createMock(AddSessionTokenToRequest.class); - expect(sessionManager.getSessionToken()).andReturn("token").anyTimes(); - replay(sessionManager); - bind(AddSessionTokenToRequest.class).toInstance(sessionManager); - Names.bindProperties(this.binder(), new SDNPropertiesBuilder(new Properties()).credentials( - "appkey/appname/username", "password").build()); - } + protected void configure() { + install(new SDNAuthRestClientModule()); + bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() { + public Logger getLogger(String category) { + return Logger.NULL; + } + }); + AddSessionTokenToRequest sessionManager = createMock(AddSessionTokenToRequest.class); + expect(sessionManager.getSessionToken()).andReturn("token").anyTimes(); + replay(sessionManager); + bind(AddSessionTokenToRequest.class).toInstance(sessionManager); + Names.bindProperties(this.binder(), + new SDNPropertiesBuilder(new Properties()).credentials("appkey/appname/username", "password").build()); + } - }); + }); filter = injector.getInstance(InsertUserContextIntoPath.class); factory = injector.getInstance(Key.get(new TypeLiteral>() { })); diff --git a/sandbox/savvis/src/main/java/org/jclouds/savvis/handlers/SymphonyVPDCErrorHandler.java b/sandbox/savvis/src/main/java/org/jclouds/savvis/handlers/SymphonyVPDCErrorHandler.java index f7c391e223..74b72ed5d2 100644 --- a/sandbox/savvis/src/main/java/org/jclouds/savvis/handlers/SymphonyVPDCErrorHandler.java +++ b/sandbox/savvis/src/main/java/org/jclouds/savvis/handlers/SymphonyVPDCErrorHandler.java @@ -31,7 +31,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.base.Throwables; import com.google.common.io.Closeables; @@ -52,7 +52,7 @@ public class SymphonyVPDCErrorHandler implements HttpErrorHandler { Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try { - message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(), + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: @@ -62,7 +62,7 @@ public class SymphonyVPDCErrorHandler implements HttpErrorHandler { exception = new AuthorizationException(message, exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; @@ -84,7 +84,7 @@ public class SymphonyVPDCErrorHandler implements HttpErrorHandler { if (response.getPayload() == null) return null; try { - return Utils.toStringAndClose(response.getPayload().getInput()); + return Strings2.toStringAndClose(response.getPayload().getInput()); } catch (IOException e) { throw new RuntimeException(e); } finally { diff --git a/sandbox/savvis/src/test/java/org/jclouds/savvis/SymphonyVPDCAsyncClientTest.java b/sandbox/savvis/src/test/java/org/jclouds/savvis/SymphonyVPDCAsyncClientTest.java index 3ad7a7d071..f1a61235c8 100644 --- a/sandbox/savvis/src/test/java/org/jclouds/savvis/SymphonyVPDCAsyncClientTest.java +++ b/sandbox/savvis/src/test/java/org/jclouds/savvis/SymphonyVPDCAsyncClientTest.java @@ -48,7 +48,7 @@ import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.savvis.config.SymphonyVPDCRestClientModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.CommonVCloudClient; import org.jclouds.vcloud.VCloudAsyncClient; import org.jclouds.vcloud.VCloudExpressMediaType; @@ -93,7 +93,7 @@ import domain.VCloudVersionsAsyncClient; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "savvis.SymphonyVPDCAsyncClientTest") +@Test(groups = "unit") public class SymphonyVPDCAsyncClientTest extends RestClientTest { public void testInstantiateVAppTemplateInVDCURI() throws SecurityException, NoSuchMethodException, IOException { Method method = SymphonyVPDCAsyncClient.class.getMethod("instantiateVAppTemplateInVDC", URI.class, URI.class, @@ -107,7 +107,7 @@ public class SymphonyVPDCAsyncClientTest extends RestClientTest { public void testGetMyMentions() throws SecurityException, NoSuchMethodException, IOException { Method method = TwitterAsyncClient.class.getMethod("getMyMentions"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals(httpRequest, "GET http://api.twitter.com/statuses/mentions.json HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals(httpRequest, "GET http://api.twitter.com/statuses/mentions.json HTTP/1.1"); // for example, using basic authentication, we should get "only one" diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java index fc52d57424..1e8b3322e8 100644 --- a/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java +++ b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java @@ -18,7 +18,7 @@ import com.vmware.vim25.mo.ServiceInstance; /** * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "vi.ViComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class ViComputeServiceLiveTest extends BaseComputeServiceLiveTest { public ViComputeServiceLiveTest() { diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java index bc37c12165..7c986a289e 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java @@ -34,7 +34,7 @@ import com.google.common.io.Resources; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.AppendFileTest") +@Test(groups = "unit") public class AppendFileTest { Statement statement = appendFile("{root}etc{fs}chef{fs}client.rb", ImmutableList.of("log_level :info", "log_location STDOUT", String.format("chef_server_url \"%s\"", "http://localhost:4000"))); diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AuthorizeRSAPublicKeyTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AuthorizeRSAPublicKeyTest.java index 9cfca03ccf..4b1a2cc62a 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AuthorizeRSAPublicKeyTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AuthorizeRSAPublicKeyTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.AuthorizeRSAPublicKeyTest") +@Test(groups = "unit") public class AuthorizeRSAPublicKeyTest { AuthorizeRSAPublicKey auth = new AuthorizeRSAPublicKey("ssh-dss AAAAB"); diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CallTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CallTest.java index df0595e308..2e9f73af39 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CallTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CallTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.CallTest") +@Test(groups = "unit") public class CallTest { public void testCallNoArgsUNIX() { diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java index beccda495d..d0e0c565bf 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java @@ -36,7 +36,7 @@ import com.google.common.io.Resources; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.CreateRunScriptTest") +@Test(groups = "unit") public class CreateRunScriptTest { Statement statement = createRunScript( "yahooprod", diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/InstallRSAPrivateKeyTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/InstallRSAPrivateKeyTest.java index 0d0d2d8e83..93c5dbb5ef 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/InstallRSAPrivateKeyTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/InstallRSAPrivateKeyTest.java @@ -26,7 +26,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.InstallRSAPrivateKeyTest") +@Test(groups = "unit") public class InstallRSAPrivateKeyTest { InstallRSAPrivateKey key = new InstallRSAPrivateKey("-----BEGIN RSA PRIVATE KEY-----\n-----END RSA PRIVATE KEY-----\n"); diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToTest.java index 5c8fa31e49..d70d006315 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableMultimap; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.PipeHttpResponseToTest") +@Test(groups = "unit") public class PipeHttpResponseToTest { PipeHttpResponseTo bash = new PipeHttpResponseTo(Statements.interpret("bash"), "GET", URI .create("https://adriancolehappy.s3.amazonaws.com/java/install"), ImmutableMultimap.of("Host", diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/ShellTokenTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/ShellTokenTest.java index 8437c129e3..4f05477b9e 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/ShellTokenTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/ShellTokenTest.java @@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableMap; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.ShellTokenTest") +@Test(groups = "unit") public class ShellTokenTest { public void testTokenValueMapUNIX() { diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/StatementListTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/StatementListTest.java index 41801a408e..4b8f953af3 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/StatementListTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/StatementListTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.StatementListTest") +@Test(groups = "unit") public class StatementListTest { Statement statement = newStatementList(call("default"), interpret("echo started{lf}")); diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java index bf19331232..6d643700c9 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java @@ -33,7 +33,7 @@ import com.google.common.collect.ImmutableMap; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.SwitchArgTest") +@Test(groups = "unit") public class SwitchArgTest { public void testSwitchArgUNIX() { diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java index 6171139b76..b204e81cff 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableMultimap; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.UnzipHttpResponseIntoDirectoryToTest") +@Test(groups = "unit") public class UnzipHttpResponseIntoDirectoryToTest { UnzipHttpResponseIntoDirectory jboss = new UnzipHttpResponseIntoDirectory( diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java index 86febc43cc..77cdc9bba3 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java @@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableMap; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "scriptbuilder.UtilsTest") +@Test(groups = "unit") public class UtilsTest { public void testReplaceTokens() throws UnsupportedEncodingException { diff --git a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java index 092fd82406..b64f7008a0 100644 --- a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java +++ b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java @@ -17,7 +17,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "servermanager.ServerManagerComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class ServerManagerComputeServiceLiveTest extends BaseComputeServiceLiveTest { public ServerManagerComputeServiceLiveTest() { provider = "servermanager"; diff --git a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java index 4d4923797e..b860079c7f 100644 --- a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java +++ b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java @@ -39,7 +39,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", testName = "servermanager.ServerManagerExperimentLiveTest") +@Test(groups = "live") public class ServerManagerExperimentLiveTest { protected String provider = "servermanager"; protected String identity; diff --git a/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateBackupToXmlPayload.java b/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateBackupToXmlPayload.java index 90da209379..ed011f2783 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateBackupToXmlPayload.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateBackupToXmlPayload.java @@ -45,7 +45,8 @@ public class BindCreateBackupToXmlPayload implements MapBinder { this.binder = binder; } - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { String sliceId = checkNotNull(postParams.get("slice_id"), "slice_id"); String name = checkNotNull(postParams.get("name"), "name"); StringBuilder builder = new StringBuilder(); @@ -53,12 +54,13 @@ public class BindCreateBackupToXmlPayload implements MapBinder { builder.append("").append(sliceId).append(""); builder.append("").append(name).append(""); builder.append(""); - binder.bindToRequest(request, builder.toString()); + request = binder.bindToRequest(request, builder.toString()); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_XML); + return request; } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { throw new UnsupportedOperationException("should use map params"); } } diff --git a/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateSliceToXmlPayload.java b/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateSliceToXmlPayload.java index df0f2abe24..57c62a0e86 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateSliceToXmlPayload.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/binders/BindCreateSliceToXmlPayload.java @@ -44,8 +44,8 @@ public class BindCreateSliceToXmlPayload implements MapBinder { BindCreateSliceToXmlPayload(BindToStringPayload binder) { this.binder = binder; } - - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { String flavorId = checkNotNull(postParams.get("flavor_id"), "flavor_id"); String imageId = checkNotNull(postParams.get("image_id"), "image_id"); String name = checkNotNull(postParams.get("name"), "name"); @@ -55,12 +55,13 @@ public class BindCreateSliceToXmlPayload implements MapBinder { builder.append("").append(imageId).append(""); builder.append("").append(name).append(""); builder.append(""); - binder.bindToRequest(request, builder.toString()); + request = binder.bindToRequest(request, builder.toString()); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_XML); + return request; } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { throw new UnsupportedOperationException("should use map params"); } } diff --git a/slicehost/src/main/java/org/jclouds/slicehost/filters/SlicehostBasic.java b/slicehost/src/main/java/org/jclouds/slicehost/filters/SlicehostBasic.java index 85397e05da..080c3fb11e 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/filters/SlicehostBasic.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/filters/SlicehostBasic.java @@ -21,17 +21,17 @@ package org.jclouds.slicehost.filters; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; import org.jclouds.Constants; import org.jclouds.crypto.CryptoStreams; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.utils.ModifyRequest; /** * @@ -47,8 +47,8 @@ public class SlicehostBasic implements HttpRequestFilter { } @Override - public void filter(HttpRequest request) throws HttpException { - request.getHeaders().replaceValues("Authorization", - Collections.singleton(String.format("Basic %s", CryptoStreams.base64(apikey.getBytes())))); + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.replaceHeader(request, HttpHeaders.AUTHORIZATION, + String.format("Basic %s", CryptoStreams.base64(apikey.getBytes()))); } } diff --git a/slicehost/src/main/java/org/jclouds/slicehost/handlers/ParseSlicehostErrorFromHttpResponse.java b/slicehost/src/main/java/org/jclouds/slicehost/handlers/ParseSlicehostErrorFromHttpResponse.java index 746d3f96a9..f4c7ba1309 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/handlers/ParseSlicehostErrorFromHttpResponse.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/handlers/ParseSlicehostErrorFromHttpResponse.java @@ -72,8 +72,8 @@ public class ParseSlicehostErrorFromHttpResponse implements HttpErrorHandler { break; case 403: case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String path = command.getRequest().getEndpoint().getPath(); + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = RESOURCE_PATTERN.matcher(path); String message; if (matcher.find()) { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/ProvidersInPropertiesTest.java b/slicehost/src/test/java/org/jclouds/slicehost/ProvidersInPropertiesTest.java index 8049f53901..37a78e5c2f 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/ProvidersInPropertiesTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.slicehost; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -41,7 +41,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "slicehost") : providers; } } diff --git a/slicehost/src/test/java/org/jclouds/slicehost/SlicehostAsyncClientTest.java b/slicehost/src/test/java/org/jclouds/slicehost/SlicehostAsyncClientTest.java index 51cfb064c5..9166115e2f 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/SlicehostAsyncClientTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/SlicehostAsyncClientTest.java @@ -46,11 +46,12 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code SlicehostClient} + * Tests behavior of {@code SlicehostAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.SlicehostClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SlicehostAsyncClientTest") public class SlicehostAsyncClientTest extends RestClientTest { public void testCreateSlice() throws IOException, SecurityException, NoSuchMethodException { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/SlicehostClientLiveTest.java b/slicehost/src/test/java/org/jclouds/slicehost/SlicehostClientLiveTest.java index aa9de7cb58..7ce82ced51 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/SlicehostClientLiveTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/SlicehostClientLiveTest.java @@ -61,7 +61,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "slicehost.SlicehostClientLiveTest") +@Test(groups = "live", sequential = true) public class SlicehostClientLiveTest { protected SlicehostClient client; diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostComputeServiceLiveTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostComputeServiceLiveTest.java index bc635d579d..f2ed50c073 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostComputeServiceLiveTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostComputeServiceLiveTest.java @@ -38,7 +38,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "slicehost.SlicehostComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class SlicehostComputeServiceLiveTest extends BaseComputeServiceLiveTest { public SlicehostComputeServiceLiveTest() { provider = "slicehost"; diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostTemplateBuilderLiveTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostTemplateBuilderLiveTest.java index c001b33f05..5e348c75c2 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostTemplateBuilderLiveTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/SlicehostTemplateBuilderLiveTest.java @@ -36,7 +36,7 @@ import com.google.common.base.Predicate; * * @author Adrian Cole */ -@Test(groups = "live", testName = "slicehost.SlicehostTemplateBuilderLiveTest") +@Test(groups = "live") public class SlicehostTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public SlicehostTemplateBuilderLiveTest() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java index 9bd52ef52b..3e0f82e7f9 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java @@ -25,7 +25,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.SlicehostComputeServiceContextModuleTest") +@Test(groups = "unit") public class SlicehostComputeServiceContextModuleTest { public void testAllStatusCovered() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java index 0b4e9a9079..7e64ae0f2d 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java @@ -40,7 +40,7 @@ import com.google.common.collect.ImmutableList; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "cloudservers.FlavorToHardwareTest") +@Test(groups = "unit") public class FlavorToHardwareTest { Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null); diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java index 53d7b29e12..845f42eb30 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java @@ -53,7 +53,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.SliceToNodeMetadataTest") +@Test(groups = "unit") public class SliceToNodeMetadataTest { Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null); diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java index 60e327be7e..49d9f0f77d 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java @@ -43,7 +43,7 @@ import com.google.inject.Guice; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.SlicehostImageToImageTest") +@Test(groups = "unit") public class SlicehostImageToImageTest { Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null); diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java index 4ad6d83065..b795ca8093 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java @@ -36,7 +36,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.FlavorHandler") +@Test(groups = "unit") public class FlavorHandlerTest { static ParseSax createParser() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorsHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorsHandlerTest.java index 407e0b650c..3a556a1154 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorsHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorsHandlerTest.java @@ -36,7 +36,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.FlavorsHandler") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "FlavorsHandlerTest") public class FlavorsHandlerTest extends BaseHandlerTest { ParseSax> createParser() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java index 62602c33a6..617352f961 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java @@ -36,7 +36,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.ImageHandler") +@Test(groups = "unit") public class ImageHandlerTest { static ParseSax createParser() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java index abfa7c532e..b269fedf56 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java @@ -36,7 +36,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.ImagesHandler") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ImagesHandlerTest") public class ImagesHandlerTest extends BaseHandlerTest { ParseSax> createParser() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java index 4a3c670832..4b8e4ce5af 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java @@ -38,7 +38,8 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.SliceHandler") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SliceHandlerTest") public class SliceHandlerTest extends BaseHandlerTest { static ParseSax createParser() { diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java index ae50e86f1f..0c592c80db 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java @@ -36,7 +36,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "slicehost.SlicesHandler") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SlicesHandlerTest") public class SlicesHandlerTest extends BaseHandlerTest { ParseSax> createParser() { diff --git a/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java b/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java index 7e069b2076..072dc04401 100644 --- a/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java +++ b/tools/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java @@ -44,7 +44,7 @@ import org.jclouds.compute.domain.Template; import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.domain.Location; import org.jclouds.http.HttpUtils; -import org.jclouds.util.Utils; +import org.jclouds.util.CredentialUtils; import com.google.common.base.CaseFormat; import com.google.common.base.Splitter; @@ -212,7 +212,7 @@ public class ComputeTask extends Task { getProject().setProperty(nodeElement.getIdproperty(), createdNode.getProviderId()); if (nodeElement.getHostproperty() != null) getProject().setProperty(nodeElement.getHostproperty(), ipOrEmptyString(createdNode.getPublicAddresses())); - if (nodeElement.getPasswordproperty() != null && !Utils.isPrivateKeyCredential(createdNode.getCredentials())) + if (nodeElement.getPasswordproperty() != null && !CredentialUtils.isPrivateKeyCredential(createdNode.getCredentials())) getProject().setProperty(nodeElement.getPasswordproperty(), createdNode.getCredentials().credential); if (nodeElement.getUsernameproperty() != null) getProject().setProperty(nodeElement.getUsernameproperty(), createdNode.getCredentials().identity); diff --git a/tools/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java b/tools/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java index 8ebdf43cd4..2fda9ca387 100644 --- a/tools/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java +++ b/tools/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java @@ -47,7 +47,7 @@ import com.google.common.io.Resources; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "jclouds.SSHJavaTest") +@Test(groups = "unit") public class SSHJavaTest { public static final Entry LAST_ENV = Iterables.getLast(System.getenv() .entrySet()); diff --git a/tools/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java b/tools/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java index 84880ccf73..434a13b5d1 100755 --- a/tools/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java +++ b/tools/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java @@ -34,7 +34,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; @@ -50,7 +50,7 @@ import com.google.common.collect.Sets; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "functionalTests") +@Test(groups = "live", sequential = true) public class GetPathLiveTest { public static final String PROPERTY_GETPATH_CONTAINER = "jclouds.getpath.container"; @@ -154,7 +154,7 @@ public class GetPathLiveTest { new File(tmpDirectory).mkdirs(); GetPath.main(uriKey, tmpDirectory); for (Entry entry : fiveStrings.entrySet()) { - assertEquals(Utils.toStringAndClose(new FileInputStream(new File(tmpDirectory, entry + assertEquals(Strings2.toStringAndClose(new FileInputStream(new File(tmpDirectory, entry .getKey()))), entry.getValue()); } } diff --git a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorClientLiveTest.java b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorClientLiveTest.java index 0f2240c7f8..ccbcbd4e49 100644 --- a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorClientLiveTest.java +++ b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorClientLiveTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "bluelock.BlueLockVCloudDirectorClientLiveTest") +@Test(groups = "live", sequential = true) public class BlueLockVCloudDirectorClientLiveTest extends VCloudClientLiveTest { public BlueLockVCloudDirectorClientLiveTest() { provider = "bluelock-vcdirector"; diff --git a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorGuestCustomizationLiveTest.java b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorGuestCustomizationLiveTest.java index 91f9c2e153..c51ac27c43 100644 --- a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorGuestCustomizationLiveTest.java +++ b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/BlueLockVCloudDirectorGuestCustomizationLiveTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "vcloud.BlueLockVCloudDirectorGuestCustomizationLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class BlueLockVCloudDirectorGuestCustomizationLiveTest extends VCloudGuestCustomizationLiveTest { public BlueLockVCloudDirectorGuestCustomizationLiveTest() { diff --git a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/ProvidersInPropertiesTest.java b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/ProvidersInPropertiesTest.java index 263e76fb08..bef2389990 100644 --- a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/ProvidersInPropertiesTest.java +++ b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.vcloud.bluelock; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "bluelock-vcdirector") : providers; } diff --git a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/VCloudSessionRefreshLiveTest.java b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/VCloudSessionRefreshLiveTest.java index 0b47fe9f7e..a711e9a9aa 100644 --- a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/VCloudSessionRefreshLiveTest.java +++ b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/VCloudSessionRefreshLiveTest.java @@ -43,7 +43,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "vcloud.VCloudSessionRefreshLiveTest") +@Test(groups = "live", sequential = true) public class VCloudSessionRefreshLiveTest { private final static int timeOut = 40; diff --git a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/compute/BlueLockVCloudDirectorComputeServiceLiveTest.java b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/compute/BlueLockVCloudDirectorComputeServiceLiveTest.java index 6eebfa0a8e..4504a7f330 100644 --- a/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/compute/BlueLockVCloudDirectorComputeServiceLiveTest.java +++ b/vcloud/bluelock/src/test/java/org/jclouds/vcloud/bluelock/compute/BlueLockVCloudDirectorComputeServiceLiveTest.java @@ -35,7 +35,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "bluelock.BlueLockVCloudComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class BlueLockVCloudDirectorComputeServiceLiveTest extends VCloudComputeServiceLiveTest { public BlueLockVCloudDirectorComputeServiceLiveTest() { provider = "bluelock-vcdirector"; diff --git a/vcloud/core/src/main/java/domain/VCloudExpressLoginAsyncClient.java b/vcloud/core/src/main/java/domain/VCloudExpressLoginAsyncClient.java index 8bed8c136e..5e93911639 100755 --- a/vcloud/core/src/main/java/domain/VCloudExpressLoginAsyncClient.java +++ b/vcloud/core/src/main/java/domain/VCloudExpressLoginAsyncClient.java @@ -21,7 +21,6 @@ package domain; import javax.ws.rs.Consumes; import javax.ws.rs.POST; -import javax.ws.rs.Path; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.Endpoint; @@ -49,7 +48,6 @@ public interface VCloudExpressLoginAsyncClient { * the token expires and you have to request a new token with this call. */ @POST - @Path("") @ResponseParser(ParseLoginResponseFromHeaders.class) @Consumes(VCloudExpressMediaType.ORGLIST_XML) ListenableFuture login(); diff --git a/vcloud/core/src/main/java/domain/VCloudLoginAsyncClient.java b/vcloud/core/src/main/java/domain/VCloudLoginAsyncClient.java index e85382c192..0e7401ddb6 100644 --- a/vcloud/core/src/main/java/domain/VCloudLoginAsyncClient.java +++ b/vcloud/core/src/main/java/domain/VCloudLoginAsyncClient.java @@ -21,7 +21,6 @@ package domain; import javax.ws.rs.Consumes; import javax.ws.rs.POST; -import javax.ws.rs.Path; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.Endpoint; @@ -49,7 +48,6 @@ public interface VCloudLoginAsyncClient { * the token expires and you have to request a new token with this call. */ @POST - @Path("") @ResponseParser(ParseLoginResponseFromHeaders.class) @Consumes(VCloudMediaType.ORGLIST_XML) ListenableFuture login(); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/CommonVCloudAsyncClient.java b/vcloud/core/src/main/java/org/jclouds/vcloud/CommonVCloudAsyncClient.java index 089febe123..1cc7537e6e 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/CommonVCloudAsyncClient.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/CommonVCloudAsyncClient.java @@ -78,7 +78,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getOrg */ @GET - @Path("") @XMLResponseParser(OrgHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(ORG_XML) @@ -88,7 +87,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getOrgNamed */ @GET - @Path("") @XMLResponseParser(OrgHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(ORG_XML) @@ -99,7 +97,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getCatalog */ @GET - @Path("") @XMLResponseParser(CatalogHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(CATALOG_XML) @@ -109,7 +106,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#findCatalogInOrgNamed */ @GET - @Path("") @XMLResponseParser(CatalogHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(CATALOG_XML) @@ -121,7 +117,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getCatalogItem */ @GET - @Path("") @Consumes(CATALOGITEM_XML) @XMLResponseParser(CatalogItemHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -131,7 +126,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getCatalogItemInOrg */ @GET - @Path("") @Consumes(CATALOGITEM_XML) @XMLResponseParser(CatalogItemHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -144,7 +138,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#findNetworkInOrgVDCNamed */ @GET - @Path("") @Consumes(NETWORK_XML) @XMLResponseParser(OrgNetworkHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -157,7 +150,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getNetwork */ @GET - @Path("") @Consumes(NETWORK_XML) @XMLResponseParser(OrgNetworkHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -167,7 +159,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getVDC(URI) */ @GET - @Path("") @XMLResponseParser(VDCHandler.class) @Consumes(VDC_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -177,7 +168,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#findVDCInOrgNamed(String, String) */ @GET - @Path("") @XMLResponseParser(VDCHandler.class) @Consumes(VDC_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -189,7 +179,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getTasksList */ @GET - @Path("") @Consumes(TASKSLIST_XML) @XMLResponseParser(TasksListHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -199,7 +188,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#findTasksListInOrgNamed */ @GET - @Path("") @Consumes(TASKSLIST_XML) @XMLResponseParser(TasksListHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -210,7 +198,6 @@ public interface CommonVCloudAsyncClient { * @see CommonVCloudClient#getTask */ @GET - @Path("") @Consumes(TASK_XML) @XMLResponseParser(TaskHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudAsyncClient.java b/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudAsyncClient.java index 9b03cce20f..55e2b2d8c0 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudAsyncClient.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudAsyncClient.java @@ -108,7 +108,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#listOrgs */ @GET - @Path("") @Endpoint(OrgList.class) @XMLResponseParser(OrgListHandler.class) @Consumes(VCloudMediaType.ORGLIST_XML) @@ -118,7 +117,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#getVAppTemplate */ @GET - @Path("") @Consumes(VAPPTEMPLATE_XML) @XMLResponseParser(VAppTemplateHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -138,7 +136,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#findVAppTemplateInOrgCatalogNamed */ @GET - @Path("") @Consumes(VAPPTEMPLATE_XML) @XMLResponseParser(VAppTemplateHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -192,7 +189,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#findVAppInOrgVDCNamed */ @GET - @Path("") @Consumes(VAPP_XML) @XMLResponseParser(VAppHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -205,7 +201,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#getVApp */ @GET - @Path("") @Consumes(VAPP_XML) @XMLResponseParser(VAppHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -215,7 +210,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#getVm */ @GET - @Path("") @Consumes(VM_XML) @XMLResponseParser(VmHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -333,7 +327,6 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient { * @see CommonVCloudClient#deleteVApp */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) @XMLResponseParser(TaskHandler.class) ListenableFuture deleteVApp(@EndpointParam URI vAppId); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudExpressAsyncClient.java b/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudExpressAsyncClient.java index 4806e2224e..7fac6530e5 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudExpressAsyncClient.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudExpressAsyncClient.java @@ -76,7 +76,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#getVAppTemplate */ @GET - @Path("") @Consumes(VAPPTEMPLATE_XML) @XMLResponseParser(VCloudExpressVAppTemplateHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -86,7 +85,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#findVAppTemplateInOrgCatalogNamed */ @GET - @Path("") @Consumes(VAPPTEMPLATE_XML) @XMLResponseParser(VCloudExpressVAppTemplateHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -100,7 +98,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { */ @Override @GET - @Path("") @Consumes(NETWORK_XML) @XMLResponseParser(OrgNetworkFromVCloudExpressNetworkHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -114,7 +111,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { */ @Override @GET - @Path("") @Consumes(NETWORK_XML) @XMLResponseParser(OrgNetworkFromVCloudExpressNetworkHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -151,7 +147,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#findVAppInOrgVDCNamed */ @GET - @Path("") @Consumes(VAPP_XML) @XMLResponseParser(VCloudExpressVAppHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -164,7 +159,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { * @see VCloudClient#getVApp */ @GET - @Path("") @Consumes(VAPP_XML) @XMLResponseParser(VCloudExpressVAppHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -235,7 +229,6 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { * @see CommonVCloudClient#deleteVApp */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteVApp(@EndpointParam URI vAppId); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudResponseException.java b/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudResponseException.java index b0081c2c8d..fb995a27a1 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudResponseException.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/VCloudResponseException.java @@ -37,14 +37,14 @@ public class VCloudResponseException extends HttpResponseException { private org.jclouds.vcloud.domain.VCloudError error; public VCloudResponseException(HttpCommand command, HttpResponse response, VCloudError error) { - super(String.format("request %s failed with code %s, error: %s", command.getRequest().getRequestLine(), response + super(String.format("request %s failed with code %s, error: %s", command.getCurrentRequest().getRequestLine(), response .getStatusCode(), error.toString()), command, response); this.setError(error); } public VCloudResponseException(HttpCommand command, HttpResponse response, VCloudError error, Throwable cause) { - super(String.format("request %1$s failed with error: %2$s", command.getRequest().getRequestLine(), error + super(String.format("request %1$s failed with error: %2$s", command.getCurrentRequest().getRequestLine(), error .toString()), command, response, cause); this.setError(error); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCaptureVAppParamsToXmlPayload.java b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCaptureVAppParamsToXmlPayload.java index 1788994877..adf55a9e9c 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCaptureVAppParamsToXmlPayload.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCaptureVAppParamsToXmlPayload.java @@ -58,17 +58,17 @@ public class BindCaptureVAppParamsToXmlPayload implements MapBinder { @Inject public BindCaptureVAppParamsToXmlPayload(BindToStringPayload stringBinder, - @Named(PROPERTY_VCLOUD_XML_NAMESPACE) String ns, @Named(PROPERTY_VCLOUD_XML_SCHEMA) String schema) { + @Named(PROPERTY_VCLOUD_XML_NAMESPACE) String ns, @Named(PROPERTY_VCLOUD_XML_SCHEMA) String schema) { this.ns = ns; this.schema = schema; this.stringBinder = stringBinder; } - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, - "this binder is only valid for GeneratedHttpRequests!"); - GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + "this binder is only valid for GeneratedHttpRequests!"); + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; checkState(gRequest.getArgs() != null, "args should be initialized at this point"); String templateName = checkNotNull(postParams.remove("templateName"), "templateName"); String vApp = checkNotNull(postParams.remove("vApp"), "vApp"); @@ -78,7 +78,7 @@ public class BindCaptureVAppParamsToXmlPayload implements MapBinder { options = new CaptureVAppOptions(); } try { - stringBinder.bindToRequest(request, generateXml(templateName, vApp, options)); + return stringBinder.bindToRequest(request, generateXml(templateName, vApp, options)); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (FactoryConfigurationError e) { @@ -90,7 +90,7 @@ public class BindCaptureVAppParamsToXmlPayload implements MapBinder { } protected String generateXml(String templateName, String vApp, CaptureVAppOptions options) - throws ParserConfigurationException, FactoryConfigurationError, TransformerException { + throws ParserConfigurationException, FactoryConfigurationError, TransformerException { XMLBuilder rootBuilder = buildRoot(templateName); if (options.getDescription() != null) rootBuilder.e("Description").text(options.getDescription()); @@ -101,8 +101,8 @@ public class BindCaptureVAppParamsToXmlPayload implements MapBinder { } protected XMLBuilder buildRoot(String name) throws ParserConfigurationException, FactoryConfigurationError { - XMLBuilder rootBuilder = XMLBuilder.create("CaptureVAppParams").a("name", name).a("xmlns", ns).a("xmlns:xsi", - "http://www.w3.org/2001/XMLSchema-instance").a("xsi:schemaLocation", ns + " " + schema); + XMLBuilder rootBuilder = XMLBuilder.create("CaptureVAppParams").a("name", name).a("xmlns", ns) + .a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance").a("xsi:schemaLocation", ns + " " + schema); return rootBuilder; } @@ -118,7 +118,8 @@ public class BindCaptureVAppParamsToXmlPayload implements MapBinder { return null; } - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("CaptureVAppParams is needs parameters"); } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayload.java b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayload.java index fb5d8ecf09..df4e924601 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayload.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayload.java @@ -58,18 +58,17 @@ public class BindCloneVAppParamsToXmlPayload implements MapBinder { @Inject public BindCloneVAppParamsToXmlPayload(BindToStringPayload stringBinder, - @Named(PROPERTY_VCLOUD_XML_NAMESPACE) String ns, - @Named(PROPERTY_VCLOUD_XML_SCHEMA) String schema) { + @Named(PROPERTY_VCLOUD_XML_NAMESPACE) String ns, @Named(PROPERTY_VCLOUD_XML_SCHEMA) String schema) { this.ns = ns; this.schema = schema; this.stringBinder = stringBinder; } - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, - "this binder is only valid for GeneratedHttpRequests!"); - GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + "this binder is only valid for GeneratedHttpRequests!"); + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; checkState(gRequest.getArgs() != null, "args should be initialized at this point"); String newName = checkNotNull(postParams.remove("newName"), "newName"); String vApp = checkNotNull(postParams.remove("vApp"), "vApp"); @@ -79,7 +78,7 @@ public class BindCloneVAppParamsToXmlPayload implements MapBinder { options = new CloneVAppOptions(); } try { - stringBinder.bindToRequest(request, generateXml(newName, vApp, options)); + return stringBinder.bindToRequest(request, generateXml(newName, vApp, options)); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (FactoryConfigurationError e) { @@ -91,7 +90,7 @@ public class BindCloneVAppParamsToXmlPayload implements MapBinder { } protected String generateXml(String newName, String vApp, CloneVAppOptions options) - throws ParserConfigurationException, FactoryConfigurationError, TransformerException { + throws ParserConfigurationException, FactoryConfigurationError, TransformerException { XMLBuilder rootBuilder = buildRoot(newName, options.isDeploy(), options.isPowerOn()); if (options.getDescription() != null) rootBuilder.e("Description").text(options.getDescription()); @@ -101,12 +100,11 @@ public class BindCloneVAppParamsToXmlPayload implements MapBinder { return rootBuilder.asString(outputProperties); } - protected XMLBuilder buildRoot(String name, boolean deploy, boolean powerOn) - throws ParserConfigurationException, FactoryConfigurationError { - XMLBuilder rootBuilder = XMLBuilder.create("CloneVAppParams").a("name", name).a("deploy", - deploy+"").a("powerOn", powerOn+"").a("xmlns", ns).a("xmlns:xsi", - "http://www.w3.org/2001/XMLSchema-instance").a("xsi:schemaLocation", - ns + " " + schema); + protected XMLBuilder buildRoot(String name, boolean deploy, boolean powerOn) throws ParserConfigurationException, + FactoryConfigurationError { + XMLBuilder rootBuilder = XMLBuilder.create("CloneVAppParams").a("name", name).a("deploy", deploy + "") + .a("powerOn", powerOn + "").a("xmlns", ns).a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") + .a("xsi:schemaLocation", ns + " " + schema); return rootBuilder; } @@ -122,7 +120,8 @@ public class BindCloneVAppParamsToXmlPayload implements MapBinder { return null; } - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("CloneVAppParams is needs parameters"); } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindGuestCustomizationSectionToXmlPayload.java b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindGuestCustomizationSectionToXmlPayload.java index 60c16ab780..db4df6de55 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindGuestCustomizationSectionToXmlPayload.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindGuestCustomizationSectionToXmlPayload.java @@ -58,8 +58,8 @@ public class BindGuestCustomizationSectionToXmlPayload extends BindToStringPaylo this.ns = ns; this.schema = schema; } - - public void bindToRequest(HttpRequest request, Object payload) { + @Override + public R bindToRequest(R request, Object payload) { checkArgument(checkNotNull(payload, "GuestCustomizationSection") instanceof GuestCustomizationSection, "this binder is only valid for GuestCustomizationSection!"); GuestCustomizationSection guest = GuestCustomizationSection.class.cast(payload); @@ -104,12 +104,12 @@ public class BindGuestCustomizationSectionToXmlPayload extends BindToStringPaylo Properties outputProperties = new Properties(); outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); - super.bindToRequest(request, guestCustomizationSection.asString(outputProperties)); + request = super.bindToRequest(request, guestCustomizationSection.asString(outputProperties)); request.getPayload().getContentMetadata().setContentType(guest.getType()); } catch (Exception e) { Throwables.propagate(e); } - + return request; } } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayload.java b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayload.java index 9b48b84ab0..9eaea0a971 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayload.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayload.java @@ -92,11 +92,11 @@ public class BindInstantiateVAppTemplateParamsToXmlPayload implements MapBinder this.client = client; } - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, "this binder is only valid for GeneratedHttpRequests!"); - GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; checkState(gRequest.getArgs() != null, "args should be initialized at this point"); String name = checkNotNull(postParams.remove("name"), "name"); final URI template = URI.create(checkNotNull(postParams.remove("template"), "template")); @@ -125,7 +125,7 @@ public class BindInstantiateVAppTemplateParamsToXmlPayload implements MapBinder networkConfig = ImmutableSet.of(networknetworkConfigDecorator.apply(null)); try { - stringBinder.bindToRequest(request, generateXml(name, deploy, powerOn, template, networkConfig, + return stringBinder.bindToRequest(request, generateXml(name, deploy, powerOn, template, networkConfig, customizeOnInstantiate)); } catch (ParserConfigurationException e) { throw new RuntimeException(e); @@ -254,8 +254,8 @@ public class BindInstantiateVAppTemplateParamsToXmlPayload implements MapBinder } return null; } - - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("InstantiateVAppTemplateParams is needs parameters"); } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload.java b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload.java index 4aa7f7d360..dd4b4e9372 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload.java @@ -85,11 +85,11 @@ public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload implemen this.defaultFenceMode = fenceMode; } - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, "this binder is only valid for GeneratedHttpRequests!"); - GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; checkState(gRequest.getArgs() != null, "args should be initialized at this point"); String name = checkNotNull(postParams.remove("name"), "name"); String template = checkNotNull(postParams.remove("template"), "template"); @@ -112,7 +112,7 @@ public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload implemen addQuantity(options, virtualHardwareQuantity); } try { - stringBinder.bindToRequest(request, generateXml(name, template, virtualHardwareQuantity, networkName, + return stringBinder.bindToRequest(request, generateXml(name, template, virtualHardwareQuantity, networkName, fenceMode, URI.create(network))); } catch (ParserConfigurationException e) { throw new RuntimeException(e); @@ -201,8 +201,8 @@ public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload implemen virtualHardwareQuantity.put(ResourceType.DISK_DRIVE, options.getDiskSizeKilobytes()); } } - - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("InstantiateVAppTemplateParams is needs parameters"); } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindParamsToXmlPayload.java b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindParamsToXmlPayload.java index 69193227bd..8bad639abd 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindParamsToXmlPayload.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/binders/BindParamsToXmlPayload.java @@ -57,10 +57,10 @@ public class BindParamsToXmlPayload implements MapBinder { this.ns = ns; this.stringBinder = stringBinder; } - - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { try { - stringBinder.bindToRequest(request, generateXml(postParams)); + return stringBinder.bindToRequest(request, generateXml(postParams)); } catch (Exception e) { throw new RuntimeException(e); } @@ -78,7 +78,7 @@ public class BindParamsToXmlPayload implements MapBinder { } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { throw new IllegalArgumentException("incorrect usage"); } } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/options/VCloudTemplateOptions.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/options/VCloudTemplateOptions.java index 76795d1ad3..8214f4587f 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/options/VCloudTemplateOptions.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/options/VCloudTemplateOptions.java @@ -23,7 +23,7 @@ import java.util.Arrays; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.io.Payload; -import org.jclouds.util.Utils; +import org.jclouds.util.Preconditions2; /** * Contains options supported in the {@code ComputeService#runNode} operation on the "vcloud" @@ -52,7 +52,7 @@ public class VCloudTemplateOptions extends TemplateOptions { * Specifies the customizationScript used to run instances with */ public VCloudTemplateOptions customizationScript(String customizationScript) { - Utils.checkNotEmpty(customizationScript, "customizationScript must be non-empty"); + Preconditions2.checkNotEmpty(customizationScript, "customizationScript must be non-empty"); this.customizationScript = customizationScript; return this; } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/filters/SetVCloudTokenCookie.java b/vcloud/core/src/main/java/org/jclouds/vcloud/filters/SetVCloudTokenCookie.java index 5be3ff1857..28b1798fb3 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/filters/SetVCloudTokenCookie.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/filters/SetVCloudTokenCookie.java @@ -19,15 +19,15 @@ package org.jclouds.vcloud.filters; -import java.util.Collections; - import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.utils.ModifyRequest; import org.jclouds.vcloud.VCloudToken; /** @@ -45,9 +45,9 @@ public class SetVCloudTokenCookie implements HttpRequestFilter { this.vcloudTokenProvider = authTokenProvider; } - public void filter(HttpRequest request) throws HttpException { - request.getHeaders().replaceValues("Cookie", - Collections.singletonList("vcloud-token=" + vcloudTokenProvider.get())); + @Override + public HttpRequest filter(HttpRequest request) throws HttpException { + return ModifyRequest.replaceHeader(request, HttpHeaders.COOKIE, "vcloud-token=" + vcloudTokenProvider.get()); } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/functions/VAppTemplatesForCatalogItems.java b/vcloud/core/src/main/java/org/jclouds/vcloud/functions/VAppTemplatesForCatalogItems.java index 54ea703f13..c9b34377cc 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/functions/VAppTemplatesForCatalogItems.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/functions/VAppTemplatesForCatalogItems.java @@ -21,7 +21,7 @@ package org.jclouds.vcloud.functions; import static com.google.common.collect.Iterables.filter; import static org.jclouds.concurrent.FutureIterables.transformParallel; -import static org.jclouds.util.Utils.propagateOrNull; +import static org.jclouds.util.Throwables2.propagateOrNull; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/handlers/ParseVCloudErrorFromHttpResponse.java b/vcloud/core/src/main/java/org/jclouds/vcloud/handlers/ParseVCloudErrorFromHttpResponse.java index 032dcbca33..32b6198906 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/handlers/ParseVCloudErrorFromHttpResponse.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/handlers/ParseVCloudErrorFromHttpResponse.java @@ -37,7 +37,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.VCloudMediaType; import org.jclouds.vcloud.VCloudResponseException; import org.jclouds.vcloud.domain.VCloudError; @@ -63,7 +63,7 @@ public class ParseVCloudErrorFromHttpResponse implements HttpErrorHandler { } public void handleError(HttpCommand command, HttpResponse response) { - HttpRequest request = command.getRequest(); + HttpRequest request = command.getCurrentRequest(); Exception exception = new HttpResponseException(command, response); try { VCloudError error = null; @@ -78,7 +78,7 @@ public class ParseVCloudErrorFromHttpResponse implements HttpErrorHandler { } } else { try { - message = Utils.toStringAndClose(response.getPayload().getInput()); + message = Strings2.toStringAndClose(response.getPayload().getInput()); exception = message != null ? new HttpResponseException(command, response, message) : exception; } catch (IOException e) { } @@ -100,8 +100,8 @@ public class ParseVCloudErrorFromHttpResponse implements HttpErrorHandler { exception = new AuthorizationException(exception.getMessage(), exception); break; case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - String path = command.getRequest().getEndpoint().getPath(); + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + String path = command.getCurrentRequest().getEndpoint().getPath(); Matcher matcher = RESOURCE_PATTERN.matcher(path); if (matcher.find()) { message = String.format("%s %s not found", matcher.group(1), matcher.group(2)); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/CaptureVAppLiveTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/CaptureVAppLiveTest.java index a11c9a85e2..6ea071285d 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/CaptureVAppLiveTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/CaptureVAppLiveTest.java @@ -46,7 +46,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "vcloud.CaptureVAppLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class CaptureVAppLiveTest { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/CommonVCloudClientLiveTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/CommonVCloudClientLiveTest.java index 2892febb30..eeaeb25d8d 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/CommonVCloudClientLiveTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/CommonVCloudClientLiveTest.java @@ -47,7 +47,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "vcloud.VCloudClientLiveTest") +@Test(groups = "live", sequential = true) public abstract class CommonVCloudClientLiveTest { protected S connection; diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/ProvidersInPropertiesTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/ProvidersInPropertiesTest.java index f901baf125..9e81967b86 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/ProvidersInPropertiesTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.vcloud; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "vcloud") : providers; } diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudAsyncClientTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudAsyncClientTest.java index 3700215533..be86cd37a5 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudAsyncClientTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudAsyncClientTest.java @@ -50,7 +50,7 @@ import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.config.VCloudRestClientModule; import org.jclouds.vcloud.domain.AllocationModel; import org.jclouds.vcloud.domain.GuestCustomizationSection; @@ -101,7 +101,8 @@ import domain.VCloudVersionsAsyncClient; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudAsyncClientTest") public class VCloudAsyncClientTest extends RestClientTest { public void testGetThumbnailOfVm() throws SecurityException, NoSuchMethodException, IOException { @@ -132,7 +133,7 @@ public class VCloudAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "PUT http://vcloud.example.com/api/v1.0/vApp/vm-12/guestCustomizationSection HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.task+xml\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream( + assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream( "/guestCustomizationSection.xml")), "application/vnd.vmware.vcloud.guestCustomizationSection+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); @@ -155,7 +156,7 @@ public class VCloudAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vApp+xml\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream( + assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream( "/instantiationparams-network.xml")), "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false); @@ -188,7 +189,7 @@ public class VCloudAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/cloneVApp HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.task+xml\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml")), + assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml")), "application/vnd.vmware.vcloud.cloneVAppParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); @@ -209,7 +210,7 @@ public class VCloudAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/cloneVApp HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.task+xml\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml")), + assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml")), "application/vnd.vmware.vcloud.cloneVAppParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); @@ -229,7 +230,7 @@ public class VCloudAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/captureVApp HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vAppTemplate+xml\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream("/captureVApp-default.xml")), + assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream("/captureVApp-default.xml")), "application/vnd.vmware.vcloud.captureVAppParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); @@ -250,7 +251,7 @@ public class VCloudAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST https://vcenterprise.bluelock.com/api/v1.0/vdc/1/action/captureVApp HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vAppTemplate+xml\n"); - assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream("/captureVApp.xml")), + assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream("/captureVApp.xml")), "application/vnd.vmware.vcloud.captureVAppParams+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudClientLiveTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudClientLiveTest.java index df802533d5..0c29bcad55 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudClientLiveTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudClientLiveTest.java @@ -37,7 +37,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "vcloud.VCloudClientLiveTest") +@Test(groups = "live", sequential = true) public class VCloudClientLiveTest extends CommonVCloudClientLiveTest { @Test diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java index 1fe2e00ca6..6c0bafc28e 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java @@ -47,7 +47,7 @@ import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.config.VCloudExpressRestClientModule; import org.jclouds.vcloud.domain.Org; import org.jclouds.vcloud.domain.ReferenceType; @@ -90,7 +90,8 @@ import domain.VCloudVersionsAsyncClient; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudExpressAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudExpressAsyncClientTest") public class VCloudExpressAsyncClientTest extends RestClientTest { public void testInstantiateVAppTemplateInVDCURI() throws SecurityException, NoSuchMethodException, IOException { @@ -103,7 +104,7 @@ public class VCloudExpressAsyncClientTest extends RestClientTest { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudGuestCustomizationLiveTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudGuestCustomizationLiveTest.java index 2e76103f72..5c424e55c5 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudGuestCustomizationLiveTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudGuestCustomizationLiveTest.java @@ -55,7 +55,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "vcloud.VCloudGuestCustomizationLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class VCloudGuestCustomizationLiveTest { public static final String PARSE_VMTOOLSD = "vmtoolsd --cmd=\"info-get guestinfo.ovfenv\" |grep vCloud_CustomizationInfo|sed 's/.*value=\"\\(.*\\)\".*/\\1/g'|base64 -d"; @@ -125,7 +125,7 @@ public class VCloudGuestCustomizationLiveTest { assert socketTester.apply(socket); - SshClient ssh = sshFactory.create(socket, node.getCredentials().identity, node.getCredentials().credential); + SshClient ssh = sshFactory.create(socket, node.getCredentials()); try { ssh.connect(); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudLoginAsyncClientTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudLoginAsyncClientTest.java index be429290f6..6e0f30df93 100755 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudLoginAsyncClientTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudLoginAsyncClientTest.java @@ -49,11 +49,12 @@ import com.google.inject.TypeLiteral; import domain.VCloudExpressLoginAsyncClient; /** - * Tests behavior of {@code VCloudLogin} + * Tests behavior of {@code VCloudLoginAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudLoginTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudLoginAsyncClientTest") public class VCloudLoginAsyncClientTest extends RestClientTest { public void testLogin() throws SecurityException, NoSuchMethodException, IOException { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudVersionsAsyncClientTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudVersionsAsyncClientTest.java index c81a834d3d..4e5cf774ac 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudVersionsAsyncClientTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/VCloudVersionsAsyncClientTest.java @@ -42,11 +42,12 @@ import com.google.inject.TypeLiteral; import domain.VCloudVersionsAsyncClient; /** - * Tests behavior of {@code VCloudVersions} + * Tests behavior of {@code VCloudVersionsAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudVersionsTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudVersionsAsyncClientTest") public class VCloudVersionsAsyncClientTest extends RestClientTest { public void testVersions() throws SecurityException, NoSuchMethodException, IOException { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayloadTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayloadTest.java index d15325e409..df666cd9ea 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayloadTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindCloneVAppParamsToXmlPayloadTest.java @@ -31,11 +31,12 @@ import java.util.Map; import java.util.Properties; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.VCloudPropertiesBuilder; import org.jclouds.vcloud.options.CloneVAppOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.inject.AbstractModule; import com.google.inject.Guice; @@ -47,7 +48,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.BindCloneVAppParamsToXmlPayloadTest") +@Test(groups = "unit") public class BindCloneVAppParamsToXmlPayloadTest { Injector injector = Guice.createInjector(new AbstractModule() { @@ -59,13 +60,13 @@ public class BindCloneVAppParamsToXmlPayloadTest { }); public void testWithDescriptionDeployOn() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp.xml")); CloneVAppOptions options = new CloneVAppOptions().deploy().powerOn().withDescription( "The description of the new vApp"); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { options }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of( options)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -79,11 +80,11 @@ public class BindCloneVAppParamsToXmlPayloadTest { } public void testDefault() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/cloneVApp-default.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] {}).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); request.setPayload(expected); replay(request); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindDeployVAppParamsToXmlPayloadTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindDeployVAppParamsToXmlPayloadTest.java index a1a568ef87..2176fa659d 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindDeployVAppParamsToXmlPayloadTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindDeployVAppParamsToXmlPayloadTest.java @@ -45,7 +45,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.BindDeployVAppParamsToXmlPayloadTest") +@Test(groups = "unit") public class BindDeployVAppParamsToXmlPayloadTest { Injector injector = Guice.createInjector(new AbstractModule() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayloadTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayloadTest.java index e2096909eb..9364f9253f 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayloadTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVAppTemplateParamsToXmlPayloadTest.java @@ -35,7 +35,7 @@ import java.util.Properties; import javax.inject.Singleton; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.VCloudPropertiesBuilder; import org.jclouds.vcloud.domain.VAppTemplate; @@ -46,6 +46,7 @@ import org.jclouds.vcloud.endpoints.Network; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.inject.AbstractModule; @@ -59,7 +60,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.BindInstantiateVAppTemplateParamsToXmlPayloadTest") +@Test(groups = "unit") public class BindInstantiateVAppTemplateParamsToXmlPayloadTest { Injector createInjector(URI vAppTemplate, VAppTemplate value) { final VCloudClient client = createMock(VCloudClient.class); @@ -91,10 +92,10 @@ public class BindInstantiateVAppTemplateParamsToXmlPayloadTest { VAppTemplate template = createMock(VAppTemplate.class); VCloudNetworkSection net = createMock(VCloudNetworkSection.class); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/instantiationparams.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/instantiationparams.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] {}).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); request.setPayload(expected); expect(template.getNetworkSection()).andReturn(net).atLeastOnce(); @@ -127,10 +128,10 @@ public class BindInstantiateVAppTemplateParamsToXmlPayloadTest { URI templateUri = URI.create("https://vcenterprise.bluelock.com/api/v1.0/vAppTemplate/3"); VAppTemplate template = null; - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/instantiationparams.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/instantiationparams.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] {}).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); request.setPayload(expected); replay(request); @@ -154,10 +155,10 @@ public class BindInstantiateVAppTemplateParamsToXmlPayloadTest { InstantiateVAppTemplateOptions options = new InstantiateVAppTemplateOptions(); options.processorCount(1).memory(512).disk(1024); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/instantiationparams.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/instantiationparams.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { options }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of( options)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -180,11 +181,11 @@ public class BindInstantiateVAppTemplateParamsToXmlPayloadTest { InstantiateVAppTemplateOptions options = addNetworkConfig(new NetworkConfig("aloha", URI .create("https://vcenterprise.bluelock.com/api/v1.0/network/1991"), FenceMode.NAT_ROUTED)); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/instantiationparams-network.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/instantiationparams-network.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { options }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of( options)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -206,12 +207,12 @@ public class BindInstantiateVAppTemplateParamsToXmlPayloadTest { VCloudNetworkSection net = createMock(VCloudNetworkSection.class); InstantiateVAppTemplateOptions options = customizeOnInstantiate(true); - String expected = Utils + String expected = Strings2 .toStringAndClose(getClass().getResourceAsStream("/instantiationparams-customization.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { options }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of( options)).atLeastOnce(); request.setPayload(expected); expect(template.getNetworkSection()).andReturn(net).atLeastOnce(); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest.java index 2c602a372d..e6696000a6 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest.java @@ -33,13 +33,14 @@ import java.util.Properties; import javax.inject.Singleton; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.VCloudExpressPropertiesBuilder; import org.jclouds.vcloud.domain.network.FenceMode; import org.jclouds.vcloud.endpoints.Network; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.inject.AbstractModule; import com.google.inject.Guice; @@ -52,7 +53,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.BindInstantiateVAppTemplateParamsToXmlPayloadTest") +@Test(groups = "unit") public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest { Injector injector = Guice.createInjector(new AbstractModule() { @@ -72,10 +73,10 @@ public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest { }); public void testDefault() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/express/newvapp-hosting.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/express/newvapp-hosting.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] {}).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); request.setPayload(expected); replay(request); @@ -94,11 +95,11 @@ public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest { InstantiateVAppTemplateOptions options = new InstantiateVAppTemplateOptions(); options.processorCount(1).memory(512).disk(1024); - String expected = Utils + String expected = Strings2 .toStringAndClose(getClass().getResourceAsStream("/express/newvapp-hostingcpumemdisk.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { options }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of( options)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -116,12 +117,12 @@ public class BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayloadTest { } public void testWithNetworkNameDhcpFenceMode() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream( + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream( "/express/newvapp-hostingnetworknamedhcpfencemode.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] {}).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); request.setPayload(expected); replay(request); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindUndeployVAppParamsToXmlPayloadTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindUndeployVAppParamsToXmlPayloadTest.java index ec812f406d..35be21f120 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindUndeployVAppParamsToXmlPayloadTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/BindUndeployVAppParamsToXmlPayloadTest.java @@ -45,7 +45,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.BindUndeployVAppParamsToXmlPayloadTest") +@Test(groups = "unit") public class BindUndeployVAppParamsToXmlPayloadTest { Injector injector = Guice.createInjector(new AbstractModule() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/VCloudExpressBindCloneVAppParamsToXmlPayloadTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/VCloudExpressBindCloneVAppParamsToXmlPayloadTest.java index a9176fba3a..0e5c88ce0a 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/binders/VCloudExpressBindCloneVAppParamsToXmlPayloadTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/binders/VCloudExpressBindCloneVAppParamsToXmlPayloadTest.java @@ -31,11 +31,12 @@ import java.util.Map; import java.util.Properties; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.VCloudExpressPropertiesBuilder; import org.jclouds.vcloud.options.CloneVAppOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.inject.AbstractModule; import com.google.inject.Guice; @@ -47,7 +48,7 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.BindCloneVAppParamsToXmlPayloadTest") +@Test(groups = "unit") public class VCloudExpressBindCloneVAppParamsToXmlPayloadTest { Injector injector = Guice.createInjector(new AbstractModule() { @@ -59,13 +60,13 @@ public class VCloudExpressBindCloneVAppParamsToXmlPayloadTest { }); public void testWithDescriptionDeployOn() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/express/cloneVApp.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/express/cloneVApp.xml")); CloneVAppOptions options = new CloneVAppOptions().deploy().powerOn().withDescription( "The description of the new vApp"); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { options }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of( options)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -79,11 +80,11 @@ public class VCloudExpressBindCloneVAppParamsToXmlPayloadTest { } public void testDefault() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/express/cloneVApp-default.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/express/cloneVApp-default.xml")); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] {}).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList.of()).atLeastOnce(); request.setPayload(expected); replay(request); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/compute/VCloudComputeServiceLiveTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/compute/VCloudComputeServiceLiveTest.java index 6ed6f83234..33867bbdca 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/compute/VCloudComputeServiceLiveTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/compute/VCloudComputeServiceLiveTest.java @@ -38,7 +38,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "vcloud.VCloudComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class VCloudComputeServiceLiveTest extends BaseComputeServiceLiveTest { public VCloudComputeServiceLiveTest() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModuleTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModuleTest.java index 42018c0055..2a5e964cc2 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModuleTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModuleTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudComputeServiceContextModuleTest") +@Test(groups = "unit") public class VCloudComputeServiceContextModuleTest { @SuppressWarnings("static-access") diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModuleTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModuleTest.java index 74946b6bdb..5e1505b47b 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModuleTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModuleTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudExpressComputeServiceContextModuleTest") +@Test(groups = "unit") public class VCloudExpressComputeServiceContextModuleTest { @SuppressWarnings("static-access") diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressOrgNetworkAdapterTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressOrgNetworkAdapterTest.java index a6e4d6ffc9..ab0c9b47ab 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressOrgNetworkAdapterTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressOrgNetworkAdapterTest.java @@ -45,7 +45,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudExpressOrgNetworkAdapterTest") +@Test(groups = "unit") public class VCloudExpressOrgNetworkAdapterTest { public void testTerremark() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/filters/SetVCloudTokenCookieTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/filters/SetVCloudTokenCookieTest.java index ad565aed49..d7c652015b 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/filters/SetVCloudTokenCookieTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/filters/SetVCloudTokenCookieTest.java @@ -51,7 +51,7 @@ public class SetVCloudTokenCookieTest { @Test public void testApply() { HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); - filter.filter(request); + request = filter.filter(request); assertEquals(request.getHeaders().size(), 1); assertEquals(request.getFirstHeaderOrNull(HttpHeaders.COOKIE), "vcloud-token=token"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/functions/ParseLoginResponseFromHeadersTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/functions/ParseLoginResponseFromHeadersTest.java index c1bb2fb9f5..a931812cd1 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/functions/ParseLoginResponseFromHeadersTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/functions/ParseLoginResponseFromHeadersTest.java @@ -35,10 +35,15 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; /** + * Tests behavior of {@code ParseLoginResponseFromHeaders} + * * @author Adrian Cole */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ParseLoginResponseFromHeadersTest") public class ParseLoginResponseFromHeadersTest extends BaseHandlerTest { private ParseLoginResponseFromHeaders parser; @@ -51,11 +56,10 @@ public class ParseLoginResponseFromHeadersTest extends BaseHandlerTest { @Test public void testApply() { HttpResponse response = new HttpResponse(200, "OK", Payloads.newInputStreamPayload(getClass() - .getResourceAsStream("/orglist.xml"))); + .getResourceAsStream("/orglist.xml")), ImmutableMultimap.of(HttpHeaders.SET_COOKIE, "vcloud-token=9er4d061-4bff-48fa-84b1-5da7166764d2; path=/")); response.getPayload().getContentMetadata().setContentType("Content-Type: application/xml; charset=utf-8"); response.getPayload().getContentMetadata().setContentLength(307l); - response.getHeaders().put(HttpHeaders.SET_COOKIE, "vcloud-token=9er4d061-4bff-48fa-84b1-5da7166764d2; path=/"); VCloudSession reply = parser.apply(response); assertEquals(reply.getVCloudToken(), "9er4d061-4bff-48fa-84b1-5da7166764d2"); assertEquals(reply.getOrgs(), ImmutableMap.of("adrian@jclouds.org", new ReferenceTypeImpl("adrian@jclouds.org", @@ -66,12 +70,10 @@ public class ParseLoginResponseFromHeadersTest extends BaseHandlerTest { @Test public void testApplyBlueLock() { HttpResponse response = new HttpResponse(200, "OK", Payloads.newInputStreamPayload(getClass() - .getResourceAsStream("/orglist.xml"))); + .getResourceAsStream("/orglist.xml")), ImmutableMultimap.of(HttpHeaders.SET_COOKIE,"vcloud-token=c9f232506df9b65d7b7d97b7499eddd7; Domain=.bluelock.com; Path=/") ); response.getPayload().getContentMetadata().setContentType("Content-Type: application/xml; charset=utf-8"); response.getPayload().getContentMetadata().setContentLength(307l); - response.getHeaders().put(HttpHeaders.SET_COOKIE, - "vcloud-token=c9f232506df9b65d7b7d97b7499eddd7; Domain=.bluelock.com; Path=/"); VCloudSession reply = parser.apply(response); assertEquals(reply.getVCloudToken(), "c9f232506df9b65d7b7d97b7499eddd7"); assertEquals(reply.getOrgs(), ImmutableMap.of("adrian@jclouds.org", new ReferenceTypeImpl("adrian@jclouds.org", diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/options/InstantiateVAppTemplateOptionsTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/options/InstantiateVAppTemplateOptionsTest.java index d824c68615..493b07eba2 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/options/InstantiateVAppTemplateOptionsTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/options/InstantiateVAppTemplateOptionsTest.java @@ -42,7 +42,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.InstantiateVAppTemplateOptionsTest") +@Test(groups = "unit") public class InstantiateVAppTemplateOptionsTest { Injector injector = Guice.createInjector(new SaxParserModule()); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogHandlerTest.java index 917239c0cb..9d4e5c932f 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogHandlerTest.java @@ -45,7 +45,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.CatalogHandlerTest") +@Test(groups = "unit") public class CatalogHandlerTest { private Injector injector; diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogItemHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogItemHandlerTest.java index 19601526d5..45c002e251 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogItemHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/CatalogItemHandlerTest.java @@ -41,7 +41,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.CatalogItemHandlerTest") +@Test(groups = "unit") public class CatalogItemHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/GuestCustomizationSectionHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/GuestCustomizationSectionHandlerTest.java index 1afb7c7de3..17a4c7b0fb 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/GuestCustomizationSectionHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/GuestCustomizationSectionHandlerTest.java @@ -36,7 +36,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.GuestCustomizationSectionHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "GuestCustomizationSectionHandlerTest") public class GuestCustomizationSectionHandlerTest extends BaseHandlerTest { public void testDefault() throws UnknownHostException { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionHandlerTest.java index f2d8b1daa1..f652019d9b 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionHandlerTest.java @@ -30,11 +30,12 @@ import org.jclouds.vcloud.domain.network.IpAddressAllocationMode; import org.testng.annotations.Test; /** - * Tests behavior of {@code NetworkConnectionSectionHandler} + * Tests behavior of {@code NetworkConnectionHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.NetworkConnectionSectionHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "NetworkConnectionHandlerTest") public class NetworkConnectionHandlerTest extends BaseHandlerTest { public void testDefault() throws UnknownHostException { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionSectionHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionSectionHandlerTest.java index 638114b5e3..f2e035fff9 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionSectionHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/NetworkConnectionSectionHandlerTest.java @@ -41,7 +41,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.NetworkConnectionSectionHandlerTest") +@Test(groups = "unit") public class NetworkConnectionSectionHandlerTest { public void testVCloud1_0() { InputStream is = getClass().getResourceAsStream("/networkconnectionsection.xml"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgHandlerTest.java index 5e41fbd5d2..d94506263a 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgHandlerTest.java @@ -44,7 +44,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.OrgHandlerTest") +@Test(groups = "unit") public class OrgHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgListHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgListHandlerTest.java index 71e30cd167..12eeeee9f3 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgListHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgListHandlerTest.java @@ -38,7 +38,8 @@ import com.google.common.collect.ImmutableMap; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.OrgListHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "OrgListHandlerTest") public class OrgListHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgNetworkHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgNetworkHandlerTest.java index 9bbcd1b22e..ac760ae682 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgNetworkHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/OrgNetworkHandlerTest.java @@ -46,7 +46,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.OrgNetworkHandlerTest") +@Test(groups = "unit") public class OrgNetworkHandlerTest { public void testIsolated() { InputStream is = getClass().getResourceAsStream("/orgnetwork-isolated.xml"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/SupportedVersionsHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/SupportedVersionsHandlerTest.java index 608477433f..dbe54aa6c5 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/SupportedVersionsHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/SupportedVersionsHandlerTest.java @@ -39,7 +39,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.SupportedVersionsHandlerTest") +@Test(groups = "unit") public class SupportedVersionsHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TaskHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TaskHandlerTest.java index 78fce0b160..76aa8e518e 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TaskHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TaskHandlerTest.java @@ -41,7 +41,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TaskHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TaskHandlerTest") public class TaskHandlerTest extends BaseHandlerTest { private DateService dateService; diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TasksListHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TasksListHandlerTest.java index a847a31afa..37e375bc48 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TasksListHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/TasksListHandlerTest.java @@ -42,7 +42,8 @@ import com.google.common.collect.ImmutableSortedSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TasksListHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TasksListHandlerTest") public class TasksListHandlerTest extends BaseHandlerTest { private DateService dateService; diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppHandlerTest.java index dff208db93..f2d7f47f23 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppHandlerTest.java @@ -44,7 +44,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VAppHandlerTest") +@Test(groups = "unit") public class VAppHandlerTest { public void testRhelOffStatic() { InputStream is = getClass().getResourceAsStream("/vapp-rhel-off-static.xml"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppTemplateHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppTemplateHandlerTest.java index 50115cd438..449b87d7ec 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppTemplateHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VAppTemplateHandlerTest.java @@ -51,7 +51,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VAppTemplateHandlerTest") +@Test(groups = "unit") public class VAppTemplateHandlerTest { public void testUbuntuTemplate() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressNetworkHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressNetworkHandlerTest.java index a0f89fec7f..9772529650 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressNetworkHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressNetworkHandlerTest.java @@ -43,7 +43,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudExpressNetworkHandlerTest") +@Test(groups = "unit") public class VCloudExpressNetworkHandlerTest { private Injector injector; diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressVAppTemplateHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressVAppTemplateHandlerTest.java index 32bef9e105..5411d2ca62 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressVAppTemplateHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VCloudExpressVAppTemplateHandlerTest.java @@ -40,7 +40,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VAppTemplateHandlerTest") +@Test(groups = "unit") public class VCloudExpressVAppTemplateHandlerTest { private Injector injector; diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VDCHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VDCHandlerTest.java index 97fdad721f..75e9541389 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VDCHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VDCHandlerTest.java @@ -47,7 +47,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VDCHandlerTest") +@Test(groups = "unit") public class VDCHandlerTest { public void testVCloud1_0() { InputStream is = getClass().getResourceAsStream("/vdc.xml"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VmHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VmHandlerTest.java index bedb735c2f..8c6033d2f8 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VmHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/VmHandlerTest.java @@ -44,7 +44,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VmHandlerTest") +@Test(groups = "unit") public class VmHandlerTest { public void testVCloud1_0() { InputStream is = getClass().getResourceAsStream("/vm-rhel-off-static.xml"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/OvfEnvelopeHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/OvfEnvelopeHandlerTest.java index becfc46a7e..789014a721 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/OvfEnvelopeHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/OvfEnvelopeHandlerTest.java @@ -35,7 +35,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.OvfEnvelopeHandlerTest") +@Test(groups = "unit") public class OvfEnvelopeHandlerTest { public void testVCloud1_0() { InputStream is = getClass().getResourceAsStream("/ovf.xml"); diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/ResourceAllocationHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/ResourceAllocationHandlerTest.java index 5c01708645..41a563fce7 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/ResourceAllocationHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/ResourceAllocationHandlerTest.java @@ -34,7 +34,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.ResourceAllocationHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ResourceAllocationHandlerTest") public class ResourceAllocationHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/SystemHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/SystemHandlerTest.java index 569fb4538b..faae8ccf0a 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/SystemHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/SystemHandlerTest.java @@ -34,7 +34,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.SystemHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SystemHandlerTest") public class SystemHandlerTest extends BaseHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudExpressVAppHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudExpressVAppHandlerTest.java index c18c7d1757..f842c22196 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudExpressVAppHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudExpressVAppHandlerTest.java @@ -54,7 +54,8 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudExpressVAppHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudExpressVAppHandlerTest") public class VCloudExpressVAppHandlerTest extends BaseHandlerTest { @BeforeTest @Override diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudOperatingSystemSectionHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudOperatingSystemSectionHandlerTest.java index 3b7dbed811..648c5d5fab 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudOperatingSystemSectionHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudOperatingSystemSectionHandlerTest.java @@ -32,11 +32,12 @@ import org.jclouds.vcloud.xml.ovf.VCloudOperatingSystemHandler; import org.testng.annotations.Test; /** - * Tests behavior of {@code VCloudOperatingSystemHandler} + * Tests behavior of {@code VCloudOperatingSystemSectionHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudOperatingSystemHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudOperatingSystemSectionHandlerTest") public class VCloudOperatingSystemSectionHandlerTest extends BaseHandlerTest { public void testDefault() throws UnknownHostException { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudVirtualHardwareSectionHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudVirtualHardwareSectionHandlerTest.java index 4d371dc361..89d6fdd52d 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudVirtualHardwareSectionHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VCloudVirtualHardwareSectionHandlerTest.java @@ -41,11 +41,12 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; /** - * Tests behavior of {@code VCloudVirtualHardwareHandler} + * Tests behavior of {@code VCloudVirtualHardwareSectionHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VCloudVirtualHardwareHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VCloudVirtualHardwareSectionHandlerTest") public class VCloudVirtualHardwareSectionHandlerTest extends BaseHandlerTest { public void testDefault() throws UnknownHostException { diff --git a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VirtualSystemHandlerTest.java b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VirtualSystemHandlerTest.java index 23df396d8b..91218d63db 100644 --- a/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VirtualSystemHandlerTest.java +++ b/vcloud/core/src/test/java/org/jclouds/vcloud/xml/ovf/VirtualSystemHandlerTest.java @@ -46,7 +46,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VirtualSystemHandlerTest") +@Test(groups = "unit") public class VirtualSystemHandlerTest { public void testVCloud1_0() { diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClient.java index b7f70e3b8e..d0fb756a07 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClient.java @@ -46,7 +46,6 @@ import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.filters.SetVCloudTokenCookie; import org.jclouds.vcloud.functions.OrgNameVDCNameResourceEntityNameToEndpoint; import org.jclouds.vcloud.terremark.binders.BindCreateKeyToXmlPayload; @@ -85,7 +84,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkVCloudExpressClient#getAllInternetServices */ @GET - @Path("") @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServicesHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -97,7 +95,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkVCloudExpressClient#activatePublicIpInVDC */ @POST - @Path("") @Consumes(PUBLICIP_XML) @XMLResponseParser(PublicIpAddressesHandler.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class) @@ -133,7 +130,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkVCloudExpressClient#getInternetService */ @GET - @Path("") @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServiceHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -144,7 +140,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkVCloudExpressClient#findKeyPairInOrgNamed */ @GET - @Path("") @XMLResponseParser(KeyPairByNameHandler.class) @Consumes(KEYSLIST_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -155,7 +150,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkVCloudExpressClient#listKeyPairsInOrgNamed */ @GET - @Path("") @Consumes(KEYSLIST_XML) @XMLResponseParser(KeyPairsHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -166,7 +160,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkECloudClient#listKeyPairs */ @GET - @Path("") @Consumes(KEYSLIST_XML) @XMLResponseParser(KeyPairsHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -176,7 +169,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkECloudClient#generateKeyPairInOrg */ @POST - @Path("") @Produces(KEYSLIST_XML) @Consumes(KEYSLIST_XML) @XMLResponseParser(KeyPairHandler.class) @@ -189,7 +181,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkECloudClient#getKeyPair */ @GET - @Path("") @XMLResponseParser(KeyPairHandler.class) @Consumes(APPLICATION_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -214,7 +205,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkECloudClient#deleteKeyPair */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteKeyPair(@EndpointParam URI keyId); @@ -223,7 +213,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { */ @Override @GET - @Path("") @Consumes(NETWORK_XML) @XMLResponseParser(TerremarkOrgNetworkFromTerremarkVCloudExpressNetworkHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -237,7 +226,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { */ @Override @GET - @Path("") @Consumes(NETWORK_XML) @XMLResponseParser(TerremarkOrgNetworkFromTerremarkVCloudExpressNetworkHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -247,7 +235,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient { * @see TerremarkECloudClient#getTerremarkNetwork */ @GET - @Path("") @XMLResponseParser(TerremarkNetworkHandler.class) @Consumes(APPLICATION_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java index d3a72b0004..899ba69813 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java @@ -112,7 +112,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { */ @Override @GET - @Path("") @Consumes(CATALOGITEM_XML) @XMLResponseParser(TerremarkCatalogItemHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -126,7 +125,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { */ @Override @GET - @Path("") @Consumes(CATALOGITEM_XML) @XMLResponseParser(TerremarkCatalogItemHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -134,7 +132,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { @Override @GET - @Path("") @XMLResponseParser(TerremarkOrgHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(ORG_XML) @@ -145,7 +142,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { */ @Override @GET - @Path("") @XMLResponseParser(TerremarkOrgHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(ORG_XML) @@ -156,7 +152,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * Terremark does not have multiple catalogs, so we ignore this parameter. */ @GET - @Path("") @Override @XMLResponseParser(CatalogHandler.class) @Consumes(CATALOG_XML) @@ -168,7 +163,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { */ @Override @GET - @Path("") @XMLResponseParser(TerremarkVDCHandler.class) @Consumes(VDC_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -178,7 +172,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see VCloudExpressClient#findVDCInOrgNamed */ @GET - @Path("") @Override @XMLResponseParser(TerremarkVDCHandler.class) @Consumes(VDC_XML) @@ -206,7 +199,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#getAllInternetServicesInVDC */ @GET - @Path("") @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServicesHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -230,7 +222,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#deletePublicIp */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnDeleteDefaultIp.class) ListenableFuture deletePublicIp(@EndpointParam URI ipId); @@ -248,7 +239,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#getPublicIp */ @GET - @Path("") @Consumes(PUBLICIP_XML) @XMLResponseParser(InternetServicesHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -258,7 +248,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#getPublicIpsAssociatedWithVDC */ @GET - @Path("") @Consumes(PUBLICIPSLIST_XML) @XMLResponseParser(PublicIpAddressesHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -269,7 +258,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#deleteInternetService */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteInternetService(@EndpointParam URI internetServiceId); @@ -277,7 +265,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#getInternetService */ @GET - @Path("") @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServiceHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -310,7 +297,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#getNode */ @GET - @Path("") @XMLResponseParser(NodeHandler.class) @Consumes(NODESERVICE_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -320,7 +306,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#configureNode */ @PUT - @Path("") @Produces(NODESERVICE_XML) @Consumes(NODESERVICE_XML) @XMLResponseParser(NodeHandler.class) @@ -332,7 +317,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#deleteNode */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteNode(@EndpointParam URI nodeId); @@ -340,7 +324,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudExpressClient#configureVApp */ @PUT - @Path("") @Produces(VAPP_XML) @Consumes(VAPP_XML) @MapBinder(BindVAppConfigurationToXmlPayload.class) @@ -353,7 +336,6 @@ public interface TerremarkVCloudAsyncClient extends VCloudExpressAsyncClient { * @see TerremarkVCloudClient#getCustomizationOptions */ @GET - @Path("") @XMLResponseParser(CustomizationParametersHandler.class) @Consumes(CATALOGITEMCUSTOMIZATIONPARAMETERS_XML) ListenableFuture getCustomizationOptions(@EndpointParam URI customization); diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClient.java index 27e81bee68..de527cd7bf 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClient.java @@ -31,7 +31,6 @@ import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; -import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.jclouds.rest.annotations.EndpointParam; @@ -71,7 +70,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#addInternetServiceToVDC */ @POST - @Path("") @Produces(INTERNETSERVICE_XML) @Consumes(INTERNETSERVICE_XML) @XMLResponseParser(InternetServiceHandler.class) @@ -85,7 +83,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#findKeyPairInOrgNamed */ @GET - @Path("") @XMLResponseParser(KeyPairByNameHandler.class) @Consumes(KEYSLIST_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -96,7 +93,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#listKeyPairsInOrgNamed */ @GET - @Path("") @Consumes(KEYSLIST_XML) @XMLResponseParser(KeyPairsHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -107,7 +103,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#listKeyPairs */ @GET - @Path("") @Consumes(KEYSLIST_XML) @XMLResponseParser(KeyPairsHandler.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @@ -117,7 +112,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#generateKeyPairInOrg */ @POST - @Path("") @Produces(KEYSLIST_XML) @Consumes(KEYSLIST_XML) @XMLResponseParser(KeyPairHandler.class) @@ -130,7 +124,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#getKeyPair */ @GET - @Path("") @XMLResponseParser(KeyPairHandler.class) @Consumes(APPLICATION_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -155,7 +148,6 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC * @see TerremarkVCloudExpressClient#deleteKeyPair */ @DELETE - @Path("") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteKeyPair(@EndpointParam URI keyId); diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayload.java index 098d0d649b..7037e4151b 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayload.java @@ -20,7 +20,6 @@ package org.jclouds.vcloud.terremark.binders; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.replaceTokens; import static org.jclouds.vcloud.terremark.reference.TerremarkConstants.PROPERTY_TERREMARK_EXTENSION_NS; import java.util.Map; @@ -33,7 +32,7 @@ import org.jclouds.http.HttpRequest; import org.jclouds.rest.MapBinder; import org.jclouds.rest.binders.BindToStringPayload; import org.jclouds.util.Patterns; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.collect.ImmutableMap; @@ -53,24 +52,24 @@ public class BindAddInternetServiceToXmlPayload implements MapBinder { @Named(PROPERTY_TERREMARK_EXTENSION_NS) private String ns; - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { String name = checkNotNull(postParams.get("name"), "name parameter not present"); String protocol = checkNotNull(postParams.get("protocol"), "protocol parameter not present"); String port = checkNotNull(postParams.get("port"), "port parameter not present"); String enabled = checkNotNull(postParams.get("enabled"), "enabled parameter not present"); String description = postParams.get("description"); - String payload = replaceTokens(xmlTemplate, ImmutableMap.of("name", name, "protocol", - protocol, "port", port, "enabled", enabled, "ns", ns)); - payload = Utils.replaceAll(payload, Patterns.TOKEN_TO_PATTERN.get("description"), - description == null ? "" : String.format("\n %s", - description)); - stringBinder.bindToRequest(request, payload); + String payload = Strings2.replaceTokens(xmlTemplate, + ImmutableMap.of("name", name, "protocol", protocol, "port", port, "enabled", enabled, "ns", ns)); + payload = Strings2.replaceAll(payload, Patterns.TOKEN_TO_PATTERN.get("description"), description == null ? "" + : String.format("\n %s", description)); + return stringBinder.bindToRequest(request, payload); } - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("CreateInternetService needs parameters"); - } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayload.java index 801979f2e7..c03c15be62 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayload.java @@ -20,7 +20,6 @@ package org.jclouds.vcloud.terremark.binders; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.replaceTokens; import static org.jclouds.vcloud.terremark.reference.TerremarkConstants.PROPERTY_TERREMARK_EXTENSION_NS; import java.util.Map; @@ -33,7 +32,7 @@ import org.jclouds.http.HttpRequest; import org.jclouds.rest.MapBinder; import org.jclouds.rest.binders.BindToStringPayload; import org.jclouds.util.Patterns; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import com.google.common.collect.ImmutableMap; @@ -54,25 +53,24 @@ public class BindAddNodeServiceToXmlPayload implements MapBinder { @Named(PROPERTY_TERREMARK_EXTENSION_NS) private String ns; - public void bindToRequest(HttpRequest request, Map postParams) { - String ipAddress = checkNotNull(postParams.get("ipAddress"), - "ipAddress parameter not present"); + @Override + public R bindToRequest(R request, Map postParams) { + String ipAddress = checkNotNull(postParams.get("ipAddress"), "ipAddress parameter not present"); String name = checkNotNull(postParams.get("name"), "name parameter not present"); String port = checkNotNull(postParams.get("port"), "port parameter not present"); String enabled = checkNotNull(postParams.get("enabled"), "enabled parameter not present"); String description = postParams.get("description"); - String payload = replaceTokens(xmlTemplate, ImmutableMap.of("name", name, "ipAddress", - ipAddress, "port", port, "enabled", enabled, "ns", ns)); - payload = Utils.replaceAll(payload, Patterns.TOKEN_TO_PATTERN.get("description"), - description == null ? "" : String.format("\n %s", - description)); - stringBinder.bindToRequest(request, payload); + String payload = Strings2.replaceTokens(xmlTemplate, + ImmutableMap.of("name", name, "ipAddress", ipAddress, "port", port, "enabled", enabled, "ns", ns)); + payload = Strings2.replaceAll(payload, Patterns.TOKEN_TO_PATTERN.get("description"), description == null ? "" + : String.format("\n %s", description)); + return stringBinder.bindToRequest(request, payload); } - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("CreateNodeService needs parameters"); - } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java index bd472506e0..a8325dc483 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java @@ -20,7 +20,6 @@ package org.jclouds.vcloud.terremark.binders; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.util.Utils.replaceTokens; import static org.jclouds.vcloud.terremark.reference.TerremarkConstants.PROPERTY_TERREMARK_EXTENSION_NS; import java.util.Map; @@ -32,6 +31,7 @@ import javax.inject.Singleton; import org.jclouds.http.HttpRequest; import org.jclouds.rest.MapBinder; import org.jclouds.rest.binders.BindToStringPayload; +import org.jclouds.util.Strings2; import com.google.common.collect.ImmutableMap; @@ -48,26 +48,26 @@ public class BindCreateKeyToXmlPayload implements MapBinder { private final String ns; @Inject - BindCreateKeyToXmlPayload(@Named(PROPERTY_TERREMARK_EXTENSION_NS) String ns, - @Named("CreateKey") String xmlTemplate, BindToStringPayload stringBinder) { + BindCreateKeyToXmlPayload(@Named(PROPERTY_TERREMARK_EXTENSION_NS) String ns, @Named("CreateKey") String xmlTemplate, + BindToStringPayload stringBinder) { this.ns = ns; this.xmlTemplate = xmlTemplate; this.stringBinder = stringBinder; } - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { String name = checkNotNull(postParams.get("name"), "name parameter not present"); - String isDefault = checkNotNull(postParams.get("isDefault"), - "isDefault parameter not present"); + String isDefault = checkNotNull(postParams.get("isDefault"), "isDefault parameter not present"); - String payload = replaceTokens(xmlTemplate, ImmutableMap.of("name", name, "isDefault", - isDefault, "ns", ns)); - stringBinder.bindToRequest(request, payload); + String payload = Strings2.replaceTokens(xmlTemplate, + ImmutableMap.of("name", name, "isDefault", isDefault, "ns", ns)); + return stringBinder.bindToRequest(request, payload); } - public void bindToRequest(HttpRequest request, Object input) { + @Override + public R bindToRequest(R request, Object input) { throw new IllegalStateException("CreateKey needs parameters"); - } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java index 4e35f33920..56b3c920aa 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java @@ -70,16 +70,17 @@ public class BindNodeConfigurationToXmlPayload implements MapBinder { } @Override - public void bindToRequest(HttpRequest request, Map postParams) { + public R bindToRequest(R request, Map postParams) { try { - stringBinder.bindToRequest(request, generateXml(postParams)); + return stringBinder.bindToRequest(request, generateXml(postParams)); } catch (Exception e) { Throwables.propagate(e); } + return request; } @Override - public void bindToRequest(HttpRequest request, Object input) { + public R bindToRequest(R request, Object input) { throw new IllegalArgumentException("this is a map binder"); } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindVAppConfigurationToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindVAppConfigurationToXmlPayload.java index d09ec97ab8..6538ca0d40 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindVAppConfigurationToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindVAppConfigurationToXmlPayload.java @@ -78,11 +78,11 @@ public class BindVAppConfigurationToXmlPayload implements MapBinder, Function postParams) { + @Override + public R bindToRequest(R request, Map postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, "this binder is only valid for GeneratedHttpRequests!"); - GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; checkState(gRequest.getArgs() != null, "args should be initialized at this point"); VCloudExpressVApp vApp = checkNotNull(findVAppInArgsOrNull(gRequest), "vApp"); @@ -90,7 +90,7 @@ public class BindVAppConfigurationToXmlPayload implements MapBinder, Function R bindToRequest(R request, Object input) { throw new IllegalStateException("BindVAppConfigurationToXmlPayload needs parameters"); } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java index 7c183fd7a7..c420fa29dd 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java @@ -31,7 +31,7 @@ import javax.inject.Singleton; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; +import org.jclouds.util.Throwables2; import org.jclouds.vcloud.terremark.TerremarkVCloudClient; import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; import org.jclouds.vcloud.terremark.domain.KeyPair; @@ -72,7 +72,7 @@ public class CreateUniqueKeyPair implements Function { keyPair = trmkClient.generateKeyPairInOrg(org, getNextName(keyPairName), false); logger.debug("<< created keyPair(%s)", keyPair.getName()); } catch (RuntimeException e) { - HttpResponseException ht = Utils.getFirstThrowableOfType(e, HttpResponseException.class); + HttpResponseException ht = Throwables2.getFirstThrowableOfType(e, HttpResponseException.class); if (ht == null || ht.getContent() == null || ht.getContent().indexOf("Security key with same name exists") == -1) throw e; diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java index 271adea0e4..111854c686 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java @@ -26,7 +26,7 @@ import java.util.Arrays; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.io.Payload; -import org.jclouds.util.Utils; +import org.jclouds.util.Preconditions2; /** * Contains options supported in the {@code ComputeService#runNode} operation on the @@ -58,7 +58,7 @@ public class TerremarkVCloudTemplateOptions extends TemplateOptions { public TerremarkVCloudTemplateOptions sshKeyFingerprint(String keyPair) { checkNotNull(keyPair, "use noKeyPair option to request boot without a keypair"); checkState(!noKeyPair, "you cannot specify both options keyPair and noKeyPair"); - Utils.checkNotEmpty(keyPair, "keypair must be non-empty"); + Preconditions2.checkNotEmpty(keyPair, "keypair must be non-empty"); this.keyPair = keyPair; return this; } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkRestClientModule.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkRestClientModule.java index 141e6bf41d..35c55d2243 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkRestClientModule.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkRestClientModule.java @@ -33,7 +33,7 @@ import org.jclouds.http.annotation.ClientError; import org.jclouds.http.annotation.Redirection; import org.jclouds.http.annotation.ServerError; import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.config.BaseVCloudExpressRestClientModule; import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.VCloudSession; @@ -58,7 +58,7 @@ public abstract class TerremarkRestClientModule postParams) { + @Override + public R bindToRequest(R request, Map postParams) { Map copy = Maps.newHashMap(); copy.putAll(postParams); copy.put("description", description); copy.put("enabled", enabled); - super.bindToRequest(request, copy); + return super.bindToRequest(request, copy); } public AddInternetServiceOptions disabled() { diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/AddNodeOptions.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/AddNodeOptions.java index c2b7851957..4926c96288 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/AddNodeOptions.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/AddNodeOptions.java @@ -38,13 +38,13 @@ public class AddNodeOptions extends BindAddNodeServiceToXmlPayload { String description = null; @VisibleForTesting String enabled = "true"; - - public void bindToRequest(HttpRequest request, Map postParams) { + @Override + public R bindToRequest(R request, Map postParams) { Map copy = Maps.newHashMap(); copy.putAll(postParams); copy.put("description", description); copy.put("enabled", enabled); - super.bindToRequest(request, copy); + return super.bindToRequest(request, copy); } public AddNodeOptions disabled() { diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandler.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandler.java index 3cdf2b54ae..9b565da90d 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandler.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandler.java @@ -49,7 +49,7 @@ public class KeyPairByNameHandler extends ParseSax.HandlerForGeneratedRequestWit @Override public KeyPair getResult() { - final String name = getRequest().getArgs()[1].toString(); + final String name = getRequest().getArgs().get(1).toString(); try { return Iterables.find(handler.getResult(), new Predicate() { @@ -60,7 +60,7 @@ public class KeyPairByNameHandler extends ParseSax.HandlerForGeneratedRequestWit }); } catch (NoSuchElementException e) { - logger.debug("keypair %s/%s not found in %s", getRequest().getArgs()[0], name, handler.getResult()); + logger.debug("keypair %s/%s not found in %s", getRequest().getArgs().get(0), name, handler.getResult()); return null; } } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java index f31ec6423b..4d3c3b2255 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java @@ -48,7 +48,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "vcloud.TerremarkVCloudClientLiveTest") +@Test(groups = "live", sequential = true) public class InternetServiceLiveTest { TerremarkVCloudExpressClient tmClient; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/ProvidersInPropertiesTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/ProvidersInPropertiesTest.java index 85145e732f..200a062d32 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/ProvidersInPropertiesTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/ProvidersInPropertiesTest.java @@ -20,7 +20,7 @@ package org.jclouds.vcloud.terremark; import org.jclouds.compute.util.ComputeServiceUtils; -import org.jclouds.util.Utils; +import org.jclouds.rest.Providers; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); + Iterable providers = Providers.getSupportedProviders(); assert Iterables.contains(providers, "trmk-vcloudexpress") : providers; assert Iterables.contains(providers, "trmk-ecloud") : providers; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java index 17736e8255..552176bcda 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java @@ -47,7 +47,7 @@ import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.CommonVCloudClient; import org.jclouds.vcloud.VCloudExpressAsyncClientTest.VCloudRestClientModuleExtension.TestOrgCatalogItemSupplier; import org.jclouds.vcloud.VCloudExpressAsyncClientTest.VCloudRestClientModuleExtension.TestOrgCatalogSupplier; @@ -95,7 +95,8 @@ import domain.VCloudVersionsAsyncClient; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true, testName = "TerremarkECloudAsyncClientTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TerremarkECloudAsyncClientTest") public class TerremarkECloudAsyncClientTest extends RestClientTest { public void testNetwork() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkECloudAsyncClient.class.getMethod("getNetwork", URI.class); @@ -172,7 +173,7 @@ public class TerremarkECloudAsyncClientTest extends RestClientTest { public void testCatalogItemURI() throws SecurityException, NoSuchMethodException, IOException { @@ -178,7 +179,7 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTest of(), null, null, null, ImmutableSet.of( - new ResourceAllocation(1, "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, - null, 2, null), new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, - null, null, null, null, null, 1024, null), new ResourceAllocation(9, "n/a", null, - ResourceType.DISK_DRIVE, null, "1048576", null, 0, null, null, 209152, null))); + VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("MyAppServer6", + URI.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, null, + ImmutableListMultimap. of(), null, null, null, ImmutableSet.of(new ResourceAllocation(1, + "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, null, 2, null), + new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null, null, null, null, null, 1024, + null), new ResourceAllocation(9, "n/a", null, ResourceType.DISK_DRIVE, null, "1048576", null, + 0, null, null, 209152, null))); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp.xml")).replace( - "eduardo", "roberto"); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp.xml")) + .replace("eduardo", "roberto"); VAppConfiguration config = new VAppConfiguration().changeNameTo("roberto"); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { vApp, config }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList. of(vApp, config)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -92,24 +94,23 @@ public class BindVAppConfigurationToXmlPayloadTest { } public void testRemoveDisk() throws IOException { - VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("MyAppServer6", URI - .create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, - null, ImmutableListMultimap. of(), null, null, null, ImmutableSet.of( - new ResourceAllocation(1, "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, - null, 2, null), new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, - null, null, null, null, null, 1024, null), new ResourceAllocation(9, "n/a", null, - ResourceType.DISK_DRIVE, null, "1048576", null, 0, null, null, 209152, null), - new ResourceAllocation(9, "n/a", null, ResourceType.DISK_DRIVE, null, "1048576", null, 1, null, - null, 209152, null))); + VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("MyAppServer6", + URI.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, null, + ImmutableListMultimap. of(), null, null, null, ImmutableSet.of(new ResourceAllocation(1, + "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, null, 2, null), + new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null, null, null, null, null, 1024, + null), new ResourceAllocation(9, "n/a", null, ResourceType.DISK_DRIVE, null, "1048576", null, + 0, null, null, 209152, null), new ResourceAllocation(9, "n/a", null, ResourceType.DISK_DRIVE, + null, "1048576", null, 1, null, null, 209152, null))); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp.xml")).replace( - "eduardo", "MyAppServer6"); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp.xml")) + .replace("eduardo", "MyAppServer6"); VAppConfiguration config = new VAppConfiguration().deleteDiskWithAddressOnParent(1); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { vApp, config }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList. of(vApp, config)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -121,20 +122,20 @@ public class BindVAppConfigurationToXmlPayloadTest { } public void testChangeCPUCountTo4() throws IOException { - VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("eduardo", URI - .create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, - null, ImmutableListMultimap. of(), null, null, null, ImmutableSet.of( - new ResourceAllocation(1, "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, - null, 4, null), new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, - null, null, null, null, null, 1024, null), new ResourceAllocation(9, "n/a", null, - ResourceType.DISK_DRIVE, null, "1048576", null, 0, null, null, 209152, null))); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp4.xml")); + VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("eduardo", + URI.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, null, + ImmutableListMultimap. of(), null, null, null, ImmutableSet.of(new ResourceAllocation(1, + "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, null, 4, null), + new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null, null, null, null, null, 1024, + null), new ResourceAllocation(9, "n/a", null, ResourceType.DISK_DRIVE, null, "1048576", null, + 0, null, null, 209152, null))); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp4.xml")); VAppConfiguration config = new VAppConfiguration().changeProcessorCountTo(4); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { vApp, config }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList. of(vApp, config)).atLeastOnce(); request.setPayload(expected); replay(request); @@ -146,22 +147,22 @@ public class BindVAppConfigurationToXmlPayloadTest { } public void testChangeMemoryTo1536() throws IOException { - VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("MyAppServer6", URI - .create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, - null, ImmutableListMultimap. of(), null, null, null, ImmutableSet.of( - new ResourceAllocation(1, "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, - null, 2, null), new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, - null, null, null, null, null, 1536, null), new ResourceAllocation(9, "n/a", null, - ResourceType.DISK_DRIVE, null, "1048576", null, 0, null, null, 209152, null))); + VCloudExpressVAppImpl vApp = new VCloudExpressVAppImpl("MyAppServer6", + URI.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"), Status.OFF, 4194304l, null, + ImmutableListMultimap. of(), null, null, null, ImmutableSet.of(new ResourceAllocation(1, + "n/a", null, ResourceType.PROCESSOR, null, null, null, null, null, null, 2, null), + new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null, null, null, null, null, 1536, + null), new ResourceAllocation(9, "n/a", null, ResourceType.DISK_DRIVE, null, "1048576", null, + 0, null, null, 209152, null))); - String expected = Utils.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp.xml")).replace( - "eduardo", "MyAppServer6").replace("1024", "1536"); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/terremark/configureVApp.xml")) + .replace("eduardo", "MyAppServer6").replace("1024", "1536"); VAppConfiguration config = new VAppConfiguration().changeMemoryTo(1536); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getArgs()).andReturn(new Object[] { vApp, config }).atLeastOnce(); + expect(request.getArgs()).andReturn(ImmutableList. of(vApp, config)).atLeastOnce(); request.setPayload(expected); replay(request); diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest.java index 84c3779947..3a546b038b 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest.java @@ -32,7 +32,7 @@ import java.util.Properties; import javax.inject.Singleton; import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.util.Utils; +import org.jclouds.util.Strings2; import org.jclouds.vcloud.domain.network.NetworkConfig; import org.jclouds.vcloud.endpoints.Network; import org.jclouds.vcloud.terremark.TerremarkVCloudPropertiesBuilder; @@ -40,6 +40,7 @@ import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOpti import org.testng.annotations.Test; import com.google.common.collect.HashMultimap; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; @@ -54,16 +55,14 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest") +@Test(groups = "unit") public class TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { Properties props = new Properties(); - Names - .bindProperties(binder(), checkNotNull(new TerremarkVCloudPropertiesBuilder(props).build(), - "properties")); + Names.bindProperties(binder(), checkNotNull(new TerremarkVCloudPropertiesBuilder(props).build(), "properties")); } @SuppressWarnings("unused") @@ -77,22 +76,22 @@ public class TerremarkBindInstantiateVAppTemplateParamsToXmlPayloadTest { public void testAllOptions() throws IOException { - String expected = Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/InstantiateVAppTemplateParams-options-test.xml")); + String expected = Strings2.toStringAndClose(getClass().getResourceAsStream( + "/terremark/InstantiateVAppTemplateParams-options-test.xml")); Multimap headers = Multimaps.synchronizedMultimap(HashMultimap. create()); GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); expect(request.getArgs()).andReturn( - new Object[] { TerremarkInstantiateVAppTemplateOptions.Builder.processorCount(2).memory(512).inGroup( - "group").withPassword("password").inRow("row").addNetworkConfig( - new NetworkConfig(URI.create("http://network"))) }).atLeastOnce(); + ImmutableList. of(TerremarkInstantiateVAppTemplateOptions.Builder.processorCount(2).memory(512) + .inGroup("group").withPassword("password").inRow("row") + .addNetworkConfig(new NetworkConfig(URI.create("http://network"))))).atLeastOnce(); expect(request.getFirstHeaderOrNull("Content-Type")).andReturn("application/unknown").atLeastOnce(); expect(request.getHeaders()).andReturn(headers).atLeastOnce(); request.setPayload(expected); replay(request); TerremarkBindInstantiateVAppTemplateParamsToXmlPayload binder = injector - .getInstance(TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.class); + .getInstance(TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.class); Map map = Maps.newHashMap(); map.put("name", "name"); diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudComputeServiceLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudComputeServiceLiveTest.java index ea30431be5..5a6fe2e759 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudComputeServiceLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudComputeServiceLiveTest.java @@ -44,7 +44,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "terremark.TerremarkVCloudComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class TerremarkECloudComputeServiceLiveTest extends BaseComputeServiceLiveTest { public TerremarkECloudComputeServiceLiveTest() { provider = "trmk-ecloud"; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudTemplateBuilderLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudTemplateBuilderLiveTest.java index 3770e566b8..7d4a6675a6 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudTemplateBuilderLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkECloudTemplateBuilderLiveTest.java @@ -36,7 +36,7 @@ import com.google.common.base.Predicate; * * @author Adrian Cole */ -@Test(groups = "live", testName = "terremark.TerremarkECloudTemplateBuilderLiveTest") +@Test(groups = "live") public class TerremarkECloudTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public TerremarkECloudTemplateBuilderLiveTest() { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java index 0e5d1bd44d..eec37c44cb 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java @@ -51,7 +51,7 @@ import com.google.common.io.ByteStreams; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.TerremarkVCloudComputeClientTest") +@Test(groups = "unit") public class TerremarkVCloudComputeClientTest { @SuppressWarnings("unchecked") @Test diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressComputeServiceLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressComputeServiceLiveTest.java index f8d52c5c10..5887f2e4c1 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressComputeServiceLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressComputeServiceLiveTest.java @@ -44,7 +44,7 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true, testName = "terremark.TerremarkVCloudComputeServiceLiveTest") +@Test(groups = "live", enabled = true, sequential = true) public class TerremarkVCloudExpressComputeServiceLiveTest extends BaseComputeServiceLiveTest { public TerremarkVCloudExpressComputeServiceLiveTest() { provider = "trmk-vcloudexpress"; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressTemplateBuilderLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressTemplateBuilderLiveTest.java index c30a81d0c4..34a89ac71e 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressTemplateBuilderLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudExpressTemplateBuilderLiveTest.java @@ -36,7 +36,7 @@ import com.google.common.base.Predicate; * * @author Adrian Cole */ -@Test(groups = "live", testName = "terremark.TerremarkVCloudExpressTemplateBuilderLiveTest") +@Test(groups = "live") public class TerremarkVCloudExpressTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public TerremarkVCloudExpressTemplateBuilderLiveTest() { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java index 3f41655e68..30110cb7a4 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java @@ -41,7 +41,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.CleanupOrphanKeysTest") +@Test(groups = "unit") public class CleanupOrphanKeysTest { public void testWhenNoDeletedNodes() { @@ -181,6 +181,7 @@ public class CleanupOrphanKeysTest { NodeMetadataToOrgAndName nodeToOrgAndName = createMock(NodeMetadataToOrgAndName.class); DeleteKeyPair deleteKeyPair = createMock(DeleteKeyPair.class); ListNodesStrategy listNodes = createMock(ListNodesStrategy.class); + @SuppressWarnings("unchecked") Map credentialStore = createMock(Map.class); return new CleanupOrphanKeys(nodeToOrgAndName, deleteKeyPair, credentialStore, listNodes); } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java index 7edac14be5..cc615e4d18 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java @@ -40,7 +40,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest") +@Test(groups = "unit") public class CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest { public void testExecuteWithDefaultOptionsAlreadyHasKey() throws SecurityException, NoSuchMethodException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java index 3318de4deb..b75c449e7c 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java @@ -38,7 +38,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.DeleteKeyPairTest") +@Test(groups = "unit") public class DeleteKeyPairTest { public void testWhenNoKeyPairsInOrg() { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/PopulateDefaultLoginCredentialsForVAppTemplateTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/PopulateDefaultLoginCredentialsForVAppTemplateTest.java index 8298ce5789..e67c94c257 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/PopulateDefaultLoginCredentialsForVAppTemplateTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/PopulateDefaultLoginCredentialsForVAppTemplateTest.java @@ -37,7 +37,7 @@ import com.google.common.io.ByteStreams; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.PopulateDefaultLoginCredentialsForVAppTemplateTest") +@Test(groups = "unit") public class PopulateDefaultLoginCredentialsForVAppTemplateTest { @Test diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgsLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgsLiveTest.java index e62121d903..6c93e0f809 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgsLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgsLiveTest.java @@ -49,7 +49,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", sequential = true, testName = "terremark.VAppTemplatesInOrgsLiveTest") +@Test(groups = "live", sequential = true) public class VAppTemplatesInOrgsLiveTest { private TerremarkVCloudClient tmClient; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddInternetServiceOptionsTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddInternetServiceOptionsTest.java index eef5f26e79..267df5d9b7 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddInternetServiceOptionsTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddInternetServiceOptionsTest.java @@ -34,7 +34,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.CreateInternetServiceOptionsTest") +@Test(groups = "unit") public class AddInternetServiceOptionsTest { Injector injector = Guice.createInjector(new SaxParserModule()); diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddNodeOptionsTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddNodeOptionsTest.java index 8f4f8c3fd9..c541392172 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddNodeOptionsTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/AddNodeOptionsTest.java @@ -34,7 +34,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.AddNodeOptionsTest") +@Test(groups = "unit") public class AddNodeOptionsTest { Injector injector = Guice.createInjector(new SaxParserModule()); diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptionsTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptionsTest.java index 87bafe360d..b4fcb86fbe 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptionsTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptionsTest.java @@ -44,7 +44,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TerremarkInstantiateVAppTemplateOptionsTest") +@Test(groups = "unit") public class TerremarkInstantiateVAppTemplateOptionsTest { Injector injector = Guice.createInjector(new SaxParserModule()); diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java index 9e6d0e8fa3..1eb2c338d0 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java @@ -33,7 +33,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.CustomizationParametersHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "CustomizationParametersHandlerTest") public class CustomizationParametersHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServiceHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServiceHandlerTest.java index a0239ccfc7..257e5645ea 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServiceHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServiceHandlerTest.java @@ -37,7 +37,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.InternetServiceHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "InternetServiceHandlerTest") public class InternetServiceHandlerTest extends BaseHandlerTest { @BeforeTest diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServicesHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServicesHandlerTest.java index 035fcae083..eb315e2d0a 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServicesHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/InternetServicesHandlerTest.java @@ -39,7 +39,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.InternetServicesHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "InternetServicesHandlerTest") public class InternetServicesHandlerTest extends BaseHandlerTest { public void test2() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/IpAddressesHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/IpAddressesHandlerTest.java index 6791a0dbe5..85448eb372 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/IpAddressesHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/IpAddressesHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.IpAddressesHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "IpAddressesHandlerTest") public class IpAddressesHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java index 6608cdf0ca..edf408edc8 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java @@ -29,7 +29,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.KeyHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "KeyHandlerTest") public class KeyHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandlerTest.java index 0756f89e44..fbde778525 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyPairByNameHandlerTest.java @@ -33,12 +33,15 @@ import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.vcloud.terremark.domain.KeyPair; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; + /** * Tests behavior of {@code KeyPairByNameHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.KeyPairByNameHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "KeyPairByNameHandlerTest") public class KeyPairByNameHandlerTest extends BaseHandlerTest { public void testGood() throws UnknownHostException { @@ -46,9 +49,9 @@ public class KeyPairByNameHandlerTest extends BaseHandlerTest { KeyPair result = factory.create( addOrgAndNameToHandler(injector.getInstance(KeyPairByNameHandler.class), "org", "default")).parse(is); - assertEquals(result, new KeyPair(URI - .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/extensions/key/9"), "default", true, - null, "4e:af:8a:9f:e9:d2:72:d7:4b:a0:da:98:72:98:4d:7d")); + assertEquals(result, + new KeyPair(URI.create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/extensions/key/9"), + "default", true, null, "4e:af:8a:9f:e9:d2:72:d7:4b:a0:da:98:72:98:4d:7d")); } @@ -63,7 +66,7 @@ public class KeyPairByNameHandlerTest extends BaseHandlerTest { private static KeyPairByNameHandler addOrgAndNameToHandler(KeyPairByNameHandler handler, String org, String name) { GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { org, name }).anyTimes(); + expect(request.getArgs()).andReturn(ImmutableList. of(org, name)).anyTimes(); replay(request); handler.setContext(request); return handler; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java index 2e9a9f4fbb..c00d911713 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.KeysHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "KeysHandlerTest") public class KeysHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodeHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodeHandlerTest.java index 7493c94f40..9d25bb2cf8 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodeHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodeHandlerTest.java @@ -30,11 +30,12 @@ import org.jclouds.vcloud.terremark.domain.Node; import org.testng.annotations.Test; /** - * Tests behavior of {@code NodeServiceHandler} + * Tests behavior of {@code NodeHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.NodeServiceHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "NodeHandlerTest") public class NodeHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodesHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodesHandlerTest.java index 8731068037..9d5f046614 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodesHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/NodesHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.NodesHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "NodesHandlerTest") public class NodesHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressHandlerTest.java index e8cfb4b718..ba01cd2d11 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressHandlerTest.java @@ -34,7 +34,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.PublicIpAddressHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "PublicIpAddressHandlerTest") public class PublicIpAddressHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressesHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressesHandlerTest.java index 8337c5db12..af659cdfcd 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressesHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressesHandlerTest.java @@ -37,7 +37,8 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.PublicIpAddressesHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "PublicIpAddressesHandlerTest") public class PublicIpAddressesHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ResourceAllocationHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ResourceAllocationHandlerTest.java index f64a5edec9..4948848f9e 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ResourceAllocationHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ResourceAllocationHandlerTest.java @@ -35,7 +35,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.ResourceAllocationHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "ResourceAllocationHandlerTest") public class ResourceAllocationHandlerTest extends BaseHandlerTest { @BeforeTest diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkCatalogItemHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkCatalogItemHandlerTest.java index 6d516f5742..3bd2770023 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkCatalogItemHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkCatalogItemHandlerTest.java @@ -45,7 +45,8 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TerremarkCatalogItemHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TerremarkCatalogItemHandlerTest") public class TerremarkCatalogItemHandlerTest extends BaseHandlerTest { @Override @BeforeTest diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkNetworkHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkNetworkHandlerTest.java index 2f2019529f..9119516fcc 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkNetworkHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkNetworkHandlerTest.java @@ -34,7 +34,8 @@ import org.testng.annotations.Test; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.TerremarkNetworkHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TerremarkNetworkHandlerTest") public class TerremarkNetworkHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java index ef687c17a7..eaf9c51fdd 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java @@ -48,7 +48,8 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TerremarkOrgHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "TerremarkOrgHandlerTest") public class TerremarkOrgHandlerTest extends BaseHandlerTest { @Override @BeforeTest diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVCloudExpressNetworkHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVCloudExpressNetworkHandlerTest.java index ab550c1768..ac1eee753b 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVCloudExpressNetworkHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVCloudExpressNetworkHandlerTest.java @@ -44,7 +44,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "terremark.TerremarkVCloudExpressNetworkHandlerTest") +@Test(groups = "unit") public class TerremarkVCloudExpressNetworkHandlerTest { private Injector injector; diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVDCHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVDCHandlerTest.java index baf0b32f16..0b619b0bae 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVDCHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkVDCHandlerTest.java @@ -43,7 +43,7 @@ import com.google.inject.Injector; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.TerremarkVDCHandlerTest") +@Test(groups = "unit") public class TerremarkVDCHandlerTest { public void testApplyInputStream() { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/VAppHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/VAppHandlerTest.java index 38caf71c53..933f13bd1d 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/VAppHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/VAppHandlerTest.java @@ -57,7 +57,8 @@ import com.google.inject.name.Names; * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VAppHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "VAppHandlerTest") public class VAppHandlerTest extends BaseHandlerTest { @BeforeTest diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ovf/SystemHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ovf/SystemHandlerTest.java index 63a359dd32..9590d6bb8c 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ovf/SystemHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ovf/SystemHandlerTest.java @@ -32,11 +32,12 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; /** - * Tests behavior of {@code VirtualSystemHandler} + * Tests behavior of {@code SystemHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.VirtualSystemHandlerTest") +// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +@Test(groups = "unit", testName = "SystemHandlerTest") public class SystemHandlerTest extends BaseHandlerTest { @BeforeTest