From d57197c1039e09c62d848a9929a7c1f8cdb6d0c0 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 12 Jan 2013 12:31:00 -0800 Subject: [PATCH] cleaned up code references detected as unnecessary by UEC plugin --- .../features/FirewallClientLiveTest.java | 2 +- .../features/LoadBalancerClientLiveTest.java | 2 +- .../features/SecurityGroupClientLiveTest.java | 2 +- .../VirtualMachineClientLiveTest.java | 2 +- ...ticNATVirtualMachineInNetworkLiveTest.java | 2 +- .../ec2/compute/EC2TemplateBuilderTest.java | 6 +- .../compute/functions/EC2ImageParserTest.java | 6 +- .../RunningInstanceToNodeMetadataTest.java | 4 +- .../strategy/NovaReviseParsedImageTest.java | 2 +- ...MatchingConfigurationKeyOrDefaultTest.java | 39 +-- ...MatchingConfigurationKeyOrDefaultTest.java | 39 +-- ...riptUsingSshAndBlockUntilCompleteTest.java | 11 +- .../RunScriptOnNodeUsingSshTest.java | 4 +- ...sFromImageOrOverridingCredentialsTest.java | 51 +--- ...PrioritizeCredentialsFromTemplateTest.java | 65 ++--- .../ReturnCredentialsBoundToImageTest.java | 3 +- core/src/main/java/org/jclouds/Fallbacks.java | 4 +- core/src/main/java/org/jclouds/View.java | 9 +- core/src/main/java/org/jclouds/apis/Apis.java | 2 +- .../apis/internal/BaseApiMetadata.java | 63 ++-- .../jclouds/cache/ForwardingCacheLoader.java | 21 -- .../cache/RetryingCacheLoaderDecorator.java | 6 +- ...onentiallyAndRetryOnThrowableCallable.java | 2 +- .../org/jclouds/collect/AbstractMapEntry.java | 12 +- .../collect/AdvanceUntilEmptyIterable.java | 4 +- .../collect/ForwardingIterableWithMarker.java | 52 ---- .../org/jclouds/collect/InputSupplierMap.java | 7 +- .../jclouds/collect/IterableWithMarkers.java | 15 +- .../org/jclouds/collect/PagedIterables.java | 12 +- .../org/jclouds/collect/TransformingMap.java | 8 +- .../jclouds/concurrent/DynamicExecutors.java | 155 +--------- .../concurrent/DynamicThreadPoolExecutor.java | 276 +++++++++--------- .../jclouds/concurrent/FutureIterables.java | 25 +- .../java/org/jclouds/concurrent/Futures.java | 29 +- .../TransformParallelException.java | 1 + .../concurrent/config/DescribedFuture.java | 4 +- .../config/DescribingExecutorService.java | 9 +- .../config/ExecutorServiceModule.java | 61 ++-- .../ScheduledExecutorServiceModule.java | 133 ++++----- .../BindPropertiesToExpandedValues.java | 1 - .../config/ValueOfConfigurationKeyOrNull.java | 7 +- .../main/java/org/jclouds/crypto/Pems.java | 6 +- .../crypto/RsaSshKeyPairGenerator.java | 8 +- .../java/org/jclouds/crypto/Sha512Crypt.java | 5 +- .../main/java/org/jclouds/crypto/SshKeys.java | 6 +- .../java/org/jclouds/date/DateService.java | 2 - .../org/jclouds/date/internal/DateUtils.java | 10 +- .../internal/SimpleDateFormatDateService.java | 5 - .../java/org/jclouds/domain/Credentials.java | 26 -- .../java/org/jclouds/domain/JsonBall.java | 2 +- .../org/jclouds/domain/LocationBuilder.java | 14 +- .../org/jclouds/domain/LocationScope.java | 1 - .../org/jclouds/domain/LoginCredentials.java | 54 +--- .../jclouds/domain/internal/LocationImpl.java | 11 +- .../encryption/internal/JCECrypto.java | 4 +- .../jclouds/events/config/EventBusModule.java | 69 +++-- .../handlers/DeadEventLoggingHandler.java | 20 +- .../MapHttp4xxCodesToExceptions.java | 9 +- core/src/main/java/org/jclouds/http/Uris.java | 15 +- .../org/jclouds/http/functions/ParseSax.java | 9 +- .../java/org/jclouds/internal/BaseView.java | 5 - ...ructorAndReflectiveTypeAdapterFactory.java | 18 +- .../rest/binders/BindMapToStringPayload.java | 2 +- .../java/org/jclouds/PerformanceTest.java | 4 +- .../ValueOfConfigurationKeyOrNullTest.java | 12 +- .../crypto/RsaSshKeyPairGeneratorTest.java | 13 +- .../org/jclouds/date/DateServiceTest.java | 7 - .../org/jclouds/domain/CredentialsTest.java | 62 ---- .../test/java/org/jclouds/http/UrisTest.java | 18 +- ...reenQloudComputeReviseParsedImageTest.java | 18 +- .../internal/JsonNodeMetadataStore.java | 8 +- .../jclouds/virtualbox/domain/YamlImage.java | 5 +- .../functions/IMachineToNodeMetadata.java | 7 +- .../functions/MastersLoadingCache.java | 5 +- .../virtualbox/functions/NodeCreator.java | 8 +- .../strategy/AWSEC2ImageParserTest.java | 16 +- 76 files changed, 579 insertions(+), 1063 deletions(-) delete mode 100644 core/src/main/java/org/jclouds/collect/ForwardingIterableWithMarker.java diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallClientLiveTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallClientLiveTest.java index 8a9713a5be..7f64aa3415 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallClientLiveTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallClientLiveTest.java @@ -80,7 +80,7 @@ public class FirewallClientLiveTest extends BaseCloudStackClientLiveTest { defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete, virtualMachineRunning); - if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) + if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null) loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); } catch (NoSuchElementException e) { diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LoadBalancerClientLiveTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LoadBalancerClientLiveTest.java index 9872434ff2..3c2dc31f99 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LoadBalancerClientLiveTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LoadBalancerClientLiveTest.java @@ -95,7 +95,7 @@ public class LoadBalancerClientLiveTest extends BaseCloudStackClientLiveTest { vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network, defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete, virtualMachineRunning); - if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) + if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null) loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); } diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SecurityGroupClientLiveTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SecurityGroupClientLiveTest.java index db8e16a074..8ce894d6c7 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SecurityGroupClientLiveTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SecurityGroupClientLiveTest.java @@ -181,7 +181,7 @@ public class SecurityGroupClientLiveTest extends BaseCloudStackClientLiveTest { vm = VirtualMachineClientLiveTest.createVirtualMachineWithSecurityGroupInZone(zone.getId(), defaultTemplateOrPreferredInZone(defaultTemplate, client, zone.getId()), group.getId(), client, jobComplete, virtualMachineRunning); - if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) + if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null) loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); // ingress port 22 checkSSH(HostAndPort.fromParts(vm.getIPAddress(), 22)); diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineClientLiveTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineClientLiveTest.java index cc46aa5f41..9baac2f14c 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineClientLiveTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineClientLiveTest.java @@ -284,7 +284,7 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest { } private void conditionallyCheckSSH() { - if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) + if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null) loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); assert HostSpecifier.isValid(vm.getIPAddress()); if (!InetAddresses2.isPrivateIPAddress(vm.getIPAddress())) { diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/StaticNATVirtualMachineInNetworkLiveTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/StaticNATVirtualMachineInNetworkLiveTest.java index 56af93c715..8a8315a5d7 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/StaticNATVirtualMachineInNetworkLiveTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/StaticNATVirtualMachineInNetworkLiveTest.java @@ -66,7 +66,7 @@ public class StaticNATVirtualMachineInNetworkLiveTest extends NATClientLiveTest vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network, defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete, virtualMachineRunning); - if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) + if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null) loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); } catch (NoSuchElementException e) { networksDisabled = true; diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2TemplateBuilderTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2TemplateBuilderTest.java index 2abca75a42..f632557188 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2TemplateBuilderTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2TemplateBuilderTest.java @@ -166,7 +166,7 @@ public class EC2TemplateBuilderTest { final Image image = new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true)) - .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false)) + .description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build()) .status(Image.Status.AVAILABLE) .build(); Map imageMap = ImmutableMap.of( @@ -191,12 +191,12 @@ public class EC2TemplateBuilderTest { final Supplier> images = Suppliers.> ofInstance(ImmutableSet. of( new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true)) - .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false)) + .description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build()) .status(Image.Status.AVAILABLE) .build(), new ImageBuilder().providerId("normal-image").name("image").id("us-east-1/normal-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "paravirtual", "ubuntu", true)) - .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false)) + .description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build()) .status(Image.Status.AVAILABLE) .build())); diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java index 765659fc99..42661b450e 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java @@ -67,7 +67,7 @@ public class EC2ImageParserTest { assertImageEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( "137112412989/amzn-ami-0.9.7-beta.i386-ebs").is64Bit(false).build()).description("Amazon") - .defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-82e4b5c7").name( + .defaultCredentials(LoginCredentials.builder().user("ec2-user").build()).id("us-east-1/ami-82e4b5c7").name( "amzn-ami-0.9.7-beta.i386-ebs").providerId("ami-82e4b5c7").location(defaultLocation) .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status( Status.AVAILABLE).backendStatus("available").build()); @@ -75,7 +75,7 @@ public class EC2ImageParserTest { assertImageEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( "amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml").is64Bit(true).build()) - .description("Amazon Linux AMI x86_64 S3").defaultCredentials(new LoginCredentials("ec2-user", false)) + .description("Amazon Linux AMI x86_64 S3").defaultCredentials(LoginCredentials.builder().user("ec2-user").build()) .id("us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").name("amzn-ami-0.9.7-beta.x86_64-S3").location( defaultLocation) .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status( @@ -86,7 +86,7 @@ public class EC2ImageParserTest { "amazon/NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10") .is64Bit(true).build()) .description("Microsoft Windows Server 2008 R2 SP1 Datacenter 64-bit Multi-language AMI provided by Amazon") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/ami-85457ff1").providerId("ami-85457ff1").name("NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10") .location(defaultLocation) .userMetadata(ImmutableMap.of("owner", "801119661308", "rootDeviceType", "ebs")) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index 5c272da6e0..a81bddebe0 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -237,9 +237,7 @@ public class RunningInstanceToNodeMetadataTest { } protected RunningInstance firstInstanceFromResource(String resource) { - RunningInstance server = Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest - .parseRunningInstances(resource), 0), 0); - return server; + return Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest.parseRunningInstances(resource), 0), 0); } protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, diff --git a/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java b/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java index 93aaf4d4c8..62c3de818e 100644 --- a/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java +++ b/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java @@ -71,7 +71,7 @@ public class NovaReviseParsedImageTest { .build()) .name("Ubuntu Maverick 10.10 Server 64-bit 20111212") .description("") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/ami-000004d6") .providerId("ami-000004d6") .location(defaultLocation) diff --git a/apis/vcloud/src/test/java/org/jclouds/vcloud/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java b/apis/vcloud/src/test/java/org/jclouds/vcloud/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java index 899a942ac2..f1e221c081 100644 --- a/apis/vcloud/src/test/java/org/jclouds/vcloud/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java +++ b/apis/vcloud/src/test/java/org/jclouds/vcloud/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java @@ -45,8 +45,8 @@ import com.google.inject.name.Names; // surefire @Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest") public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest { - ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = new ValueOfConfigurationKeyOrNull( - Guice.createInjector()); + ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = Guice.createInjector().getInstance( + ValueOfConfigurationKeyOrNull.class); @Test(expectedExceptions = IllegalArgumentException.class) public void testIllegalArgumentWhenResourcesEmpty() { @@ -91,16 +91,14 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); - assertEquals(new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault( - new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { - bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*"); - } - - })), "foo", Predicates. alwaysTrue()).apply(ImmutableList. of(reference1, - reference2)), reference2); + assertEquals( + new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector( + new AbstractModule() { + protected void configure() { + bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*"); + } + }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates. alwaysTrue()).apply(ImmutableList + . of(reference1, reference2)), reference2); } @@ -109,16 +107,11 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); - new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(new ValueOfConfigurationKeyOrNull( - Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { - bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*"); - } - - })), "foo", Predicates. alwaysTrue()).apply(ImmutableList. of(reference1, - reference2)); - + new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(new AbstractModule() { + protected void configure() { + bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*"); + } + }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates. alwaysTrue()) + .apply(ImmutableList. of(reference1, reference2)); } } diff --git a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java index 52fdab9353..601ad76a03 100644 --- a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java +++ b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/suppliers/OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest.java @@ -45,8 +45,8 @@ import com.google.inject.name.Names; // surefire @Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest") public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest { - ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = new ValueOfConfigurationKeyOrNull( - Guice.createInjector()); + ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = Guice.createInjector().getInstance( + ValueOfConfigurationKeyOrNull.class); @Test(expectedExceptions = IllegalArgumentException.class) public void testIllegalArgumentWhenResourcesEmpty() { @@ -91,16 +91,14 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); - assertEquals(new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault( - new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { - bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*"); - } - - })), "foo", Predicates. alwaysTrue()).apply(ImmutableList. of(reference1, - reference2)), reference2); + assertEquals( + new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector( + new AbstractModule() { + protected void configure() { + bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*"); + } + }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates. alwaysTrue()).apply(ImmutableList + . of(reference1, reference2)), reference2); } @@ -109,16 +107,11 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); - new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(new ValueOfConfigurationKeyOrNull( - Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { - bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*"); - } - - })), "foo", Predicates. alwaysTrue()).apply(ImmutableList. of(reference1, - reference2)); - + new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(new AbstractModule() { + protected void configure() { + bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*"); + } + }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates. alwaysTrue()) + .apply(ImmutableList. of(reference1, reference2)); } } diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java index 5ba1383f1a..da0c39fdf9 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java @@ -86,7 +86,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( - new LoginCredentials("tester", "testpassword!", null, false)).build(); + LoginCredentials.builder().user("tester").password("testpassword!").build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -153,7 +153,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testWithSudoPassword() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( - new LoginCredentials("tester", "testpassword!", null, true)).build(); + LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -206,7 +206,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testDoublecheckStatusInCaseTransientlyWrong() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( - new LoginCredentials("tester", "testpassword!", null, true)).build(); + LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -256,7 +256,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testNotRoot() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( - new LoginCredentials("tester", "testpassword!", null, true)).build(); + LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -302,11 +302,10 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { verify(sshClient); } - public void testBadReturnCode() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("badreturncode").status(Status.RUNNING).credentials( - new LoginCredentials("tester", "testpassword!", null, true)).build(); + LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java index 0aa383c480..c596a06581 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java @@ -57,7 +57,7 @@ public class RunScriptOnNodeUsingSshTest { } }; node = createMock(NodeMetadata.class); - expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "notalot", null, false)).atLeastOnce(); + expect(node.getCredentials()).andReturn(LoginCredentials.builder().user("tester").password("notalot").build()).atLeastOnce(); replay(node); } @@ -97,7 +97,7 @@ public class RunScriptOnNodeUsingSshTest { public void simpleRootTestWithSudoPassword() { node = createMock(NodeMetadata.class); - expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "testpassword!", null, true)) + expect(node.getCredentials()).andReturn(LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()) .atLeastOnce(); replay(node); RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"), diff --git a/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java b/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java index f5fbd518e3..482e2fd05a 100644 --- a/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java +++ b/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java @@ -48,19 +48,16 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { expect(image.getDefaultCredentials()).andReturn(null); expect(template.getOptions()).andReturn(new TemplateOptions()); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template), expected); - verify(template); - verify(image); - + verify(template, image); } - public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); + LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build(); + public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() { Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -68,19 +65,14 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { expect(image.getDefaultCredentials()).andReturn(null); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected)); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template), expected); - verify(template); - verify(image); - + verify(template, image); } public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); - Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -88,53 +80,40 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { expect(image.getDefaultCredentials()).andReturn(expected); expect(template.getOptions()).andReturn(new TemplateOptions()); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template), expected); - verify(template); - verify(image); - + verify(template, image); } public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); - Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false)); + expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("user").password("password").build()); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template), expected); - - verify(template); - verify(image); - + + verify(template, image); } public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); - Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false)); + expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password2").build()); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password")); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template), expected); - verify(template); - verify(image); - + verify(template, image); } } diff --git a/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java b/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java index f3cf1ce6f7..d3668061ca 100644 --- a/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java +++ b/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java @@ -51,18 +51,16 @@ public class PrioritizeCredentialsFromTemplateTest { expect(image.getDefaultCredentials()).andReturn(null); expect(template.getOptions()).andReturn(new TemplateOptions()); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template, null), expected); verify(template); verify(image); - } - + public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() { - LoginCredentials expected = new LoginCredentials("foo", "bar", null, false); + LoginCredentials expected = LoginCredentials.builder().user("foo").password("bar").build(); Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -71,18 +69,16 @@ public class PrioritizeCredentialsFromTemplateTest { expect(image.getDefaultCredentials()).andReturn(null); expect(template.getOptions()).andReturn(new TemplateOptions()); - replay(template); - replay(image); + replay(template, image); assertEquals(fn.apply(template, expected), expected); verify(template); verify(image); - } - + public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); + LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build(); Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -91,16 +87,14 @@ public class PrioritizeCredentialsFromTemplateTest { expect(image.getDefaultCredentials()).andReturn(null); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected)); - replay(template); - replay(image); + replay(template, image); - assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); + assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected); verify(template); verify(image); - } - + public void testWhenCredentialsNotPresentInImageReturnsCredentialFromTemplateOptionsAndUserFromParameter() { Credentials expected = new Credentials("ubuntu", "password"); @@ -111,18 +105,16 @@ public class PrioritizeCredentialsFromTemplateTest { expect(image.getDefaultCredentials()).andReturn(null); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); - replay(template); - replay(image); + replay(template, image); - assertEquals(fn.apply(template, new LoginCredentials("foo", "password", null, false)), expected); + assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("password").build()), expected); verify(template); verify(image); - } - + public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); + LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build(); Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -131,16 +123,14 @@ public class PrioritizeCredentialsFromTemplateTest { expect(image.getDefaultCredentials()).andReturn(expected); expect(template.getOptions()).andReturn(new TemplateOptions()); - replay(template); - replay(image); + replay(template, image); - assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); + assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected); verify(template); verify(image); - } - + public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptionsAndNotParameter() { Credentials expected = new Credentials("ubuntu", "password"); @@ -148,36 +138,31 @@ public class PrioritizeCredentialsFromTemplateTest { Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false)); + expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password").build()); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); - replay(template); - replay(image); + replay(template, image); - assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); - - verify(template); - verify(image); + assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected); + verify(template, image); } - + public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() { - LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); + LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build(); Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false)); + expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password2").build()); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password")); - replay(template); - replay(image); + replay(template, image); - assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); + assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected); verify(template); verify(image); - } } diff --git a/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java b/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java index 12302fda60..1d5bb586bd 100644 --- a/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java +++ b/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java @@ -39,12 +39,12 @@ import com.google.common.collect.ImmutableMap; */ @Test(groups = "unit", testName = "ReturnCredentialsBoundToImageTest") public class ReturnCredentialsBoundToImageTest { + LoginCredentials creds = LoginCredentials.builder().user("ubuntu").password("foo").build(); public void testDefaultIsToReturnConfiguredCredential() { Image image = createMock(Image.class); replay(image); - LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false); assertEquals(new ReturnCredentialsBoundToImage(creds, ImmutableMap. of(), ImmutableMap . of()).apply(image), creds); @@ -57,7 +57,6 @@ public class ReturnCredentialsBoundToImageTest { expect(image.getId()).andReturn("1").times(2); replay(image); - LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false); assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap. of("image#1", creds), ImmutableMap. of()).apply(image), creds); diff --git a/core/src/main/java/org/jclouds/Fallbacks.java b/core/src/main/java/org/jclouds/Fallbacks.java index 7947a6e8b3..916387564b 100644 --- a/core/src/main/java/org/jclouds/Fallbacks.java +++ b/core/src/main/java/org/jclouds/Fallbacks.java @@ -124,7 +124,7 @@ public final class Fallbacks { } } - public static final class EmptyListOnNotFoundOr404 implements FutureFallback> { + public static final class EmptyListOnNotFoundOr404 implements FutureFallback> { // NO_UCD (unused code) @Override public ListenableFuture> create(Throwable t) { return valOnNotFoundOr404(ImmutableList.of(), checkNotNull(t, "throwable")); @@ -145,7 +145,7 @@ public final class Fallbacks { } } - public static final class EmptyMultimapOnNotFoundOr404 implements FutureFallback> { + public static final class EmptyMultimapOnNotFoundOr404 implements FutureFallback> { // NO_UCD (unused code) @Override public ListenableFuture> create(Throwable t) { return valOnNotFoundOr404(ImmutableMultimap.of(), checkNotNull(t, "throwable")); diff --git a/core/src/main/java/org/jclouds/View.java b/core/src/main/java/org/jclouds/View.java index 9ac7e86f19..42ac909c09 100644 --- a/core/src/main/java/org/jclouds/View.java +++ b/core/src/main/java/org/jclouds/View.java @@ -48,7 +48,7 @@ public interface View { * * ex. *
-    * RestContext backendApi = computeContext.unwrap(NovaApiMetadata.CONTEXT_TOKEN);
+    * RestContext backendApi = computeContext.unwrap(NovaApiMetadata.CONTEXT_TOKEN);
     * 
* @param type * the type of the context to be returned. The backend context must @@ -61,13 +61,6 @@ public interface View { */ C unwrap(TypeToken type) throws IllegalArgumentException; - /** - * shortcut for {@code unwrap(TypeToken.of(clazz))} - * - * @see #unwrap(TypeToken) - */ - C unwrap(Class clazz) throws IllegalArgumentException; - /** * shortcut for {@code unwrap(getWrappedType())} * diff --git a/core/src/main/java/org/jclouds/apis/Apis.java b/core/src/main/java/org/jclouds/apis/Apis.java index 08eb3be905..5cfbf9b32e 100644 --- a/core/src/main/java/org/jclouds/apis/Apis.java +++ b/core/src/main/java/org/jclouds/apis/Apis.java @@ -41,7 +41,7 @@ import com.google.common.reflect.TypeToken; */ public class Apis { - public static enum IdFunction implements Function { + private static enum IdFunction implements Function { INSTANCE; @Override diff --git a/core/src/main/java/org/jclouds/apis/internal/BaseApiMetadata.java b/core/src/main/java/org/jclouds/apis/internal/BaseApiMetadata.java index e0b4017678..38c314a3e5 100644 --- a/core/src/main/java/org/jclouds/apis/internal/BaseApiMetadata.java +++ b/core/src/main/java/org/jclouds/apis/internal/BaseApiMetadata.java @@ -79,22 +79,21 @@ public abstract class BaseApiMetadata implements ApiMetadata { public static abstract class Builder> implements ApiMetadata.Builder { protected abstract T self(); - protected String id; - protected String name; - protected Set> views = ImmutableSet.of(); - protected String endpointName = "https endpoint"; - protected String identityName; - protected Optional credentialName = Optional.absent(); - protected String version = ""; - protected Optional buildVersion = Optional.of(""); - protected Optional defaultEndpoint = Optional.absent(); - protected Optional defaultIdentity = Optional.absent(); - protected Optional defaultCredential = Optional.absent(); - protected Properties defaultProperties = BaseApiMetadata.defaultProperties(); - protected URI documentation; - // - protected TypeToken context = TypeToken.of(Context.class); - protected Set> defaultModules = ImmutableSet.of(); + private String id; + private String name; + private Set> views = ImmutableSet.of(); + private String endpointName = "https endpoint"; + private String identityName; + private Optional credentialName = Optional.absent(); + private String version = ""; + private Optional buildVersion = Optional.of(""); + private Optional defaultEndpoint = Optional.absent(); + private Optional defaultIdentity = Optional.absent(); + private Optional defaultCredential = Optional.absent(); + private Properties defaultProperties = BaseApiMetadata.defaultProperties(); + private URI documentation; + private TypeToken context = TypeToken.of(Context.class); + private Set> defaultModules = ImmutableSet.of(); /** * {@inheritDoc} @@ -265,21 +264,21 @@ public abstract class BaseApiMetadata implements ApiMetadata { } } - protected final String id; - protected final String name; - protected final Set> views; - protected final String endpointName; - protected final String identityName; - protected final Optional credentialName; - protected final String version; - protected final Optional buildVersion; - protected final Optional defaultEndpoint; - protected final Optional defaultIdentity; - protected final Optional defaultCredential; - protected final Properties defaultProperties; - protected final URI documentation; - protected final TypeToken context; - protected final Set> defaultModules; + private final String id; + private final String name; + private final Set> views; + private final String endpointName; + private final String identityName; + private final Optional credentialName; + private final String version; + private final Optional buildVersion; + private final Optional defaultEndpoint; + private final Optional defaultIdentity; + private final Optional defaultCredential; + private final Properties defaultProperties; + private final URI documentation; + private final TypeToken context; + private final Set> defaultModules; protected BaseApiMetadata(Builder builder) { this(builder.id, builder.name, builder.views, builder.endpointName, builder.identityName, builder.credentialName, @@ -288,7 +287,7 @@ public abstract class BaseApiMetadata implements ApiMetadata { builder.defaultModules); } - public BaseApiMetadata(String id, String name, Set> views, String endpointName, String identityName, + protected BaseApiMetadata(String id, String name, Set> views, String endpointName, String identityName, // NO_UCD (use private) Optional credentialName, String version, Optional buildVersion, Optional defaultEndpoint, Optional defaultIdentity, Optional defaultCredential, Properties defaultProperties, URI documentation, TypeToken context, diff --git a/core/src/main/java/org/jclouds/cache/ForwardingCacheLoader.java b/core/src/main/java/org/jclouds/cache/ForwardingCacheLoader.java index e0998c1f84..5686421399 100644 --- a/core/src/main/java/org/jclouds/cache/ForwardingCacheLoader.java +++ b/core/src/main/java/org/jclouds/cache/ForwardingCacheLoader.java @@ -21,7 +21,6 @@ package org.jclouds.cache; import java.util.Map; import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; import com.google.common.cache.CacheLoader; import com.google.common.util.concurrent.ListenableFuture; @@ -56,24 +55,4 @@ public abstract class ForwardingCacheLoader extends CacheLoader { public Map loadAll(Iterable keys) throws Exception { return delegate().loadAll(keys); } - - /** - * A simplified version of {@link ForwardingCacheLoader} where subclasses can pass in an already - * constructed {@link CacheLoader} as the delegate. - * - */ - @Beta - public static class SimpleForwardingCacheLoader extends ForwardingCacheLoader { - private final CacheLoader delegate; - - protected SimpleForwardingCacheLoader(CacheLoader delegate) { - this.delegate = Preconditions.checkNotNull(delegate); - } - - @Override - protected final CacheLoader delegate() { - return delegate; - } - - } } diff --git a/core/src/main/java/org/jclouds/cache/RetryingCacheLoaderDecorator.java b/core/src/main/java/org/jclouds/cache/RetryingCacheLoaderDecorator.java index e120d7f802..bd1a90ab41 100644 --- a/core/src/main/java/org/jclouds/cache/RetryingCacheLoaderDecorator.java +++ b/core/src/main/java/org/jclouds/cache/RetryingCacheLoaderDecorator.java @@ -85,9 +85,9 @@ public class RetryingCacheLoaderDecorator { } public static class OnThrowableBuilder { - Class retryableThrowable; + private Class retryableThrowable; - protected OnThrowableBuilder(Class retryableThrowable) { + private OnThrowableBuilder(Class retryableThrowable) { this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable"); } @@ -107,7 +107,7 @@ public class RetryingCacheLoaderDecorator { private int maxTries = 5; private final Class retryableThrowable; - protected BackoffExponentiallyAndRetryOnThrowableCacheLoaderDecorator(Class retryableThrowable) { + private BackoffExponentiallyAndRetryOnThrowableCacheLoaderDecorator(Class retryableThrowable) { this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable"); } diff --git a/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallable.java b/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallable.java index 0e27814a5a..277dcbd5fc 100644 --- a/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallable.java +++ b/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallable.java @@ -81,7 +81,7 @@ class BackoffExponentiallyAndRetryOnThrowableCallable extends ForwardingObjec throw currentException; } - void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max) { + private void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max) { long delayMs = (long) (period * Math.pow(failureCount, pow)); delayMs = delayMs > maxPeriod ? maxPeriod : delayMs; try { diff --git a/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java b/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java index 78b2fedcbf..81850ecaf6 100644 --- a/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java +++ b/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java @@ -25,13 +25,10 @@ import org.jclouds.javax.annotation.Nullable; import com.google.common.base.Objects; -public abstract class AbstractMapEntry implements Entry { +abstract class AbstractMapEntry implements Entry { - public abstract K getKey(); - - public abstract V getValue(); - - public V setValue(V value) { + @Override + public V setValue(V value) { // NO_UCD throw new UnsupportedOperationException(); } @@ -51,9 +48,6 @@ public abstract class AbstractMapEntry implements Entry { return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } - /** - * Returns a string representation of the form {key}={value}. - */ @Override public String toString() { return getKey() + "=" + getValue(); diff --git a/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java b/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java index bb630327d4..44017b851a 100644 --- a/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java +++ b/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java @@ -53,13 +53,13 @@ public class AdvanceUntilEmptyIterable extends FluentIterable extends AbstractIterator> { + private static class AdvanceUntilEmptyIterator extends AbstractIterator> { private final Supplier> nextIterable; private transient FluentIterable current; private transient boolean unread = true; - AdvanceUntilEmptyIterator(Supplier> nextIterable) { + private AdvanceUntilEmptyIterator(Supplier> nextIterable) { this.nextIterable = checkNotNull(nextIterable, "next iterable"); } diff --git a/core/src/main/java/org/jclouds/collect/ForwardingIterableWithMarker.java b/core/src/main/java/org/jclouds/collect/ForwardingIterableWithMarker.java deleted file mode 100644 index 9c74532196..0000000000 --- a/core/src/main/java/org/jclouds/collect/ForwardingIterableWithMarker.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.collect; - -import java.util.Iterator; - -import com.google.common.annotations.Beta; -import com.google.common.base.Optional; - -/** - * An iterator which forwards all its method calls to another iterator. Subclasses should override - * one or more methods to modify the behavior of the backing iterable as desired per the decorator pattern. - * - * @author Adrian Cole - */ -@Beta -public abstract class ForwardingIterableWithMarker extends IterableWithMarker { - - /** Constructor for use by subclasses. */ - protected ForwardingIterableWithMarker() { - } - - protected abstract IterableWithMarker delegate(); - - @Override - public Iterator iterator() { - return delegate().iterator(); - } - - @Override - public Optional nextMarker() { - return delegate().nextMarker(); - } - -} diff --git a/core/src/main/java/org/jclouds/collect/InputSupplierMap.java b/core/src/main/java/org/jclouds/collect/InputSupplierMap.java index f1c8767adb..f7344d4125 100644 --- a/core/src/main/java/org/jclouds/collect/InputSupplierMap.java +++ b/core/src/main/java/org/jclouds/collect/InputSupplierMap.java @@ -39,8 +39,8 @@ import com.google.common.io.InputSupplier; * */ public class InputSupplierMap extends AbstractMap { - final Map> toMap; - final Function> putFunction; + private final Map> toMap; + private final Function> putFunction; public InputSupplierMap(Map> toMap, Function> putFunction) { this.toMap = checkNotNull(toMap); @@ -91,10 +91,9 @@ public class InputSupplierMap extends AbstractMap { @Override public Set> entrySet() { return new EntrySet(); - } - class EntrySet extends AbstractSet> { + private class EntrySet extends AbstractSet> { @Override public int size() { return InputSupplierMap.this.size(); diff --git a/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java b/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java index 9c7c460b06..9b8eabf8b8 100644 --- a/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java +++ b/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java @@ -86,7 +86,20 @@ public class IterableWithMarkers { public Optional nextMarker() { return marker; } - } + private static abstract class ForwardingIterableWithMarker extends IterableWithMarker { + + protected abstract IterableWithMarker delegate(); + + @Override + public Iterator iterator() { + return delegate().iterator(); + } + + @Override + public Optional nextMarker() { + return delegate().nextMarker(); + } + } } diff --git a/core/src/main/java/org/jclouds/collect/PagedIterables.java b/core/src/main/java/org/jclouds/collect/PagedIterables.java index 2d58b8aeb3..4fbae7dbbf 100644 --- a/core/src/main/java/org/jclouds/collect/PagedIterables.java +++ b/core/src/main/java/org/jclouds/collect/PagedIterables.java @@ -35,17 +35,7 @@ import com.google.common.collect.ImmutableSet; */ @Beta public class PagedIterables { - - @SuppressWarnings("rawtypes") - public static final PagedIterable EMPTY = new PagedIterable() { - @Override - public Iterator iterator() { - return ImmutableSet.of(IterableWithMarkers.EMPTY).iterator(); - } - - }; - /** * @param only * the only page of data @@ -154,7 +144,7 @@ public class PagedIterables { * @return iterable current data which continues if the user iterates beyond * the first page */ - public static Iterator> advancingIterator(IterableWithMarker initial, + private static Iterator> advancingIterator(IterableWithMarker initial, Function> markerToNext) { if (!initial.nextMarker().isPresent()) { return ImmutableSet.of(initial).iterator(); diff --git a/core/src/main/java/org/jclouds/collect/TransformingMap.java b/core/src/main/java/org/jclouds/collect/TransformingMap.java index 88886e2f29..4c714b98b3 100644 --- a/core/src/main/java/org/jclouds/collect/TransformingMap.java +++ b/core/src/main/java/org/jclouds/collect/TransformingMap.java @@ -36,9 +36,9 @@ import com.google.common.base.Function; * */ public class TransformingMap extends AbstractMap { - final Map fromMap; - final Function getFunction; - final Function putFunction; + private final Map fromMap; + private final Function getFunction; + private final Function putFunction; public TransformingMap(Map fromMap, Function getFunction, Function putFunction) { this.fromMap = checkNotNull(fromMap); @@ -85,7 +85,7 @@ public class TransformingMap extends AbstractMap { } - class EntrySet extends AbstractSet> { + private class EntrySet extends AbstractSet> { @Override public int size() { return TransformingMap.this.size(); diff --git a/core/src/main/java/org/jclouds/concurrent/DynamicExecutors.java b/core/src/main/java/org/jclouds/concurrent/DynamicExecutors.java index dee1653667..d81d8a38f7 100644 --- a/core/src/main/java/org/jclouds/concurrent/DynamicExecutors.java +++ b/core/src/main/java/org/jclouds/concurrent/DynamicExecutors.java @@ -19,7 +19,6 @@ package org.jclouds.concurrent; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -30,45 +29,23 @@ import java.util.concurrent.TimeUnit; * @author kimchy (shay.banon) */ public class DynamicExecutors { - /** - * Creates a thread pool that creates new threads as needed, but will reuse previously - * constructed threads when they are available. Calls to execute will reuse previously - * constructed threads if available. If no existing thread is available, a new thread will be - * created and added to the pool. No more than max threads will be created. Threads that - * have not been used for a keepAlive timeout are terminated and removed from the cache. - * Thus, a pool that remains idle for long enough will not consume any resources other than the - * min specified. - * - * @param min - * the number of threads to keep in the pool, even if they are idle. - * @param max - * the maximum number of threads to allow in the pool. - * @param keepAliveTime - * when the number of threads is greater than the min, this is the maximum time that - * excess idle threads will wait for new tasks before terminating (in milliseconds). - * @return the newly created thread pool - */ - public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime) { - return newScalingThreadPool(min, max, keepAliveTime, Executors.defaultThreadFactory()); - } /** - * Creates a thread pool, same as in {@link #newScalingThreadPool(int, int, long)}, using the - * provided ThreadFactory to create new threads when needed. + * Creates a thread pool, same as in {@link #newScalingThreadPool(int, int, long)}, using the provided ThreadFactory + * to create new threads when needed. * * @param min * the number of threads to keep in the pool, even if they are idle. * @param max * the maximum number of threads to allow in the pool. * @param keepAliveTime - * when the number of threads is greater than the min, this is the maximum time that - * excess idle threads will wait for new tasks before terminating (in milliseconds). + * when the number of threads is greater than the min, this is the maximum time that excess idle threads + * will wait for new tasks before terminating (in milliseconds). * @param threadFactory * the factory to use when creating new threads. * @return the newly created thread pool */ - public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime, - ThreadFactory threadFactory) { + public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime, ThreadFactory threadFactory) { DynamicThreadPoolExecutor.DynamicQueue queue = new DynamicThreadPoolExecutor.DynamicQueue(); ThreadPoolExecutor executor = new DynamicThreadPoolExecutor(min, max, keepAliveTime, TimeUnit.MILLISECONDS, queue, threadFactory); @@ -77,128 +54,6 @@ public class DynamicExecutors { return executor; } - /** - * Creates a thread pool similar to that constructed by - * {@link #newScalingThreadPool(int, int, long)}, but blocks the call to execute if the - * queue has reached it's capacity, and all max threads are busy handling requests. - *

- * If the wait time of this queue has elapsed, a {@link RejectedExecutionException} will be - * thrown. - * - * @param min - * the number of threads to keep in the pool, even if they are idle. - * @param max - * the maximum number of threads to allow in the pool. - * @param keepAliveTime - * when the number of threads is greater than the min, this is the maximum time that - * excess idle threads will wait for new tasks before terminating (in milliseconds). - * @param capacity - * the fixed capacity of the underlying queue (resembles backlog). - * @param waitTime - * the wait time (in milliseconds) for space to become available in the queue. - * @return the newly created thread pool - */ - public static ExecutorService newBlockingThreadPool(int min, int max, long keepAliveTime, - int capacity, long waitTime) { - return newBlockingThreadPool(min, max, keepAliveTime, capacity, waitTime, Executors - .defaultThreadFactory()); - } - - /** - * Creates a thread pool, same as in {@link #newBlockingThreadPool(int, int, long, int, long)}, - * using the provided ThreadFactory to create new threads when needed. - * - * @param min - * the number of threads to keep in the pool, even if they are idle. - * @param max - * the maximum number of threads to allow in the pool. - * @param keepAliveTime - * when the number of threads is greater than the min, this is the maximum time that - * excess idle threads will wait for new tasks before terminating (in milliseconds). - * @param capacity - * the fixed capacity of the underlying queue (resembles backlog). - * @param waitTime - * the wait time (in milliseconds) for space to become available in the queue. - * @param threadFactory - * the factory to use when creating new threads. - * @return the newly created thread pool - */ - public static ExecutorService newBlockingThreadPool(int min, int max, long keepAliveTime, - int capacity, long waitTime, ThreadFactory threadFactory) { - DynamicThreadPoolExecutor.DynamicQueue queue = new DynamicThreadPoolExecutor.DynamicQueue( - capacity); - ThreadPoolExecutor executor = new DynamicThreadPoolExecutor(min, max, keepAliveTime, - TimeUnit.MILLISECONDS, queue, threadFactory); - executor.setRejectedExecutionHandler(new DynamicThreadPoolExecutor.TimedBlockingPolicy( - waitTime)); - queue.setThreadPoolExecutor(executor); - return executor; - } - - /** - * A priority based thread factory, for all Thread priority constants: - * Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY; - *

- * This factory is used instead of Executors.DefaultThreadFactory to allow manipulation of - * priority and thread owner name. - * - * @param namePrefix - * a name prefix for this thread - * @return a thread factory based on given priority. - */ - public static ThreadFactory daemonThreadFactory(String namePrefix) { - final ThreadFactory f = Executors.defaultThreadFactory(); - final String o = namePrefix + "-"; - - return new ThreadFactory() { - public Thread newThread(Runnable r) { - Thread t = f.newThread(r); - - /* - * Thread name: owner-pool-N-thread-M, where N is the sequence number of this factory, - * and ApiMetadata is the sequence number of the thread created by this factory. - */ - t.setName(o + t.getName()); - - /* override default definition t.setDaemon(false); */ - t.setDaemon(true); - - return t; - } - }; - } - - /** - * A priority based thread factory, for all Thread priority constants: - * Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY; - *

- * This factory is used instead of Executors.DefaultThreadFactory to allow manipulation of - * priority and thread owner name. - * - * @param priority - * The priority to be assigned to each thread; can be either - * Thread.MIN_PRIORITY, Thread.NORM_PRIORITY or Thread.MAX_PRIORITY. - * @param namePrefix - * a name prefix for this thread - * @return a thread factory based on given priority. - */ - public static ThreadFactory priorityThreadFactory(int priority, String namePrefix) { - final ThreadFactory f = DynamicExecutors.daemonThreadFactory(namePrefix); - final int p = priority; - - return new ThreadFactory() { - public Thread newThread(Runnable r) { - Thread t = f.newThread(r); - - /* override default thread priority of Thread.NORM_PRIORITY */ - if (p != Thread.NORM_PRIORITY) - t.setPriority(p); - - return t; - } - }; - } - /** * Cannot instantiate. */ diff --git a/core/src/main/java/org/jclouds/concurrent/DynamicThreadPoolExecutor.java b/core/src/main/java/org/jclouds/concurrent/DynamicThreadPoolExecutor.java index a2bc16e4ec..ad91763611 100644 --- a/core/src/main/java/org/jclouds/concurrent/DynamicThreadPoolExecutor.java +++ b/core/src/main/java/org/jclouds/concurrent/DynamicThreadPoolExecutor.java @@ -17,23 +17,23 @@ * under the License. */ /* -* Licensed to Elastic Search and Shay Banon under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. Elastic Search licenses this -* file to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ + * Licensed to Elastic Search and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Elastic Search licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.jclouds.concurrent; @@ -47,140 +47,138 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** -* An {@link ExecutorService} that executes each submitted task using one of -* possibly several pooled threads, normally configured using -* {@link DynamicExecutors} factory methods. -* -* @author kimchy (shay.banon) -*/ -public class DynamicThreadPoolExecutor extends ThreadPoolExecutor { - /** -* number of threads that are actively executing tasks -*/ - private final AtomicInteger activeCount = new AtomicInteger(); + * An {@link ExecutorService} that executes each submitted task using one of possibly several pooled threads, normally + * configured using {@link DynamicExecutors} factory methods. + * + * @author kimchy (shay.banon) + */ +class DynamicThreadPoolExecutor extends ThreadPoolExecutor { + /** + * number of threads that are actively executing tasks + */ + private final AtomicInteger activeCount = new AtomicInteger(); - public DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, - long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, - ThreadFactory threadFactory) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); - } + DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, + BlockingQueue workQueue, ThreadFactory threadFactory) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); + } - @Override public int getActiveCount() { - return activeCount.get(); - } + @Override + public int getActiveCount() { + return activeCount.get(); + } - @Override protected void beforeExecute(Thread t, Runnable r) { - activeCount.incrementAndGet(); - } + @Override + protected void beforeExecute(Thread t, Runnable r) { + activeCount.incrementAndGet(); + } - @Override protected void afterExecute(Runnable r, Throwable t) { - activeCount.decrementAndGet(); - } + @Override + protected void afterExecute(Runnable r, Throwable t) { + activeCount.decrementAndGet(); + } - /** -* Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It -* is well suited for handoff designs, in which a tasks is only queued if there -* is an available thread to pick it up. -*

-* This queue is correlated with a thread-pool, and allows insertions to the -* queue only if there is a free thread that can poll this task. Otherwise, the -* task is rejected and the decision is left up to one of the -* {@link RejectedExecutionHandler} policies: -*

    -*
  1. {@link ForceQueuePolicy} - forces the queue to accept the rejected task.
  2. -*
  3. {@link TimedBlockingPolicy} - waits for a given time for the task to be -* executed.
  4. -*
-* -* @author kimchy (Shay Banon) -*/ - public static class DynamicQueue extends LinkedBlockingQueue { + /** + * Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It is well suited for handoff designs, in + * which a tasks is only queued if there is an available thread to pick it up. + *

+ * This queue is correlated with a thread-pool, and allows insertions to the queue only if there is a free thread + * that can poll this task. Otherwise, the task is rejected and the decision is left up to one of the + * {@link RejectedExecutionHandler} policies: + *

    + *
  1. {@link ForceQueuePolicy} - forces the queue to accept the rejected task.
  2. + *
  3. {@link TimedBlockingPolicy} - waits for a given time for the task to be executed.
  4. + *
+ * + * @author kimchy (Shay Banon) + */ + static class DynamicQueue extends LinkedBlockingQueue { + private static final long serialVersionUID = 1L; - /** -* The executor this Queue belongs to -*/ - private transient ThreadPoolExecutor executor; + /** + * The executor this Queue belongs to + */ + private transient ThreadPoolExecutor executor; - /** -* Creates a DynamicQueue with a capacity of -* {@link Integer#MAX_VALUE}. -*/ - public DynamicQueue() { - super(); - } + /** + * Creates a DynamicQueue with a capacity of {@link Integer#MAX_VALUE}. + */ + public DynamicQueue() { + super(); + } - /** -* Creates a DynamicQueue with the given (fixed) capacity. -* -* @param capacity the capacity of this queue. -*/ - public DynamicQueue(int capacity) { - super(capacity); - } + /** + * Creates a DynamicQueue with the given (fixed) capacity. + * + * @param capacity + * the capacity of this queue. + */ + DynamicQueue(int capacity) { + super(capacity); + } - /** -* Sets the executor this queue belongs to. -*/ - public void setThreadPoolExecutor(ThreadPoolExecutor executor) { - this.executor = executor; - } + /** + * Sets the executor this queue belongs to. + */ + public void setThreadPoolExecutor(ThreadPoolExecutor executor) { + this.executor = executor; + } - /** -* Inserts the specified element at the tail of this queue if there is at -* least one available thread to run the current task. If all pool threads -* are actively busy, it rejects the offer. -* -* @param o the element to add. -* @return true if it was possible to add the element to this -* queue, else false -* @see ThreadPoolExecutor#execute(Runnable) -*/ - @Override - public boolean offer(E o) { - int allWorkingThreads = executor.getActiveCount() + super.size(); - return allWorkingThreads < executor.getPoolSize() && super.offer(o); - } - } + /** + * Inserts the specified element at the tail of this queue if there is at least one available thread to run the + * current task. If all pool threads are actively busy, it rejects the offer. + * + * @param o + * the element to add. + * @return true if it was possible to add the element to this queue, else false + * @see ThreadPoolExecutor#execute(Runnable) + */ + @Override + public boolean offer(E o) { + int allWorkingThreads = executor.getActiveCount() + super.size(); + return allWorkingThreads < executor.getPoolSize() && super.offer(o); + } + } - /** -* A handler for rejected tasks that adds the specified element to this queue, -* waiting if necessary for space to become available. -*/ - public static class ForceQueuePolicy implements RejectedExecutionHandler { - public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { - try { - executor.getQueue().put(r); - } catch (InterruptedException e) { - //should never happen since we never wait - throw new RejectedExecutionException(e); - } - } - } + /** + * A handler for rejected tasks that adds the specified element to this queue, waiting if necessary for space to + * become available. + */ + static class ForceQueuePolicy implements RejectedExecutionHandler { + public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { + try { + executor.getQueue().put(r); + } catch (InterruptedException e) { + // should never happen since we never wait + throw new RejectedExecutionException(e); + } + } + } - /** -* A handler for rejected tasks that inserts the specified element into this -* queue, waiting if necessary up to the specified wait time for space to become -* available. -*/ - public static class TimedBlockingPolicy implements RejectedExecutionHandler { - private final long waitTime; + /** + * A handler for rejected tasks that inserts the specified element into this queue, waiting if necessary up to the + * specified wait time for space to become available. + */ + static class TimedBlockingPolicy implements RejectedExecutionHandler { + private final long waitTime; - /** -* @param waitTime wait time in milliseconds for space to become available. -*/ - public TimedBlockingPolicy(long waitTime) { - this.waitTime = waitTime; - } + /** + * @param waitTime + * wait time in milliseconds for space to become available. + */ + TimedBlockingPolicy(long waitTime) { + this.waitTime = waitTime; + } - public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { - try { - boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS); - if (!successful) - throw new RejectedExecutionException("Rejected execution after waiting " - + waitTime + " ms for task [" + r.getClass() + "] to be executed."); - } catch (InterruptedException e) { - throw new RejectedExecutionException(e); - } - } - } + public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { + try { + boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS); + if (!successful) + throw new RejectedExecutionException("Rejected execution after waiting " + waitTime + " ms for task [" + + r.getClass() + "] to be executed."); + } catch (InterruptedException e) { + throw new RejectedExecutionException(e); + } + } + } } diff --git a/core/src/main/java/org/jclouds/concurrent/FutureIterables.java b/core/src/main/java/org/jclouds/concurrent/FutureIterables.java index e30052695f..7ae67d415c 100644 --- a/core/src/main/java/org/jclouds/concurrent/FutureIterables.java +++ b/core/src/main/java/org/jclouds/concurrent/FutureIterables.java @@ -56,8 +56,6 @@ import com.google.inject.Inject; */ @Beta public class FutureIterables { - @Resource - private static Logger logger = Logger.CONSOLE; @Inject(optional = true) @Named(Constants.PROPERTY_MAX_RETRIES) @@ -69,17 +67,7 @@ public class FutureIterables { @Inject(optional = true) private static BackoffLimitedRetryHandler retryHandler = BackoffLimitedRetryHandler.INSTANCE; - - public static Iterable transformParallel(final Iterable fromIterable, - final Function> function) { - return transformParallel(fromIterable, function, org.jclouds.concurrent.MoreExecutors.sameThreadExecutor(), null); - } - - public static Iterable transformParallel(final Iterable fromIterable, - final Function> function, ExecutorService exec, @Nullable Long maxTime) { - return transformParallel(fromIterable, function, exec, maxTime, logger, "transforming"); - } - + public static Iterable transformParallel(final Iterable fromIterable, final Function> function, ExecutorService exec, @Nullable Long maxTime, Logger logger, String logPrefix) { @@ -113,8 +101,8 @@ public class FutureIterables { } //make sure we propagate any authorization exception so that we don't lock out accounts if (exceptions.size() > 0) - return propagateAuthorizationOrOriginalException(new TransformParallelException((Map) responses, exceptions, - logPrefix)); + return propagateAuthorizationOrOriginalException(new TransformParallelException(Map.class.cast(responses), + exceptions, logPrefix)); return unwrap(responses.values()); } @@ -180,7 +168,7 @@ public class FutureIterables { return errorMap; } - public static Iterable unwrap(Iterable> values) { + private static Iterable unwrap(Iterable> values) { return transform(values, new Function, T>() { @Override public T apply(Future from) { @@ -211,9 +199,4 @@ public class FutureIterables { return String.format("%s, completed: %d/%d, errors: %d, rate: %dms/op", prefix, complete, size, errors, (long) ((System.currentTimeMillis() - start) / ((double) size))); } - - protected static boolean timeOut(long start, Long maxTime) { - return maxTime != null ? System.currentTimeMillis() < start + maxTime : false; - } - } diff --git a/core/src/main/java/org/jclouds/concurrent/Futures.java b/core/src/main/java/org/jclouds/concurrent/Futures.java index 2d85ec6af7..8f9ad14166 100644 --- a/core/src/main/java/org/jclouds/concurrent/Futures.java +++ b/core/src/main/java/org/jclouds/concurrent/Futures.java @@ -48,7 +48,7 @@ public class Futures { private final Future delegate; private final ExecutionList executionList; - public CallGetAndRunExecutionList(Future delegate, ExecutionList executionList) { + CallGetAndRunExecutionList(Future delegate, ExecutionList executionList) { this.delegate = checkNotNull(delegate, "delegate"); this.executionList = checkNotNull(executionList, "executionList"); } @@ -84,9 +84,9 @@ public class Futures { // note that this is done so that we can operate in Google AppEngine which // restricts thread creation // * to allow us to print debug info about what the delegate was doing - public static class FutureListener { + private static class FutureListener { - final ExecutorService adapterExecutor; + private final ExecutorService adapterExecutor; // The execution list to hold our listeners. private final ExecutionList executionList = new ExecutionList(); @@ -98,7 +98,7 @@ public class Futures { // The delegate future. private final Future delegate; - static FutureListener create(Future delegate, ExecutorService adapterExecutor) { + private static FutureListener create(Future delegate, ExecutorService adapterExecutor) { return new FutureListener(delegate, adapterExecutor); } @@ -107,7 +107,7 @@ public class Futures { this.adapterExecutor = checkNotNull(adapterExecutor, "adapterExecutor"); } - public void addListener(Runnable listener, Executor exec) { + private void addListener(Runnable listener, Executor exec) { executionList.add(listener, exec); // When a listener is first added, we run a task that will wait for @@ -123,19 +123,15 @@ public class Futures { } } - Future getFuture() { + private Future getFuture() { return delegate; } - - ExecutorService getExecutor() { - return adapterExecutor; - } } - public static class ListenableFutureAdapter extends ForwardingFuture implements ListenableFuture { - final FutureListener futureListener; + private static class ListenableFutureAdapter extends ForwardingFuture implements ListenableFuture { + private final FutureListener futureListener; - static ListenableFutureAdapter create(Future future, ExecutorService executor) { + private static ListenableFutureAdapter create(Future future, ExecutorService executor) { return new ListenableFutureAdapter(future, executor); } @@ -152,20 +148,19 @@ public class Futures { public void addListener(Runnable listener, Executor exec) { futureListener.addListener(listener, exec); } - } - public static class LazyListenableFutureFunctionAdapter extends ForwardingObject implements + private static class LazyListenableFutureFunctionAdapter extends ForwardingObject implements ListenableFuture { private final FutureListener futureListener; private final Function function; - static LazyListenableFutureFunctionAdapter create(Future future, + private static LazyListenableFutureFunctionAdapter create(Future future, Function function, ExecutorService executor) { return new LazyListenableFutureFunctionAdapter(future, function, executor); } - static LazyListenableFutureFunctionAdapter create(FutureListener futureListener, + private static LazyListenableFutureFunctionAdapter create(FutureListener futureListener, Function function) { return new LazyListenableFutureFunctionAdapter(futureListener, function); } diff --git a/core/src/main/java/org/jclouds/concurrent/TransformParallelException.java b/core/src/main/java/org/jclouds/concurrent/TransformParallelException.java index f7b902e668..fa59a52a90 100644 --- a/core/src/main/java/org/jclouds/concurrent/TransformParallelException.java +++ b/core/src/main/java/org/jclouds/concurrent/TransformParallelException.java @@ -29,6 +29,7 @@ import com.google.common.collect.Iterables; * * @author Adrian Cole */ +@SuppressWarnings("serial") public final class TransformParallelException extends RuntimeException { private final Map> success; diff --git a/core/src/main/java/org/jclouds/concurrent/config/DescribedFuture.java b/core/src/main/java/org/jclouds/concurrent/config/DescribedFuture.java index 079aebc8be..b7454b33f7 100644 --- a/core/src/main/java/org/jclouds/concurrent/config/DescribedFuture.java +++ b/core/src/main/java/org/jclouds/concurrent/config/DescribedFuture.java @@ -23,12 +23,12 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -public class DescribedFuture implements Future { +class DescribedFuture implements Future { protected final Future delegate; private final String description; private StackTraceElement[] submissionTrace; - public DescribedFuture(Future delegate, String description, StackTraceElement[] submissionTrace) { + DescribedFuture(Future delegate, String description, StackTraceElement[] submissionTrace) { this.delegate = delegate; this.description = description; this.submissionTrace = submissionTrace; diff --git a/core/src/main/java/org/jclouds/concurrent/config/DescribingExecutorService.java b/core/src/main/java/org/jclouds/concurrent/config/DescribingExecutorService.java index 26748dbb7c..ccdcab4bd1 100644 --- a/core/src/main/java/org/jclouds/concurrent/config/DescribingExecutorService.java +++ b/core/src/main/java/org/jclouds/concurrent/config/DescribingExecutorService.java @@ -19,6 +19,7 @@ package org.jclouds.concurrent.config; import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.concurrent.config.ExecutorServiceModule.getStackTraceHere; import java.util.Collection; import java.util.List; @@ -86,18 +87,18 @@ public class DescribingExecutorService implements ExecutorService { @Override public Future submit(Callable task) { - return new DescribedFuture(delegate.submit(task), task.toString(), ExecutorServiceModule.getStackTraceHere()); + return new DescribedFuture(delegate.submit(task), task.toString(), getStackTraceHere()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Future submit(Runnable task) { - return new DescribedFuture(delegate.submit(task), task.toString(), ExecutorServiceModule.getStackTraceHere()); + return new DescribedFuture(delegate.submit(task), task.toString(), getStackTraceHere()); } @Override - public Future submit(Runnable task, T result) { - return new DescribedFuture(delegate.submit(task, result), task.toString(), ExecutorServiceModule.getStackTraceHere()); + public Future submit(Runnable task, T result) { // NO_UCD + return new DescribedFuture(delegate.submit(task, result), task.toString(), getStackTraceHere()); } @Override diff --git a/core/src/main/java/org/jclouds/concurrent/config/ExecutorServiceModule.java b/core/src/main/java/org/jclouds/concurrent/config/ExecutorServiceModule.java index fb2c5d64b2..24754813da 100644 --- a/core/src/main/java/org/jclouds/concurrent/config/ExecutorServiceModule.java +++ b/core/src/main/java/org/jclouds/concurrent/config/ExecutorServiceModule.java @@ -18,6 +18,8 @@ */ package org.jclouds.concurrent.config; +import static org.jclouds.Constants.PROPERTY_IO_WORKER_THREADS; +import static org.jclouds.Constants.PROPERTY_USER_THREADS; import static org.jclouds.concurrent.DynamicExecutors.newScalingThreadPool; import java.io.Closeable; @@ -32,13 +34,11 @@ import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.Constants; import org.jclouds.concurrent.MoreExecutors; import org.jclouds.concurrent.SingleThreaded; import org.jclouds.lifecycle.Closer; import org.jclouds.logging.Logger; -import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Provides; @@ -47,21 +47,20 @@ import com.google.inject.Provides; * Configures {@link ExecutorService}. * * Note that this uses threads. - * + * *

- * This extends the underlying Future to expose a description (the task's toString) and the submission context (stack trace). - * The submission stack trace is appended to relevant stack traces on exceptions that are returned, - * so the user can see the logical chain of execution (in the executor, and where it was passed to the executor). + * This extends the underlying Future to expose a description (the task's toString) and the submission context (stack + * trace). The submission stack trace is appended to relevant stack traces on exceptions that are returned, so the user + * can see the logical chain of execution (in the executor, and where it was passed to the executor). * * @author Adrian Cole */ @ConfiguresExecutorService public class ExecutorServiceModule extends AbstractModule { - @VisibleForTesting static final class ShutdownExecutorOnClose implements Closeable { @Resource - protected Logger logger = Logger.NULL; + private Logger logger = Logger.NULL; private final ExecutorService service; @@ -77,32 +76,31 @@ public class ExecutorServiceModule extends AbstractModule { } } - @VisibleForTesting final ExecutorService userExecutorFromConstructor; - @VisibleForTesting + final ExecutorService ioExecutorFromConstructor; @Inject - public ExecutorServiceModule(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads, - @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads) { + public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userThreads, + @Named(PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads) { this.userExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(userThreads)); this.ioExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(ioThreads)); } - ExecutorService addToStringOnSubmit(ExecutorService executor) { + private ExecutorService addToStringOnSubmit(ExecutorService executor) { if (executor != null) { return new DescribingExecutorService(executor); } return executor; } - ExecutorService checkNotGuavaSameThreadExecutor(ExecutorService executor) { + private ExecutorService checkNotGuavaSameThreadExecutor(ExecutorService executor) { // we detect behavior based on the class if (executor != null && !(executor.getClass().isAnnotationPresent(SingleThreaded.class)) - && executor.getClass().getSimpleName().indexOf("SameThread") != -1) { + && executor.getClass().getSimpleName().indexOf("SameThread") != -1) { Logger.CONSOLE.warn( - "please switch from %s to %s or annotate your same threaded executor with @SingleThreaded", executor - .getClass().getName(), MoreExecutors.SameThreadExecutorService.class.getName()); + "please switch from %s to %s or annotate your same threaded executor with @SingleThreaded", executor + .getClass().getName(), MoreExecutors.SameThreadExecutorService.class.getName()); return MoreExecutors.sameThreadExecutor(); } return executor; @@ -113,13 +111,13 @@ public class ExecutorServiceModule extends AbstractModule { } @Override - protected void configure() { + protected void configure() { // NO_UCD } @Provides @Singleton - @Named(Constants.PROPERTY_USER_THREADS) - ExecutorService provideExecutorService(@Named(Constants.PROPERTY_USER_THREADS) int count, Closer closer) { + @Named(PROPERTY_USER_THREADS) + ExecutorService provideExecutorService(@Named(PROPERTY_USER_THREADS) int count, Closer closer) { // NO_UCD if (userExecutorFromConstructor != null) return userExecutorFromConstructor; return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("user thread %d", count)), closer); @@ -127,47 +125,42 @@ public class ExecutorServiceModule extends AbstractModule { @Provides @Singleton - @Named(Constants.PROPERTY_IO_WORKER_THREADS) - ExecutorService provideIOExecutor(@Named(Constants.PROPERTY_IO_WORKER_THREADS) int count, Closer closer) { + @Named(PROPERTY_IO_WORKER_THREADS) + ExecutorService provideIOExecutor(@Named(PROPERTY_IO_WORKER_THREADS) int count, Closer closer) { // NO_UCD if (ioExecutorFromConstructor != null) return ioExecutorFromConstructor; return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("i/o thread %d", count)), closer); } - @VisibleForTesting static T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } - @VisibleForTesting - ExecutorService newCachedThreadPoolNamed(String name) { + private ExecutorService newCachedThreadPoolNamed(String name) { return Executors.newCachedThreadPool(namedThreadFactory(name)); } - @VisibleForTesting - ExecutorService newThreadPoolNamed(String name, int maxCount) { + private ExecutorService newThreadPoolNamed(String name, int maxCount) { return maxCount == 0 ? newCachedThreadPoolNamed(name) : newScalingThreadPoolNamed(name, maxCount); } - @VisibleForTesting - ExecutorService newScalingThreadPoolNamed(String name, int maxCount) { + private ExecutorService newScalingThreadPoolNamed(String name, int maxCount) { return newScalingThreadPool(1, maxCount, 60L * 1000, namedThreadFactory(name)); } - protected ThreadFactory namedThreadFactory(String name) { + private ThreadFactory namedThreadFactory(String name) { return new ThreadFactoryBuilder().setNameFormat(name).setThreadFactory(Executors.defaultThreadFactory()).build(); } - /** returns the stack trace at the caller */ static StackTraceElement[] getStackTraceHere() { - // remove the first two items in the stack trace (because the first one refers to the call to + // remove the first two items in the stack trace (because the first one refers to the call to // Thread.getStackTrace, and the second one is us) StackTraceElement[] fullSubmissionTrace = Thread.currentThread().getStackTrace(); - StackTraceElement[] cleanedSubmissionTrace = new StackTraceElement[fullSubmissionTrace.length-2]; + StackTraceElement[] cleanedSubmissionTrace = new StackTraceElement[fullSubmissionTrace.length - 2]; System.arraycopy(fullSubmissionTrace, 2, cleanedSubmissionTrace, 0, cleanedSubmissionTrace.length); return cleanedSubmissionTrace; } - + } diff --git a/core/src/main/java/org/jclouds/concurrent/config/ScheduledExecutorServiceModule.java b/core/src/main/java/org/jclouds/concurrent/config/ScheduledExecutorServiceModule.java index 7b47300cfa..11ab487d59 100644 --- a/core/src/main/java/org/jclouds/concurrent/config/ScheduledExecutorServiceModule.java +++ b/core/src/main/java/org/jclouds/concurrent/config/ScheduledExecutorServiceModule.java @@ -1,7 +1,8 @@ package org.jclouds.concurrent.config; -import static org.jclouds.concurrent.config.ExecutorServiceModule.shutdownOnClose; +import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS; import static org.jclouds.concurrent.config.ExecutorServiceModule.getStackTraceHere; +import static org.jclouds.concurrent.config.ExecutorServiceModule.shutdownOnClose; import java.util.concurrent.Callable; import java.util.concurrent.Delayed; @@ -14,10 +15,8 @@ import java.util.concurrent.TimeUnit; import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.Constants; import org.jclouds.lifecycle.Closer; -import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Provides; @@ -30,90 +29,82 @@ import com.google.inject.Provides; * @author Ignasi Barrera * * @see ExecutorServiceModule - * + * */ public class ScheduledExecutorServiceModule extends AbstractModule { - static class DescribingScheduledExecutorService extends DescribingExecutorService implements ScheduledExecutorService { + private static class DescribingScheduledExecutorService extends DescribingExecutorService implements + ScheduledExecutorService { - public DescribingScheduledExecutorService(ScheduledExecutorService delegate) { - super(delegate); - } + private DescribingScheduledExecutorService(ScheduledExecutorService delegate) { + super(delegate); + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { - return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) - .schedule(command, delay, unit), command.toString(), getStackTraceHere()); - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).schedule(command, delay, unit), + command.toString(), getStackTraceHere()); + } - @Override - public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { - return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) - .schedule(callable, delay, unit), callable.toString(), getStackTraceHere()); - } + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).schedule(callable, delay, unit), + callable.toString(), getStackTraceHere()); + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, - long period, TimeUnit unit) { - return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) - .scheduleAtFixedRate(command, initialDelay, period, unit), command.toString(), getStackTraceHere()); - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { + return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).scheduleAtFixedRate(command, + initialDelay, period, unit), command.toString(), getStackTraceHere()); + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, - long delay, TimeUnit unit) { - return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) - .scheduleWithFixedDelay(command, initialDelay, delay, unit), command.toString(), getStackTraceHere()); - } - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { + return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).scheduleWithFixedDelay(command, + initialDelay, delay, unit), command.toString(), getStackTraceHere()); + } + } - static class DescribedScheduledFuture extends DescribedFuture implements ScheduledFuture { + private static class DescribedScheduledFuture extends DescribedFuture implements ScheduledFuture { - public DescribedScheduledFuture(ScheduledFuture delegate, String description, + private DescribedScheduledFuture(ScheduledFuture delegate, String description, StackTraceElement[] submissionTrace) { - super(delegate, description, submissionTrace); - } + super(delegate, description, submissionTrace); + } - @Override - public long getDelay(TimeUnit unit) { - return ((ScheduledFuture) delegate).getDelay(unit); - } + @Override + public long getDelay(TimeUnit unit) { + return ((ScheduledFuture) delegate).getDelay(unit); + } - @Override - public int compareTo(Delayed o) { - return ((ScheduledFuture) delegate).compareTo(o); - } - } + @Override + public int compareTo(Delayed o) { + return ((ScheduledFuture) delegate).compareTo(o); + } + } - static ScheduledExecutorService addToStringOnSchedule(ScheduledExecutorService executor) { - if (executor != null) { - return new DescribingScheduledExecutorService(executor); - } - return executor; - } + private static ScheduledExecutorService addToStringOnSchedule(ScheduledExecutorService executor) { + return (executor != null) ? new DescribingScheduledExecutorService(executor) : executor; + } - @Provides - @Singleton - @Named(Constants.PROPERTY_SCHEDULER_THREADS) - ScheduledExecutorService provideScheduledExecutor(@Named(Constants.PROPERTY_SCHEDULER_THREADS) final int count, - final Closer closer) { - return shutdownOnClose(addToStringOnSchedule(newScheduledThreadPoolNamed("scheduler thread %d", count)), closer); - } + @Provides + @Singleton + @Named(PROPERTY_SCHEDULER_THREADS) + ScheduledExecutorService provideScheduledExecutor(@Named(PROPERTY_SCHEDULER_THREADS) int count, Closer closer) { + return shutdownOnClose(addToStringOnSchedule(newScheduledThreadPoolNamed("scheduler thread %d", count)), closer); + } - @VisibleForTesting - static ScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) { - ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name) + private static ScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) { + ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name) .setThreadFactory(Executors.defaultThreadFactory()).build(); - return maxCount == 0 ? Executors.newSingleThreadScheduledExecutor(factory) - : Executors.newScheduledThreadPool(maxCount, factory); - } - - @Override - protected void configure() { - - } + return maxCount == 0 ? Executors.newSingleThreadScheduledExecutor(factory) : Executors.newScheduledThreadPool( + maxCount, factory); + } + @Override + protected void configure() { // NO_UCD + } } diff --git a/core/src/main/java/org/jclouds/config/BindPropertiesToExpandedValues.java b/core/src/main/java/org/jclouds/config/BindPropertiesToExpandedValues.java index ad0edf44c4..6da992542b 100644 --- a/core/src/main/java/org/jclouds/config/BindPropertiesToExpandedValues.java +++ b/core/src/main/java/org/jclouds/config/BindPropertiesToExpandedValues.java @@ -53,7 +53,6 @@ public class BindPropertiesToExpandedValues extends AbstractModule { bindProperties(resolved); } - @SuppressWarnings("unused") @Provides @Singleton protected Properties expanded(FilterStringsBoundToInjectorByName filterStringsBoundByName) { diff --git a/core/src/main/java/org/jclouds/config/ValueOfConfigurationKeyOrNull.java b/core/src/main/java/org/jclouds/config/ValueOfConfigurationKeyOrNull.java index 5ddb922f26..52bdbc6aa8 100644 --- a/core/src/main/java/org/jclouds/config/ValueOfConfigurationKeyOrNull.java +++ b/core/src/main/java/org/jclouds/config/ValueOfConfigurationKeyOrNull.java @@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.inject.name.Names.named; import javax.inject.Inject; -import javax.inject.Singleton; import com.google.common.base.Function; import com.google.inject.ConfigurationException; @@ -33,12 +32,11 @@ import com.google.inject.Key; * * @author Adrian Cole */ -@Singleton public class ValueOfConfigurationKeyOrNull implements Function { - protected final Injector injector; + private final Injector injector; @Inject - public ValueOfConfigurationKeyOrNull(Injector injector) { + private ValueOfConfigurationKeyOrNull(Injector injector) { this.injector = checkNotNull(injector, "injector"); } @@ -51,5 +49,4 @@ public class ValueOfConfigurationKeyOrNull implements Function { return null; } } - } diff --git a/core/src/main/java/org/jclouds/crypto/Pems.java b/core/src/main/java/org/jclouds/crypto/Pems.java index 972f60a196..1da295507e 100644 --- a/core/src/main/java/org/jclouds/crypto/Pems.java +++ b/core/src/main/java/org/jclouds/crypto/Pems.java @@ -76,15 +76,15 @@ public class Pems { public static final String PUBLIC_X509_MARKER = "-----BEGIN PUBLIC KEY-----"; public static final String PUBLIC_PKCS1_MARKER = "-----BEGIN RSA PUBLIC KEY-----"; - public static class PemProcessor implements ByteProcessor { - public interface ResultParser { + private static class PemProcessor implements ByteProcessor { + private interface ResultParser { T parseResult(byte[] bytes) throws IOException; } private final ByteArrayOutputStream out = new ByteArrayOutputStream(); private final Map> parsers; - public PemProcessor(Map> parsers) { + private PemProcessor(Map> parsers) { this.parsers = checkNotNull(parsers, "parsers"); } diff --git a/core/src/main/java/org/jclouds/crypto/RsaSshKeyPairGenerator.java b/core/src/main/java/org/jclouds/crypto/RsaSshKeyPairGenerator.java index 387bb7a1bc..99d98dcf55 100644 --- a/core/src/main/java/org/jclouds/crypto/RsaSshKeyPairGenerator.java +++ b/core/src/main/java/org/jclouds/crypto/RsaSshKeyPairGenerator.java @@ -28,12 +28,12 @@ import javax.inject.Singleton; import com.google.inject.Inject; @Singleton -public class RsaSshKeyPairGenerator implements SshKeyPairGenerator { - protected final Crypto crypto; - protected final SecureRandom secureRandom; +class RsaSshKeyPairGenerator implements SshKeyPairGenerator { + private final Crypto crypto; + private final SecureRandom secureRandom; @Inject - public RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) { + private RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) { this.crypto = checkNotNull(crypto, "crypto"); this.secureRandom = checkNotNull(secureRandom, "secureRandom"); } diff --git a/core/src/main/java/org/jclouds/crypto/Sha512Crypt.java b/core/src/main/java/org/jclouds/crypto/Sha512Crypt.java index 7e91469721..9c59a4c561 100644 --- a/core/src/main/java/org/jclouds/crypto/Sha512Crypt.java +++ b/core/src/main/java/org/jclouds/crypto/Sha512Crypt.java @@ -99,7 +99,7 @@ public class Sha512Crypt { return Function.INSTANCE; } - public static enum Function implements com.google.common.base.Function { + private static enum Function implements com.google.common.base.Function { INSTANCE; @Override @@ -111,7 +111,6 @@ public class Sha512Crypt { public String toString() { return "sha512Crypt()"; } - } private static final String sha512_salt_prefix = "$6$"; @@ -141,7 +140,7 @@ public class Sha512Crypt { * * @return The Sha512 Unix Crypt hash text for the password */ - public static String makeShadowLine(String password, @Nullable String shadowPrefix) { + static String makeShadowLine(String password, @Nullable String shadowPrefix) { MessageDigest ctx = sha512(); MessageDigest alt_ctx = sha512(); diff --git a/core/src/main/java/org/jclouds/crypto/SshKeys.java b/core/src/main/java/org/jclouds/crypto/SshKeys.java index cb4f5cae24..377b588105 100644 --- a/core/src/main/java/org/jclouds/crypto/SshKeys.java +++ b/core/src/main/java/org/jclouds/crypto/SshKeys.java @@ -110,7 +110,7 @@ public class SshKeys { } // http://www.ietf.org/rfc/rfc4253.txt - static byte[] readLengthFirst(InputStream in) throws IOException { + private static byte[] readLengthFirst(InputStream in) throws IOException { int byte1 = in.read(); int byte2 = in.read(); int byte3 = in.read(); @@ -315,7 +315,7 @@ public class SshKeys { return on(':').join(fixedLength(2).split(base16().lowerCase().encode(hc.asBytes()))); } - public static byte[] keyBlob(BigInteger publicExponent, BigInteger modulus) { + private static byte[] keyBlob(BigInteger publicExponent, BigInteger modulus) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); writeLengthFirst("ssh-rsa".getBytes(), out); @@ -328,7 +328,7 @@ public class SshKeys { } // http://www.ietf.org/rfc/rfc4253.txt - static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException { + private static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException { out.write((array.length >>> 24) & 0xFF); out.write((array.length >>> 16) & 0xFF); out.write((array.length >>> 8) & 0xFF); diff --git a/core/src/main/java/org/jclouds/date/DateService.java b/core/src/main/java/org/jclouds/date/DateService.java index 405fea3e8f..93c6aa4498 100644 --- a/core/src/main/java/org/jclouds/date/DateService.java +++ b/core/src/main/java/org/jclouds/date/DateService.java @@ -34,8 +34,6 @@ import com.google.inject.ImplementedBy; @ImplementedBy(SimpleDateFormatDateService.class) public interface DateService { - Date fromSeconds(long seconds); - String cDateFormat(Date date); String cDateFormat(); diff --git a/core/src/main/java/org/jclouds/date/internal/DateUtils.java b/core/src/main/java/org/jclouds/date/internal/DateUtils.java index 0f951d81c6..f1fe02b53f 100644 --- a/core/src/main/java/org/jclouds/date/internal/DateUtils.java +++ b/core/src/main/java/org/jclouds/date/internal/DateUtils.java @@ -27,12 +27,10 @@ import java.util.regex.Pattern; */ public class DateUtils { - public static final String TZ_REGEX = "([+-][0-9][0-9](:?[0-9][0-9])?|Z)"; - - public static final Pattern MILLIS_PATTERN = Pattern.compile("(.*\\.[0-9][0-9][0-9])[0-9]*" + TZ_REGEX + "?"); - + private static final String TZ_REGEX = "([+-][0-9][0-9](:?[0-9][0-9])?|Z)"; + private static final Pattern MILLIS_PATTERN = Pattern.compile("(.*\\.[0-9][0-9][0-9])[0-9]*" + TZ_REGEX + "?"); // This regexp will match all TZ forms that are valid is ISO 8601 - public static final Pattern TZ_PATTERN = Pattern.compile("(.*)" + TZ_REGEX + "$"); + private static final Pattern TZ_PATTERN = Pattern.compile("(.*)" + TZ_REGEX + "$"); public static String trimToMillis(String toParse) { Matcher matcher = MILLIS_PATTERN.matcher(toParse); @@ -44,7 +42,7 @@ public class DateUtils { return toParse; } - public static final Pattern SECOND_PATTERN = Pattern.compile(".*[0-2][0-9]:00"); + private static final Pattern SECOND_PATTERN = Pattern.compile(".*[0-2][0-9]:00"); public static String trimTZ(String toParse) { Matcher matcher = TZ_PATTERN.matcher(toParse); diff --git a/core/src/main/java/org/jclouds/date/internal/SimpleDateFormatDateService.java b/core/src/main/java/org/jclouds/date/internal/SimpleDateFormatDateService.java index dd96f2a2f5..02334a3436 100644 --- a/core/src/main/java/org/jclouds/date/internal/SimpleDateFormatDateService.java +++ b/core/src/main/java/org/jclouds/date/internal/SimpleDateFormatDateService.java @@ -66,11 +66,6 @@ public class SimpleDateFormatDateService implements DateService { cSimpleDateFormat.setTimeZone(new SimpleTimeZone(0, "GMT")); } - @Override - public final Date fromSeconds(long seconds) { - return new Date(seconds * 1000); - } - @Override public final String cDateFormat(Date date) { synchronized (cSimpleDateFormat) { diff --git a/core/src/main/java/org/jclouds/domain/Credentials.java b/core/src/main/java/org/jclouds/domain/Credentials.java index 48d061cd10..e4da6ad9bf 100644 --- a/core/src/main/java/org/jclouds/domain/Credentials.java +++ b/core/src/main/java/org/jclouds/domain/Credentials.java @@ -18,23 +18,12 @@ */ package org.jclouds.domain; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.net.URI; -import java.util.List; - -import org.jclouds.util.Strings2; - import com.google.common.base.Objects; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; /** * @author Adrian Cole */ public class Credentials { - public static final Credentials NO_CREDENTIALS = new Credentials(null, null); - public static class Builder { protected String identity; protected String credential; @@ -63,21 +52,6 @@ public class Credentials { this.credential = credential; } - public static Credentials parse(URI uri) { - checkNotNull(uri, "uri"); - 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 (Strings2.isUrlEncoded(identity)) { - identity = Strings2.urlDecode(identity); - } - String credential = userInfo.size() > 1 ? userInfo.get(1) : null; - if (credential != null && Strings2.isUrlEncoded(credential)) { - credential = Strings2.urlDecode(credential); - } - return new Credentials(identity, credential); - } - public Builder toBuilder() { return new Builder().identity(identity).credential(credential); } diff --git a/core/src/main/java/org/jclouds/domain/JsonBall.java b/core/src/main/java/org/jclouds/domain/JsonBall.java index a00f84daa5..647118b3ba 100644 --- a/core/src/main/java/org/jclouds/domain/JsonBall.java +++ b/core/src/main/java/org/jclouds/domain/JsonBall.java @@ -87,7 +87,7 @@ public class JsonBall implements Comparable, CharSequence { this.value = quoteStringIfNotNumberOrBoolean(checkNotNull(value, "value")); } - static String quoteStringIfNotNumberOrBoolean(String in) { + private static String quoteStringIfNotNumberOrBoolean(String in) { if (JSON_STRING_PATTERN.matcher(in).find() && !JSON_NUMBER_PATTERN.matcher(in).find() && !JSON_BOOLEAN_PATTERN.matcher(in).find()) { return "\"" + in + "\""; diff --git a/core/src/main/java/org/jclouds/domain/LocationBuilder.java b/core/src/main/java/org/jclouds/domain/LocationBuilder.java index e722ddc1c7..dc97bc6ff4 100644 --- a/core/src/main/java/org/jclouds/domain/LocationBuilder.java +++ b/core/src/main/java/org/jclouds/domain/LocationBuilder.java @@ -32,13 +32,13 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -public class LocationBuilder { - protected LocationScope scope; - protected String id; - protected String description; - protected Location parent; - protected Set iso3166Codes = ImmutableSet.of(); - protected Map metadata = ImmutableMap.of(); +public final class LocationBuilder { + private LocationScope scope; + private String id; + private String description; + private Location parent; + private Set iso3166Codes = ImmutableSet.of(); + private Map metadata = ImmutableMap.of(); public LocationBuilder scope(LocationScope scope) { this.scope = scope; diff --git a/core/src/main/java/org/jclouds/domain/LocationScope.java b/core/src/main/java/org/jclouds/domain/LocationScope.java index 85ac72a668..32ee3e0c61 100644 --- a/core/src/main/java/org/jclouds/domain/LocationScope.java +++ b/core/src/main/java/org/jclouds/domain/LocationScope.java @@ -36,7 +36,6 @@ public enum LocationScope { * E.g. the DMZ segment, secure segment. */ NETWORK, - RACK, HOST; } diff --git a/core/src/main/java/org/jclouds/domain/LoginCredentials.java b/core/src/main/java/org/jclouds/domain/LoginCredentials.java index 6f2f4d51a4..8f217fd982 100644 --- a/core/src/main/java/org/jclouds/domain/LoginCredentials.java +++ b/core/src/main/java/org/jclouds/domain/LoginCredentials.java @@ -18,7 +18,9 @@ */ package org.jclouds.domain; -import org.jclouds.crypto.Pems; +import static org.jclouds.crypto.Pems.PRIVATE_PKCS1_MARKER; +import static org.jclouds.crypto.Pems.PRIVATE_PKCS8_MARKER; + import org.jclouds.javax.annotation.Nullable; import com.google.common.base.Optional; @@ -28,9 +30,9 @@ import com.google.common.base.Optional; */ public class LoginCredentials extends Credentials { - public static boolean isPrivateKeyCredential(String credential) { + private static boolean isPrivateKeyCredential(String credential) { return credential != null - && (credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credential.startsWith(Pems.PRIVATE_PKCS8_MARKER)); + && (credential.startsWith(PRIVATE_PKCS1_MARKER) || credential.startsWith(PRIVATE_PKCS8_MARKER)); } public static LoginCredentials fromCredentials(Credentials creds) { @@ -115,15 +117,7 @@ public class LoginCredentials extends Credentials { private final Optional password; private final Optional privateKey; - public LoginCredentials(String username, boolean authenticateSudo) { - this(username, Optional.absent(), Optional.absent(), authenticateSudo); - } - - public LoginCredentials(String username, @Nullable String password, @Nullable String privateKey, boolean authenticateSudo) { - this(username, Optional.fromNullable(password), Optional.fromNullable(privateKey), authenticateSudo); - } - - public LoginCredentials(String username, @Nullable Optional password, @Nullable Optional privateKey, boolean authenticateSudo) { + private LoginCredentials(String username, @Nullable Optional password, @Nullable Optional privateKey, boolean authenticateSudo) { super(username, privateKey != null && privateKey.isPresent() && isPrivateKeyCredential(privateKey.get()) ? privateKey.get() : (password != null && password.isPresent() ? password.get() : null)); @@ -139,26 +133,12 @@ public class LoginCredentials extends Credentials { return identity; } - /** - * @return true if a password is available - */ - public boolean hasPassword() { - return password != null && password.isPresent(); - } - - /** - * @return true if a password was set - */ - public boolean hasPasswordOption() { - return password != null; - } - /** * @return the password of the login user or null */ @Nullable public String getPassword() { - return hasPassword() ? password.get() : null; + return (password != null) ? password.orNull() : null; } /** @@ -169,26 +149,12 @@ public class LoginCredentials extends Credentials { return password; } - /** - * @return true if a private key is available - */ - public boolean hasPrivateKey() { - return privateKey != null && privateKey.isPresent(); - } - - /** - * @return true if a password was set - */ - public boolean hasPrivateKeyOption() { - return privateKey != null; - } - /** * @return the private ssh key of the user or null */ @Nullable public String getPrivateKey() { - return hasPrivateKey() ? privateKey.get() : null; + return (privateKey != null) ? privateKey.orNull() : null; } /** @@ -233,7 +199,7 @@ public class LoginCredentials extends Credentials { @Override public String toString() { - return "[user=" + getUser() + ", passwordPresent=" + hasPassword() + ", privateKeyPresent=" - + hasPrivateKey() + ", shouldAuthenticateSudo=" + authenticateSudo + "]"; + return "[user=" + getUser() + ", passwordPresent=" + password.isPresent() + ", privateKeyPresent=" + + privateKey.isPresent() + ", shouldAuthenticateSudo=" + authenticateSudo + "]"; } } diff --git a/core/src/main/java/org/jclouds/domain/internal/LocationImpl.java b/core/src/main/java/org/jclouds/domain/internal/LocationImpl.java index 22113da65d..9f44aa31ff 100644 --- a/core/src/main/java/org/jclouds/domain/internal/LocationImpl.java +++ b/core/src/main/java/org/jclouds/domain/internal/LocationImpl.java @@ -63,22 +63,15 @@ public class LocationImpl implements Location { @Override public String toString() { - return string().toString(); - } - - - protected ToStringHelper string() { ToStringHelper helper = Objects.toStringHelper("").omitNullValues().add("scope", scope).add("id", id) - .add("description", description); - + .add("description", description); if (parent != null) helper.add("parent", parent.getId()); - if (iso3166Codes.size() > 0) helper.add("iso3166Codes", iso3166Codes); if (metadata.size() > 0) helper.add("metadata", metadata); - return helper; + return helper.toString(); } public LocationImpl(LocationScope scope, String id, String description, @Nullable Location parent, diff --git a/core/src/main/java/org/jclouds/encryption/internal/JCECrypto.java b/core/src/main/java/org/jclouds/encryption/internal/JCECrypto.java index 77d0a06773..d5fecaadd1 100644 --- a/core/src/main/java/org/jclouds/encryption/internal/JCECrypto.java +++ b/core/src/main/java/org/jclouds/encryption/internal/JCECrypto.java @@ -87,8 +87,8 @@ public class JCECrypto implements Crypto { return provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider); } - public static final String HmacSHA256 = "HmacSHA256"; - public static final String HmacSHA1 = "HmacSHA1"; + private static final String HmacSHA256 = "HmacSHA256"; + private static final String HmacSHA1 = "HmacSHA1"; @Override public Mac hmacSHA1(byte[] key) throws InvalidKeyException { diff --git a/core/src/main/java/org/jclouds/events/config/EventBusModule.java b/core/src/main/java/org/jclouds/events/config/EventBusModule.java index ea3d88706d..559e86492a 100644 --- a/core/src/main/java/org/jclouds/events/config/EventBusModule.java +++ b/core/src/main/java/org/jclouds/events/config/EventBusModule.java @@ -19,12 +19,15 @@ package org.jclouds.events.config; +import static com.google.inject.Scopes.SINGLETON; +import static org.jclouds.Constants.PROPERTY_USER_THREADS; + import java.util.concurrent.ExecutorService; import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.Constants; +import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.events.config.annotations.AsyncBus; import org.jclouds.events.handlers.DeadEventLoggingHandler; @@ -32,13 +35,12 @@ import com.google.common.eventbus.AsyncEventBus; import com.google.common.eventbus.EventBus; import com.google.inject.AbstractModule; import com.google.inject.Provides; -import com.google.inject.Scopes; /** * Configures the {@link EventBus} to be used in the platform. *

- * This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for - * asynchronous operations. + * This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for asynchronous + * operations. * * @author Ignasi Barrera * @@ -49,37 +51,34 @@ import com.google.inject.Scopes; */ @ConfiguresEventBus public class EventBusModule extends AbstractModule { - /** - * Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch - * events to subscribers. - */ - @Provides - @Singleton - AsyncEventBus provideAsyncEventBus( - @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService executor, - final DeadEventLoggingHandler deadEventsHandler) { - AsyncEventBus asyncBus = new AsyncEventBus("jclouds-async-event-bus", executor); - asyncBus.register(deadEventsHandler); - return asyncBus; - } + /** + * Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch events to subscribers. + */ + @Provides + @Singleton + AsyncEventBus provideAsyncEventBus(@Named(PROPERTY_USER_THREADS) ExecutorService executor, + DeadEventLoggingHandler deadEventsHandler) {// NO_UCD + AsyncEventBus asyncBus = new AsyncEventBus("jclouds-async-event-bus", executor); + asyncBus.register(deadEventsHandler); + return asyncBus; + } - /** - * Provides asynchronous {@link EventBus}. - */ - @Provides - @Singleton - EventBus provideSyncEventBus(final DeadEventLoggingHandler deadEventsHandler) { - EventBus syncBus = new EventBus("jclouds-sync-event-bus"); - syncBus.register(deadEventsHandler); - return syncBus; - } - - /** - * Configures the {@link EventBus} to be singleton and enables the {@link AsyncBus} annotation. - */ - @Override - protected void configure() { - bind(EventBus.class).annotatedWith(AsyncBus.class).to(AsyncEventBus.class).in(Scopes.SINGLETON); - } + /** + * Provides asynchronous {@link EventBus}. + */ + @Provides + @Singleton + EventBus provideSyncEventBus(DeadEventLoggingHandler deadEventsHandler) { // NO_UCD + EventBus syncBus = new EventBus("jclouds-sync-event-bus"); + syncBus.register(deadEventsHandler); + return syncBus; + } + /** + * Configures the {@link EventBus} to be singleton and enables the {@link AsyncBus} annotation. + */ + @Override + protected void configure() { + bind(EventBus.class).annotatedWith(AsyncBus.class).to(AsyncEventBus.class).in(SINGLETON); + } } diff --git a/core/src/main/java/org/jclouds/events/handlers/DeadEventLoggingHandler.java b/core/src/main/java/org/jclouds/events/handlers/DeadEventLoggingHandler.java index c4fbafa9cf..2bdd5ccaa9 100644 --- a/core/src/main/java/org/jclouds/events/handlers/DeadEventLoggingHandler.java +++ b/core/src/main/java/org/jclouds/events/handlers/DeadEventLoggingHandler.java @@ -35,18 +35,12 @@ import com.google.common.eventbus.Subscribe; * @author Ignasi Barrera */ @Singleton -public class DeadEventLoggingHandler -{ - @Resource - private Logger logger = Logger.NULL; +public class DeadEventLoggingHandler { + @Resource + private Logger logger = Logger.NULL; - /** - * Due to Guava Issue - * 786 {@link #handleDeadEvent(DeadEvent)} is marked finalto avoid having - * duplicate events. - */ - @Subscribe - public final void handleDeadEvent(DeadEvent deadEvent) { - logger.trace("detected dead event %s", deadEvent.getEvent()); - } + @Subscribe + public void handleDeadEvent(DeadEvent deadEvent) { // NO_UCD + logger.trace("detected dead event %s", deadEvent.getEvent()); + } } diff --git a/core/src/main/java/org/jclouds/fallbacks/MapHttp4xxCodesToExceptions.java b/core/src/main/java/org/jclouds/fallbacks/MapHttp4xxCodesToExceptions.java index cd39989e19..2748af68eb 100644 --- a/core/src/main/java/org/jclouds/fallbacks/MapHttp4xxCodesToExceptions.java +++ b/core/src/main/java/org/jclouds/fallbacks/MapHttp4xxCodesToExceptions.java @@ -36,19 +36,18 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adrian Cole */ @Singleton -public class MapHttp4xxCodesToExceptions implements FutureFallback { +public final class MapHttp4xxCodesToExceptions implements FutureFallback { private final PropagateIfRetryAfter propagateIfRetryAfter; @Inject - protected MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) { + MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) { // NO_UCD this.propagateIfRetryAfter = checkNotNull(propagateIfRetryAfter, "propagateIfRetryAfter"); } @Override - public ListenableFuture create(Throwable t) { - // if we pass here, we aren't a retry-after exception - propagateIfRetryAfter.create(t); + public ListenableFuture create(Throwable t) { // NO_UCD + propagateIfRetryAfter.create(t); // if we pass here, we aren't a retry-after exception if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) diff --git a/core/src/main/java/org/jclouds/http/Uris.java b/core/src/main/java/org/jclouds/http/Uris.java index f8a66bf378..c87d5bd395 100644 --- a/core/src/main/java/org/jclouds/http/Uris.java +++ b/core/src/main/java/org/jclouds/http/Uris.java @@ -139,11 +139,6 @@ public final class Uris { return this; } - public UriBuilder clearPath() { - path = null; - return this; - } - public UriBuilder path(@Nullable String path) { path = emptyToNull(path); if (path == null) @@ -163,10 +158,6 @@ public final class Uris { return this; } - public UriBuilder query(Map parameters) { - return query(forMap(parameters)); - } - public UriBuilder query(@Nullable String queryLine) { if (query == null) return clearQuery(); @@ -194,10 +185,6 @@ public final class Uris { return addQuery(name, Arrays.asList(checkNotNull(values, "values of %s", name))); } - public UriBuilder addQuery(Map parameters) { - return addQuery(forMap(parameters)); - } - public UriBuilder addQuery(Multimap parameters) { query.putAll(checkNotNull(parameters, "parameters")); return this; @@ -315,7 +302,7 @@ public final class Uris { } } - public String expand(Map variables) { + private String expand(Map variables) { StringBuilder b = new StringBuilder(); if (scheme != null) b.append(scheme).append("://"); 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 d28f701187..1d03452a3e 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseSax.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseSax.java @@ -205,10 +205,6 @@ public class ParseSax implements Function, InvocationContext } public abstract static class HandlerForGeneratedRequestWithResult extends HandlerWithResult { - @Override - protected GeneratedHttpRequest getRequest() { - return (GeneratedHttpRequest) super.getRequest(); - } @Override public HandlerForGeneratedRequestWithResult setContext(HttpRequest request) { @@ -216,6 +212,11 @@ public class ParseSax implements Function, InvocationContext super.setContext(request); return this; } + + @Override + protected GeneratedHttpRequest getRequest() { + return (GeneratedHttpRequest) super.getRequest(); + } } @Override diff --git a/core/src/main/java/org/jclouds/internal/BaseView.java b/core/src/main/java/org/jclouds/internal/BaseView.java index b58ebd32a4..0e5c7ba733 100644 --- a/core/src/main/java/org/jclouds/internal/BaseView.java +++ b/core/src/main/java/org/jclouds/internal/BaseView.java @@ -53,11 +53,6 @@ public abstract class BaseView extends ForwardingObject implements View { return (C) backend; } - @Override - public C unwrap(Class clazz) { - return unwrap (TypeToken.of(checkNotNull(clazz, "clazz"))); - } - @Override public TypeToken getBackendType() { return backendType; diff --git a/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java index 743463fbe2..157de5dd69 100644 --- a/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java +++ b/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java @@ -123,7 +123,6 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp this.delegateFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, checkNotNull(serializationFieldNamingPolicy, "fieldNamingPolicy"), checkNotNull(excluder, "excluder")); } - @SuppressWarnings("unchecked") public TypeAdapter create(Gson gson, final TypeToken type) { Class raw = type.getRawType(); Constructor deserializationCtor = constructorFieldNamingPolicy.getDeserializationConstructor(raw); @@ -139,11 +138,11 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp private final class DeserializeWithParameterizedConstructorSerializeWithDelegate extends TypeAdapter { private final Constructor parameterizedCtor; - private final Map parameterReaders; + private final Map> parameterReaders; private final TypeAdapter delegate; private DeserializeWithParameterizedConstructorSerializeWithDelegate(TypeAdapter delegate, - Constructor parameterizedCtor, Map parameterReaders) { + Constructor parameterizedCtor, Map> parameterReaders) { this.delegate = delegate; this.parameterizedCtor = parameterizedCtor; this.parameterReaders = parameterReaders; @@ -174,7 +173,7 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp while (in.hasNext()) { empty = false; String name = in.nextName(); - ParameterReader parameter = parameterReaders.get(name); + ParameterReader parameter = parameterReaders.get(name); if (parameter == null) { in.skipValue(); } else { @@ -246,20 +245,19 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp } } - @SuppressWarnings("unchecked") - private Map getParameterReaders(Gson context, TypeToken declaring, Constructor constructor) { - Map result = Maps.newLinkedHashMap(); + private Map> getParameterReaders(Gson context, TypeToken declaring, Constructor constructor) { + Map> result = Maps.newLinkedHashMap(); for (int index = 0; index < constructor.getGenericParameterTypes().length; index++) { Type parameterType = getTypeOfConstructorParameter(declaring, constructor, index); TypeAdapter adapter = context.getAdapter(TypeToken.get(parameterType)); String parameterName = constructorFieldNamingPolicy.translateName(constructor, index); checkArgument(parameterName != null, constructor + " parameter " + 0 + " failed to be named by " + constructorFieldNamingPolicy); - ParameterReader parameterReader = new ParameterReader(parameterName, index, adapter); - ParameterReader previous = result.put(parameterReader.name, parameterReader); + @SuppressWarnings({ "rawtypes", "unchecked" }) + ParameterReader parameterReader = new ParameterReader(parameterName, index, adapter); + ParameterReader previous = result.put(parameterReader.name, parameterReader); checkArgument(previous == null, constructor + " declares multiple JSON parameters named " + parameterReader.name); } - return result; } diff --git a/core/src/main/java/org/jclouds/rest/binders/BindMapToStringPayload.java b/core/src/main/java/org/jclouds/rest/binders/BindMapToStringPayload.java index cc3332db2d..95c63847c9 100644 --- a/core/src/main/java/org/jclouds/rest/binders/BindMapToStringPayload.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindMapToStringPayload.java @@ -45,7 +45,7 @@ public class BindMapToStringPayload implements MapBinder { @Override public R bindToRequest(R request, Map postParams) { checkNotNull(postParams, "postParams"); - GeneratedHttpRequest r = GeneratedHttpRequest.class.cast(checkNotNull(request, "request")); + GeneratedHttpRequest r = GeneratedHttpRequest.class.cast(checkNotNull(request, "request")); Invokable invoked = r.getInvocation().getInvokable(); checkArgument(invoked.isAnnotationPresent(Payload.class), "method %s must have @Payload annotation to use this binder", invoked); diff --git a/core/src/test/java/org/jclouds/PerformanceTest.java b/core/src/test/java/org/jclouds/PerformanceTest.java index 82ee76b03f..dc2346c080 100644 --- a/core/src/test/java/org/jclouds/PerformanceTest.java +++ b/core/src/test/java/org/jclouds/PerformanceTest.java @@ -18,6 +18,8 @@ */ package org.jclouds; +import static java.util.concurrent.Executors.defaultThreadFactory; + import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; @@ -44,7 +46,7 @@ public abstract class PerformanceTest { @BeforeTest public void setupExecutorService() { - exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000); + exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000, defaultThreadFactory()); } @AfterTest diff --git a/core/src/test/java/org/jclouds/config/ValueOfConfigurationKeyOrNullTest.java b/core/src/test/java/org/jclouds/config/ValueOfConfigurationKeyOrNullTest.java index 53c8000b82..adafb7a5b1 100644 --- a/core/src/test/java/org/jclouds/config/ValueOfConfigurationKeyOrNullTest.java +++ b/core/src/test/java/org/jclouds/config/ValueOfConfigurationKeyOrNullTest.java @@ -36,32 +36,30 @@ public class ValueOfConfigurationKeyOrNullTest { @Test public void testNotThere() { - assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector()).apply("foo"), null); + assertEquals(Guice.createInjector().getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), null); } @Test public void testThere() { - assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { + assertEquals(Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith(Names.named("foo")).to("bar"); } - })).apply("foo"), "bar"); - + }).getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), "bar"); } @Test public void testEmptyIsThere() { - assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { + assertEquals(Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith(Names.named("foo")).to(""); } - })).apply("foo"), ""); - + }).getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), ""); } } diff --git a/core/src/test/java/org/jclouds/crypto/RsaSshKeyPairGeneratorTest.java b/core/src/test/java/org/jclouds/crypto/RsaSshKeyPairGeneratorTest.java index ac67a54953..bc364d7102 100644 --- a/core/src/test/java/org/jclouds/crypto/RsaSshKeyPairGeneratorTest.java +++ b/core/src/test/java/org/jclouds/crypto/RsaSshKeyPairGeneratorTest.java @@ -42,6 +42,8 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; /** * @author Adrian Cole @@ -66,9 +68,9 @@ public class RsaSshKeyPairGeneratorTest { @Test public void testApply() { - Crypto crypto = createMock(Crypto.class); + final Crypto crypto = createMock(Crypto.class); KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class); - SecureRandom secureRandom = createMock(SecureRandom.class); + final SecureRandom secureRandom = createMock(SecureRandom.class); expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator); rsaKeyPairGenerator.initialize(2048, secureRandom); @@ -76,7 +78,12 @@ public class RsaSshKeyPairGeneratorTest { replay(crypto, rsaKeyPairGenerator, secureRandom); - RsaSshKeyPairGenerator supplier = new RsaSshKeyPairGenerator(crypto, secureRandom); + RsaSshKeyPairGenerator supplier = Guice.createInjector(new AbstractModule(){ + protected void configure() { + bind(Crypto.class).toInstance(crypto); + bind(SecureRandom.class).toInstance(secureRandom); + } + }).getInstance(RsaSshKeyPairGenerator.class); assertEquals(supplier.get(), ImmutableMap.of("public", openSshKey, "private", PRIVATE_KEY.replaceAll("\n", lineSeparator))); diff --git a/core/src/test/java/org/jclouds/date/DateServiceTest.java b/core/src/test/java/org/jclouds/date/DateServiceTest.java index 439c1b4203..71878eb19b 100644 --- a/core/src/test/java/org/jclouds/date/DateServiceTest.java +++ b/core/src/test/java/org/jclouds/date/DateServiceTest.java @@ -174,13 +174,6 @@ public class DateServiceTest extends PerformanceTest { dateService.iso8601DateFormat(); } - @Test - void testFromSeconds() { - long seconds = 1254008225; - Date date = dateService.fromSeconds(seconds); - assertEquals(dateService.iso8601SecondsDateFormat(date), "2009-09-26T23:37:05Z"); - } - @Test void testUTCIsGMT() { assertEquals(dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime(), dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime()); diff --git a/core/src/test/java/org/jclouds/domain/CredentialsTest.java b/core/src/test/java/org/jclouds/domain/CredentialsTest.java index f976270208..af4201e164 100644 --- a/core/src/test/java/org/jclouds/domain/CredentialsTest.java +++ b/core/src/test/java/org/jclouds/domain/CredentialsTest.java @@ -20,8 +20,6 @@ package org.jclouds.domain; import static org.testng.Assert.assertEquals; -import java.net.URI; - import org.testng.annotations.Test; /** @@ -30,69 +28,9 @@ import org.testng.annotations.Test; @Test(groups = "unit") public class CredentialsTest { - public void testAzure() { - Credentials creds = Credentials - .parse(URI.create("compute://identity:Base64==@azureblob/container-hyphen/prefix")); - assertEquals(creds.identity, "identity"); - assertEquals(creds.credential, "Base64=="); - } - - public void testAtmos() { - Credentials creds = Credentials.parse(URI - .create("compute://domain%2Fuser:Base64%3D%3D@azureblob/container-hyphen/prefix")); - assertEquals(creds.identity, "domain/user"); - assertEquals(creds.credential, "Base64=="); - } - - public void testDollar() { - Credentials creds = Credentials.parse(URI.create("compute://user%40domain:pa%24sword@hostingdotcom")); - assertEquals(creds.identity, "user@domain"); - assertEquals(creds.credential, "pa$sword"); - } - - public void testTerremark() { - Credentials creds = Credentials.parse(URI.create("compute://user%40domain:password@terremark")); - assertEquals(creds.identity, "user@domain"); - assertEquals(creds.credential, "password"); - } - - public void testTerremark2() { - Credentials creds = Credentials.parse(URI.create("compute://user%40domain:passw%40rd@terremark")); - assertEquals(creds.identity, "user@domain"); - assertEquals(creds.credential, "passw@rd"); - } - - public void testTerremark3() { - Credentials creds = Credentials.parse(URI.create("compute://user%40domain:AbC%21%40943%21@terremark")); - assertEquals(creds.identity, "user@domain"); - assertEquals(creds.credential, "AbC!@943!"); - } - - public void testCloudFiles() { - Credentials creds = Credentials.parse(URI.create("compute://identity:h3c@cloudfiles/container-hyphen/prefix")); - assertEquals(creds.identity, "identity"); - assertEquals(creds.credential, "h3c"); - - } - - public void testS3() { - - Credentials creds = Credentials.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/prefix")); - assertEquals(creds.identity, "0AB"); - assertEquals(creds.credential, "aA+/0"); - } - - public void testS3Space() { - - Credentials creds = Credentials.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/pre%20fix")); - assertEquals(creds.identity, "0AB"); - assertEquals(creds.credential, "aA+/0"); - } - public void testSubClassEquals() { Credentials creds = new Credentials("user", "pass"); assertEquals(creds, new Credentials("user", "pass") { }); } - } diff --git a/core/src/test/java/org/jclouds/http/UrisTest.java b/core/src/test/java/org/jclouds/http/UrisTest.java index db7ef6f53d..17aae4754c 100644 --- a/core/src/test/java/org/jclouds/http/UrisTest.java +++ b/core/src/test/java/org/jclouds/http/UrisTest.java @@ -23,7 +23,6 @@ import static org.jclouds.util.Strings2.urlEncode; import static org.testng.Assert.assertEquals; import java.net.URI; -import java.util.Map; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -74,18 +73,17 @@ public class UrisTest { @Test(dataProvider = "strings") public void testQuery(String val) { - Map query = ImmutableMap.of("moo", val); - assertEquals(uriBuilder("https://foo.com:8080").query(query).toString(), "https://foo.com:8080?moo=" + val); - assertEquals(uriBuilder("https://foo.com:8080").query(query).build().toString(), "https://foo.com:8080?moo=" + assertEquals(uriBuilder("https://foo.com:8080").addQuery("moo", val).toString(), "https://foo.com:8080?moo=" + val); + assertEquals(uriBuilder("https://foo.com:8080").addQuery("moo", val).build().toString(), "https://foo.com:8080?moo=" + urlEncode(val, '/', ',')); - assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").query(query).toString(), - "https://api.github.com/repos/user?moo=" + val); - assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").query(query).build().toString(), - "https://api.github.com/repos/user?moo=" + urlEncode(val, '/', ',')); - assertEquals(uriBuilder("https://api.github.com/repos/{user}").query(query).toString(), + assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").addQuery("moo", val).toString(), + "https://api.github.com/repos/user?foo=bar&kung=fu&moo=" + val); + assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").addQuery("moo", val).build().toString(), + "https://api.github.com/repos/user?foo=bar&kung=fu&moo=" + urlEncode(val, '/', ',')); + assertEquals(uriBuilder("https://api.github.com/repos/{user}").addQuery("moo", val).toString(), "https://api.github.com/repos/{user}?moo=" + val); assertEquals( - uriBuilder("https://api.github.com/repos/{user}").query(query).build(templateParams).toASCIIString(), + uriBuilder("https://api.github.com/repos/{user}").addQuery("moo", val).build(templateParams).toASCIIString(), "https://api.github.com/repos/bob?moo=" + urlEncode(val, '/', ',')); } diff --git a/labs/greenqloud-compute/src/test/java/org/jclouds/greenqloud/compute/strategy/GreenQloudComputeReviseParsedImageTest.java b/labs/greenqloud-compute/src/test/java/org/jclouds/greenqloud/compute/strategy/GreenQloudComputeReviseParsedImageTest.java index 7ad0cdfe58..fac32a2966 100644 --- a/labs/greenqloud-compute/src/test/java/org/jclouds/greenqloud/compute/strategy/GreenQloudComputeReviseParsedImageTest.java +++ b/labs/greenqloud-compute/src/test/java/org/jclouds/greenqloud/compute/strategy/GreenQloudComputeReviseParsedImageTest.java @@ -70,7 +70,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("Ubuntu Server 10.04 (64-bit)") .name("Ubuntu Server 10.04.3") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-4e5b842f") .providerId("qmi-4e5b842f") .location(defaultLocation) @@ -89,7 +89,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("Ubuntu Server 11.10 (64-bit)") .name("Ubuntu Server 11.10") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-9ac92558") .providerId("qmi-9ac92558") .location(defaultLocation) @@ -108,7 +108,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("CentOS 5.5 Server 64-bit") .name("CentOS 5.5 Server") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-33a467aa") .providerId("qmi-33a467aa") .location(defaultLocation) @@ -127,7 +127,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("Debian 6.0 (64-bit)") .name("Debian 6.0") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-f2a9d2ba") .providerId("qmi-f2a9d2ba") .location(defaultLocation) @@ -146,7 +146,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("CentOS 6.0 (64-bit)") .name("CentOS 6.0") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-96f82145") .providerId("qmi-96f82145") .location(defaultLocation) @@ -165,7 +165,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("CentOS 6.0 GUI (64-bit)") .name("CentOS 6.0 GUI") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-42e877f6") .providerId("qmi-42e877f6") .location(defaultLocation) @@ -184,7 +184,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("Ubuntu Server 11.04 (64-bit)") .name("Ubuntu Server 11.04") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-eed8cea7") .providerId("qmi-eed8cea7") .location(defaultLocation) @@ -204,7 +204,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("Fedora 16 Server") .name("Fedora 16 Server") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-fa4bdae0") .providerId("qmi-fa4bdae0") .location(defaultLocation) @@ -223,7 +223,7 @@ public class GreenQloudComputeReviseParsedImageTest { .arch("paravirtual").build()) .description("CentOS 5.6 Server GUI 64-bit") .name("CentOS 5.6 GUI") - .defaultCredentials(new LoginCredentials("root", false)) + .defaultCredentials(LoginCredentials.builder().user("root").build()) .id("us-east-1/qmi-93271d32") .providerId("qmi-93271d32") .location(defaultLocation) diff --git a/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java b/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java index 5c71ef8ef2..d2b64fc7ed 100644 --- a/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java +++ b/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java @@ -129,9 +129,11 @@ public class JsonNodeMetadataStore implements NodeMetadataStore { .tags(jsonMetadata.tags) .group(jsonMetadata.group) .userMetadata(jsonMetadata.userMetadata) - .credentials( - new LoginCredentials(jsonMetadata.user, jsonMetadata.password, jsonMetadata.privateKey, - jsonMetadata.authenticateSudo)).build(); + .credentials(LoginCredentials.builder() + .user(jsonMetadata.user) + .privateKey(jsonMetadata.privateKey) + .password(jsonMetadata.password) + .authenticateSudo(jsonMetadata.authenticateSudo).build()).build(); } @Override diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java index b8a561321c..a881cea9fb 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java @@ -146,7 +146,10 @@ public class YamlImage { return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description) .operatingSystem(operatingSystem).status(Image.Status.AVAILABLE) - .defaultCredentials(new LoginCredentials(arg0.username, arg0.credential, null, true)) + .defaultCredentials(LoginCredentials.builder() + .user(arg0.username) + .password(arg0.credential) + .authenticateSudo(true).build()) .build(); } }; diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index e5166f8da0..12e7bb3cb7 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -120,9 +120,10 @@ public class IMachineToNodeMetadata implements Function String guestOsUser = vm.getExtraData(GUEST_OS_USER); String guestOsPassword = vm.getExtraData(GUEST_OS_PASSWORD); - LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true); - nodeMetadataBuilder.credentials(loginCredentials); - + nodeMetadataBuilder.credentials(LoginCredentials.builder() + .user(guestOsUser) + .password(guestOsPassword) + .authenticateSudo(true).build()); return nodeMetadataBuilder.build(); } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/MastersLoadingCache.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/MastersLoadingCache.java index c6a82173f9..81042bc231 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/MastersLoadingCache.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/MastersLoadingCache.java @@ -241,7 +241,10 @@ public class MastersLoadingCache extends AbstractLoadingCache { .iso(IsoSpec.builder().sourcePath(localIsoUrl) .installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())).build()) .network(networkSpec) - .credentials(new LoginCredentials(currentImage.username, currentImage.credential, null, true)).build(); + .credentials(LoginCredentials.builder() + .user(currentImage.username) + .password(currentImage.credential) + .authenticateSudo(true).build()).build(); } @Override diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java index f1d0326e1c..3243dcfd04 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java @@ -181,9 +181,11 @@ public class NodeCreator implements Function