cleaned up code references detected as unnecessary by UEC plugin

This commit is contained in:
Adrian Cole 2013-01-12 12:31:00 -08:00
parent cd401757fc
commit d57197c103
76 changed files with 579 additions and 1063 deletions

View File

@ -80,7 +80,7 @@ public class FirewallClientLiveTest extends BaseCloudStackClientLiveTest {
defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()),
client, jobComplete, virtualMachineRunning); client, jobComplete, virtualMachineRunning);
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {

View File

@ -95,7 +95,7 @@ public class LoadBalancerClientLiveTest extends BaseCloudStackClientLiveTest {
vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network, vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network,
defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()),
client, jobComplete, virtualMachineRunning); client, jobComplete, virtualMachineRunning);
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
} }

View File

@ -181,7 +181,7 @@ public class SecurityGroupClientLiveTest extends BaseCloudStackClientLiveTest {
vm = VirtualMachineClientLiveTest.createVirtualMachineWithSecurityGroupInZone(zone.getId(), vm = VirtualMachineClientLiveTest.createVirtualMachineWithSecurityGroupInZone(zone.getId(),
defaultTemplateOrPreferredInZone(defaultTemplate, client, zone.getId()), group.getId(), client, defaultTemplateOrPreferredInZone(defaultTemplate, client, zone.getId()), group.getId(), client,
jobComplete, virtualMachineRunning); jobComplete, virtualMachineRunning);
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
// ingress port 22 // ingress port 22
checkSSH(HostAndPort.fromParts(vm.getIPAddress(), 22)); checkSSH(HostAndPort.fromParts(vm.getIPAddress(), 22));

View File

@ -284,7 +284,7 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest {
} }
private void conditionallyCheckSSH() { private void conditionallyCheckSSH() {
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
assert HostSpecifier.isValid(vm.getIPAddress()); assert HostSpecifier.isValid(vm.getIPAddress());
if (!InetAddresses2.isPrivateIPAddress(vm.getIPAddress())) { if (!InetAddresses2.isPrivateIPAddress(vm.getIPAddress())) {

View File

@ -66,7 +66,7 @@ public class StaticNATVirtualMachineInNetworkLiveTest extends NATClientLiveTest
vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network, vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network,
defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete, defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete,
virtualMachineRunning); virtualMachineRunning);
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption()) if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
networksDisabled = true; networksDisabled = true;

View File

@ -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) 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)) .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) .status(Image.Status.AVAILABLE)
.build(); .build();
Map<RegionAndName, Image> imageMap = ImmutableMap.of( Map<RegionAndName, Image> imageMap = ImmutableMap.of(
@ -191,12 +191,12 @@ public class EC2TemplateBuilderTest {
final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of( final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) 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)) .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) .status(Image.Status.AVAILABLE)
.build(), .build(),
new ImageBuilder().providerId("normal-image").name("image").id("us-east-1/normal-image").location(location) 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)) .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) .status(Image.Status.AVAILABLE)
.build())); .build()));

View File

@ -67,7 +67,7 @@ public class EC2ImageParserTest {
assertImageEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( assertImageEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem(
new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description(
"137112412989/amzn-ami-0.9.7-beta.i386-ebs").is64Bit(false).build()).description("Amazon") "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) "amzn-ami-0.9.7-beta.i386-ebs").providerId("ami-82e4b5c7").location(defaultLocation)
.userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status( .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status(
Status.AVAILABLE).backendStatus("available").build()); Status.AVAILABLE).backendStatus("available").build());
@ -75,7 +75,7 @@ public class EC2ImageParserTest {
assertImageEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem( assertImageEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem(
new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( 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()) "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( .id("us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").name("amzn-ami-0.9.7-beta.x86_64-S3").location(
defaultLocation) defaultLocation)
.userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status( .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") "amazon/NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10")
.is64Bit(true).build()) .is64Bit(true).build())
.description("Microsoft Windows Server 2008 R2 SP1 Datacenter 64-bit Multi-language AMI provided by Amazon") .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") .id("us-east-1/ami-85457ff1").providerId("ami-85457ff1").name("NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10")
.location(defaultLocation) .location(defaultLocation)
.userMetadata(ImmutableMap.of("owner", "801119661308", "rootDeviceType", "ebs")) .userMetadata(ImmutableMap.of("owner", "801119661308", "rootDeviceType", "ebs"))

View File

@ -237,9 +237,7 @@ public class RunningInstanceToNodeMetadataTest {
} }
protected RunningInstance firstInstanceFromResource(String resource) { protected RunningInstance firstInstanceFromResource(String resource) {
RunningInstance server = Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest return Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest.parseRunningInstances(resource), 0), 0);
.parseRunningInstances(resource), 0), 0);
return server;
} }
protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware, protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware,

View File

@ -71,7 +71,7 @@ public class NovaReviseParsedImageTest {
.build()) .build())
.name("Ubuntu Maverick 10.10 Server 64-bit 20111212") .name("Ubuntu Maverick 10.10 Server 64-bit 20111212")
.description("") .description("")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/ami-000004d6") .id("us-east-1/ami-000004d6")
.providerId("ami-000004d6") .providerId("ami-000004d6")
.location(defaultLocation) .location(defaultLocation)

View File

@ -45,8 +45,8 @@ import com.google.inject.name.Names;
// surefire // surefire
@Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest") @Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest")
public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest { public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest {
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = new ValueOfConfigurationKeyOrNull( ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = Guice.createInjector().getInstance(
Guice.createInjector()); ValueOfConfigurationKeyOrNull.class);
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testIllegalArgumentWhenResourcesEmpty() { public void testIllegalArgumentWhenResourcesEmpty() {
@ -91,16 +91,14 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest
ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null);
ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null);
assertEquals(new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault( assertEquals(
new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(
new AbstractModule() {
@Override protected void configure() {
protected void configure() { bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*");
bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*"); }
} }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList
.<ReferenceType> of(reference1, reference2)), reference2);
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
reference2)), reference2);
} }
@ -109,16 +107,11 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest
ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null);
ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null);
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(new ValueOfConfigurationKeyOrNull( new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(new AbstractModule() {
Guice.createInjector(new AbstractModule() { protected void configure() {
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*");
@Override }
protected void configure() { }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<ReferenceType> alwaysTrue())
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*"); .apply(ImmutableList.<ReferenceType> of(reference1, reference2));
}
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
reference2));
} }
} }

View File

@ -45,8 +45,8 @@ import com.google.inject.name.Names;
// surefire // surefire
@Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest") @Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest")
public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest { public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest {
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = new ValueOfConfigurationKeyOrNull( ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = Guice.createInjector().getInstance(
Guice.createInjector()); ValueOfConfigurationKeyOrNull.class);
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testIllegalArgumentWhenResourcesEmpty() { public void testIllegalArgumentWhenResourcesEmpty() {
@ -91,16 +91,14 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest
ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null);
ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null);
assertEquals(new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault( assertEquals(
new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(
new AbstractModule() {
@Override protected void configure() {
protected void configure() { bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*");
bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*"); }
} }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList
.<ReferenceType> of(reference1, reference2)), reference2);
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
reference2)), reference2);
} }
@ -109,16 +107,11 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest
ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null); ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null);
ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null); ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null);
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(new ValueOfConfigurationKeyOrNull( new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(new AbstractModule() {
Guice.createInjector(new AbstractModule() { protected void configure() {
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*");
@Override }
protected void configure() { }).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<ReferenceType> alwaysTrue())
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*"); .apply(ImmutableList.<ReferenceType> of(reference1, reference2));
}
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
reference2));
} }
} }

View File

@ -86,7 +86,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testWithoutInitThrowsIllegalStateException() { public void testWithoutInitThrowsIllegalStateException() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -153,7 +153,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testWithSudoPassword() { public void testWithSudoPassword() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -206,7 +206,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testDoublecheckStatusInCaseTransientlyWrong() { public void testDoublecheckStatusInCaseTransientlyWrong() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -256,7 +256,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testNotRoot() { public void testNotRoot() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -302,11 +302,10 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
verify(sshClient); verify(sshClient);
} }
public void testBadReturnCode() { public void testBadReturnCode() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("badreturncode").status(Status.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);

View File

@ -57,7 +57,7 @@ public class RunScriptOnNodeUsingSshTest {
} }
}; };
node = createMock(NodeMetadata.class); 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); replay(node);
} }
@ -97,7 +97,7 @@ public class RunScriptOnNodeUsingSshTest {
public void simpleRootTestWithSudoPassword() { public void simpleRootTestWithSudoPassword() {
node = createMock(NodeMetadata.class); 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(); .atLeastOnce();
replay(node); replay(node);
RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"), RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"),

View File

@ -48,19 +48,16 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(new TemplateOptions()); expect(template.getOptions()).andReturn(new TemplateOptions());
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template), expected); assertEquals(fn.apply(template), expected);
verify(template); verify(template, image);
verify(image);
} }
public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() { LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build();
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() {
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -68,19 +65,14 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected)); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template), expected); assertEquals(fn.apply(template), expected);
verify(template); verify(template, image);
verify(image);
} }
public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() { public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() {
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -88,53 +80,40 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
expect(image.getDefaultCredentials()).andReturn(expected); expect(image.getDefaultCredentials()).andReturn(expected);
expect(template.getOptions()).andReturn(new TemplateOptions()); expect(template.getOptions()).andReturn(new TemplateOptions());
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template), expected); assertEquals(fn.apply(template), expected);
verify(template); verify(template, image);
verify(image);
} }
public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() { public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() {
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); 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")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template), expected); assertEquals(fn.apply(template), expected);
verify(template); verify(template, image);
verify(image);
} }
public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() { public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() {
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); 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")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password"));
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template), expected); assertEquals(fn.apply(template), expected);
verify(template); verify(template, image);
verify(image);
} }
} }

View File

@ -51,18 +51,16 @@ public class PrioritizeCredentialsFromTemplateTest {
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(new TemplateOptions()); expect(template.getOptions()).andReturn(new TemplateOptions());
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template, null), expected); assertEquals(fn.apply(template, null), expected);
verify(template); verify(template);
verify(image); verify(image);
} }
public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() { 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); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -71,18 +69,16 @@ public class PrioritizeCredentialsFromTemplateTest {
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(new TemplateOptions()); expect(template.getOptions()).andReturn(new TemplateOptions());
replay(template); replay(template, image);
replay(image);
assertEquals(fn.apply(template, expected), expected); assertEquals(fn.apply(template, expected), expected);
verify(template); verify(template);
verify(image); verify(image);
} }
public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() { 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); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -91,14 +87,12 @@ public class PrioritizeCredentialsFromTemplateTest {
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected)); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));
replay(template); replay(template, image);
replay(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(template);
verify(image); verify(image);
} }
public void testWhenCredentialsNotPresentInImageReturnsCredentialFromTemplateOptionsAndUserFromParameter() { public void testWhenCredentialsNotPresentInImageReturnsCredentialFromTemplateOptionsAndUserFromParameter() {
@ -111,18 +105,16 @@ public class PrioritizeCredentialsFromTemplateTest {
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
replay(template); replay(template, image);
replay(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(template);
verify(image); verify(image);
} }
public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() { 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); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -131,14 +123,12 @@ public class PrioritizeCredentialsFromTemplateTest {
expect(image.getDefaultCredentials()).andReturn(expected); expect(image.getDefaultCredentials()).andReturn(expected);
expect(template.getOptions()).andReturn(new TemplateOptions()); expect(template.getOptions()).andReturn(new TemplateOptions());
replay(template); replay(template, image);
replay(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(template);
verify(image); verify(image);
} }
public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptionsAndNotParameter() { public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptionsAndNotParameter() {
@ -148,36 +138,31 @@ public class PrioritizeCredentialsFromTemplateTest {
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); 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")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
replay(template); replay(template, image);
replay(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);
verify(template, image);
} }
public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() { 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); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); 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")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password"));
replay(template); replay(template, image);
replay(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(template);
verify(image); verify(image);
} }
} }

View File

@ -39,12 +39,12 @@ import com.google.common.collect.ImmutableMap;
*/ */
@Test(groups = "unit", testName = "ReturnCredentialsBoundToImageTest") @Test(groups = "unit", testName = "ReturnCredentialsBoundToImageTest")
public class ReturnCredentialsBoundToImageTest { public class ReturnCredentialsBoundToImageTest {
LoginCredentials creds = LoginCredentials.builder().user("ubuntu").password("foo").build();
public void testDefaultIsToReturnConfiguredCredential() { public void testDefaultIsToReturnConfiguredCredential() {
Image image = createMock(Image.class); Image image = createMock(Image.class);
replay(image); replay(image);
LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false);
assertEquals(new ReturnCredentialsBoundToImage(creds, ImmutableMap.<String, Credentials> of(), ImmutableMap assertEquals(new ReturnCredentialsBoundToImage(creds, ImmutableMap.<String, Credentials> of(), ImmutableMap
.<OsFamily, LoginCredentials> of()).apply(image), creds); .<OsFamily, LoginCredentials> of()).apply(image), creds);
@ -57,7 +57,6 @@ public class ReturnCredentialsBoundToImageTest {
expect(image.getId()).andReturn("1").times(2); expect(image.getId()).andReturn("1").times(2);
replay(image); replay(image);
LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false);
assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap.<String, Credentials> of("image#1", creds), assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap.<String, Credentials> of("image#1", creds),
ImmutableMap.<OsFamily, LoginCredentials> of()).apply(image), creds); ImmutableMap.<OsFamily, LoginCredentials> of()).apply(image), creds);

View File

@ -124,7 +124,7 @@ public final class Fallbacks {
} }
} }
public static final class EmptyListOnNotFoundOr404 implements FutureFallback<ImmutableList<Object>> { public static final class EmptyListOnNotFoundOr404 implements FutureFallback<ImmutableList<Object>> { // NO_UCD (unused code)
@Override @Override
public ListenableFuture<ImmutableList<Object>> create(Throwable t) { public ListenableFuture<ImmutableList<Object>> create(Throwable t) {
return valOnNotFoundOr404(ImmutableList.of(), checkNotNull(t, "throwable")); return valOnNotFoundOr404(ImmutableList.of(), checkNotNull(t, "throwable"));
@ -145,7 +145,7 @@ public final class Fallbacks {
} }
} }
public static final class EmptyMultimapOnNotFoundOr404 implements FutureFallback<ImmutableMultimap<Object, Object>> { public static final class EmptyMultimapOnNotFoundOr404 implements FutureFallback<ImmutableMultimap<Object, Object>> { // NO_UCD (unused code)
@Override @Override
public ListenableFuture<ImmutableMultimap<Object, Object>> create(Throwable t) { public ListenableFuture<ImmutableMultimap<Object, Object>> create(Throwable t) {
return valOnNotFoundOr404(ImmutableMultimap.of(), checkNotNull(t, "throwable")); return valOnNotFoundOr404(ImmutableMultimap.of(), checkNotNull(t, "throwable"));

View File

@ -48,7 +48,7 @@ public interface View {
* *
* ex. * ex.
* <pre> * <pre>
* RestContext<NovaClient, NovaAsyncClient> backendApi = computeContext.unwrap(NovaApiMetadata.CONTEXT_TOKEN); * RestContext<NovaApi, NovaAsyncApi> backendApi = computeContext.unwrap(NovaApiMetadata.CONTEXT_TOKEN);
* </pre> * </pre>
* @param type * @param type
* the type of the context to be returned. The backend context must * the type of the context to be returned. The backend context must
@ -61,13 +61,6 @@ public interface View {
*/ */
<C extends Context> C unwrap(TypeToken<C> type) throws IllegalArgumentException; <C extends Context> C unwrap(TypeToken<C> type) throws IllegalArgumentException;
/**
* shortcut for {@code unwrap(TypeToken.of(clazz))}
*
* @see #unwrap(TypeToken)
*/
<C extends Context> C unwrap(Class<C> clazz) throws IllegalArgumentException;
/** /**
* shortcut for {@code unwrap(getWrappedType())} * shortcut for {@code unwrap(getWrappedType())}
* *

View File

@ -41,7 +41,7 @@ import com.google.common.reflect.TypeToken;
*/ */
public class Apis { public class Apis {
public static enum IdFunction implements Function<ApiMetadata, String> { private static enum IdFunction implements Function<ApiMetadata, String> {
INSTANCE; INSTANCE;
@Override @Override

View File

@ -79,22 +79,21 @@ public abstract class BaseApiMetadata implements ApiMetadata {
public static abstract class Builder<T extends Builder<T>> implements ApiMetadata.Builder<T> { public static abstract class Builder<T extends Builder<T>> implements ApiMetadata.Builder<T> {
protected abstract T self(); protected abstract T self();
protected String id; private String id;
protected String name; private String name;
protected Set<TypeToken<? extends View>> views = ImmutableSet.of(); private Set<TypeToken<? extends View>> views = ImmutableSet.of();
protected String endpointName = "https endpoint"; private String endpointName = "https endpoint";
protected String identityName; private String identityName;
protected Optional<String> credentialName = Optional.absent(); private Optional<String> credentialName = Optional.absent();
protected String version = ""; private String version = "";
protected Optional<String> buildVersion = Optional.of(""); private Optional<String> buildVersion = Optional.of("");
protected Optional<String> defaultEndpoint = Optional.absent(); private Optional<String> defaultEndpoint = Optional.absent();
protected Optional<String> defaultIdentity = Optional.absent(); private Optional<String> defaultIdentity = Optional.absent();
protected Optional<String> defaultCredential = Optional.absent(); private Optional<String> defaultCredential = Optional.absent();
protected Properties defaultProperties = BaseApiMetadata.defaultProperties(); private Properties defaultProperties = BaseApiMetadata.defaultProperties();
protected URI documentation; private URI documentation;
// private TypeToken<? extends Context> context = TypeToken.of(Context.class);
protected TypeToken<? extends Context> context = TypeToken.of(Context.class); private Set<Class<? extends Module>> defaultModules = ImmutableSet.of();
protected Set<Class<? extends Module>> defaultModules = ImmutableSet.of();
/** /**
* {@inheritDoc} * {@inheritDoc}
@ -265,21 +264,21 @@ public abstract class BaseApiMetadata implements ApiMetadata {
} }
} }
protected final String id; private final String id;
protected final String name; private final String name;
protected final Set<TypeToken<? extends View>> views; private final Set<TypeToken<? extends View>> views;
protected final String endpointName; private final String endpointName;
protected final String identityName; private final String identityName;
protected final Optional<String> credentialName; private final Optional<String> credentialName;
protected final String version; private final String version;
protected final Optional<String> buildVersion; private final Optional<String> buildVersion;
protected final Optional<String> defaultEndpoint; private final Optional<String> defaultEndpoint;
protected final Optional<String> defaultIdentity; private final Optional<String> defaultIdentity;
protected final Optional<String> defaultCredential; private final Optional<String> defaultCredential;
protected final Properties defaultProperties; private final Properties defaultProperties;
protected final URI documentation; private final URI documentation;
protected final TypeToken<? extends Context> context; private final TypeToken<? extends Context> context;
protected final Set<Class<? extends Module>> defaultModules; private final Set<Class<? extends Module>> defaultModules;
protected BaseApiMetadata(Builder<?> builder) { protected BaseApiMetadata(Builder<?> builder) {
this(builder.id, builder.name, builder.views, builder.endpointName, builder.identityName, builder.credentialName, 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); builder.defaultModules);
} }
public BaseApiMetadata(String id, String name, Set<TypeToken<? extends View>> views, String endpointName, String identityName, protected BaseApiMetadata(String id, String name, Set<TypeToken<? extends View>> views, String endpointName, String identityName, // NO_UCD (use private)
Optional<String> credentialName, String version, Optional<String> buildVersion, Optional<String> credentialName, String version, Optional<String> buildVersion,
Optional<String> defaultEndpoint, Optional<String> defaultIdentity, Optional<String> defaultCredential, Optional<String> defaultEndpoint, Optional<String> defaultIdentity, Optional<String> defaultCredential,
Properties defaultProperties, URI documentation, TypeToken<? extends Context> context, Properties defaultProperties, URI documentation, TypeToken<? extends Context> context,

View File

@ -21,7 +21,6 @@ package org.jclouds.cache;
import java.util.Map; import java.util.Map;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -56,24 +55,4 @@ public abstract class ForwardingCacheLoader<K, V> extends CacheLoader<K, V> {
public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception { public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
return delegate().loadAll(keys); 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<K, V> extends ForwardingCacheLoader<K, V> {
private final CacheLoader<K, V> delegate;
protected SimpleForwardingCacheLoader(CacheLoader<K, V> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
protected final CacheLoader<K, V> delegate() {
return delegate;
}
}
} }

View File

@ -85,9 +85,9 @@ public class RetryingCacheLoaderDecorator<K, V> {
} }
public static class OnThrowableBuilder<K, V> { public static class OnThrowableBuilder<K, V> {
Class<? extends Throwable> retryableThrowable; private Class<? extends Throwable> retryableThrowable;
protected OnThrowableBuilder(Class<? extends Throwable> retryableThrowable) { private OnThrowableBuilder(Class<? extends Throwable> retryableThrowable) {
this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable"); this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable");
} }
@ -107,7 +107,7 @@ public class RetryingCacheLoaderDecorator<K, V> {
private int maxTries = 5; private int maxTries = 5;
private final Class<? extends Throwable> retryableThrowable; private final Class<? extends Throwable> retryableThrowable;
protected BackoffExponentiallyAndRetryOnThrowableCacheLoaderDecorator(Class<? extends Throwable> retryableThrowable) { private BackoffExponentiallyAndRetryOnThrowableCacheLoaderDecorator(Class<? extends Throwable> retryableThrowable) {
this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable"); this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable");
} }

View File

@ -81,7 +81,7 @@ class BackoffExponentiallyAndRetryOnThrowableCallable<T> extends ForwardingObjec
throw currentException; 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)); long delayMs = (long) (period * Math.pow(failureCount, pow));
delayMs = delayMs > maxPeriod ? maxPeriod : delayMs; delayMs = delayMs > maxPeriod ? maxPeriod : delayMs;
try { try {

View File

@ -25,13 +25,10 @@ import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects; import com.google.common.base.Objects;
public abstract class AbstractMapEntry<K, V> implements Entry<K, V> { abstract class AbstractMapEntry<K, V> implements Entry<K, V> {
public abstract K getKey(); @Override
public V setValue(V value) { // NO_UCD
public abstract V getValue();
public V setValue(V value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -51,9 +48,6 @@ public abstract class AbstractMapEntry<K, V> implements Entry<K, V> {
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
} }
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Override @Override
public String toString() { public String toString() {
return getKey() + "=" + getValue(); return getKey() + "=" + getValue();

View File

@ -53,13 +53,13 @@ public class AdvanceUntilEmptyIterable<E> extends FluentIterable<FluentIterable<
return iterator; return iterator;
} }
static class AdvanceUntilEmptyIterator<E> extends AbstractIterator<FluentIterable<E>> { private static class AdvanceUntilEmptyIterator<E> extends AbstractIterator<FluentIterable<E>> {
private final Supplier<FluentIterable<E>> nextIterable; private final Supplier<FluentIterable<E>> nextIterable;
private transient FluentIterable<E> current; private transient FluentIterable<E> current;
private transient boolean unread = true; private transient boolean unread = true;
AdvanceUntilEmptyIterator(Supplier<FluentIterable<E>> nextIterable) { private AdvanceUntilEmptyIterator(Supplier<FluentIterable<E>> nextIterable) {
this.nextIterable = checkNotNull(nextIterable, "next iterable"); this.nextIterable = checkNotNull(nextIterable, "next iterable");
} }

View File

@ -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 <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Adrian Cole
*/
@Beta
public abstract class ForwardingIterableWithMarker<T> extends IterableWithMarker<T> {
/** Constructor for use by subclasses. */
protected ForwardingIterableWithMarker() {
}
protected abstract IterableWithMarker<T> delegate();
@Override
public Iterator<T> iterator() {
return delegate().iterator();
}
@Override
public Optional<Object> nextMarker() {
return delegate().nextMarker();
}
}

View File

@ -39,8 +39,8 @@ import com.google.common.io.InputSupplier;
* *
*/ */
public class InputSupplierMap<K, V> extends AbstractMap<K, V> { public class InputSupplierMap<K, V> extends AbstractMap<K, V> {
final Map<K, InputSupplier<V>> toMap; private final Map<K, InputSupplier<V>> toMap;
final Function<V, InputSupplier<V>> putFunction; private final Function<V, InputSupplier<V>> putFunction;
public InputSupplierMap(Map<K, InputSupplier<V>> toMap, Function<V, InputSupplier<V>> putFunction) { public InputSupplierMap(Map<K, InputSupplier<V>> toMap, Function<V, InputSupplier<V>> putFunction) {
this.toMap = checkNotNull(toMap); this.toMap = checkNotNull(toMap);
@ -91,10 +91,9 @@ public class InputSupplierMap<K, V> extends AbstractMap<K, V> {
@Override @Override
public Set<Entry<K, V>> entrySet() { public Set<Entry<K, V>> entrySet() {
return new EntrySet(); return new EntrySet();
} }
class EntrySet extends AbstractSet<Entry<K, V>> { private class EntrySet extends AbstractSet<Entry<K, V>> {
@Override @Override
public int size() { public int size() {
return InputSupplierMap.this.size(); return InputSupplierMap.this.size();

View File

@ -86,7 +86,20 @@ public class IterableWithMarkers {
public Optional<Object> nextMarker() { public Optional<Object> nextMarker() {
return marker; return marker;
} }
} }
private static abstract class ForwardingIterableWithMarker<T> extends IterableWithMarker<T> {
protected abstract IterableWithMarker<T> delegate();
@Override
public Iterator<T> iterator() {
return delegate().iterator();
}
@Override
public Optional<Object> nextMarker() {
return delegate().nextMarker();
}
}
} }

View File

@ -36,16 +36,6 @@ import com.google.common.collect.ImmutableSet;
@Beta @Beta
public class PagedIterables { public class PagedIterables {
@SuppressWarnings("rawtypes")
public static final PagedIterable EMPTY = new PagedIterable() {
@Override
public Iterator<IterableWithMarker> iterator() {
return ImmutableSet.of(IterableWithMarkers.EMPTY).iterator();
}
};
/** /**
* @param only * @param only
* the only page of data * the only page of data
@ -154,7 +144,7 @@ public class PagedIterables {
* @return iterable current data which continues if the user iterates beyond * @return iterable current data which continues if the user iterates beyond
* the first page * the first page
*/ */
public static <T> Iterator<IterableWithMarker<T>> advancingIterator(IterableWithMarker<T> initial, private static <T> Iterator<IterableWithMarker<T>> advancingIterator(IterableWithMarker<T> initial,
Function<Object, IterableWithMarker<T>> markerToNext) { Function<Object, IterableWithMarker<T>> markerToNext) {
if (!initial.nextMarker().isPresent()) { if (!initial.nextMarker().isPresent()) {
return ImmutableSet.of(initial).iterator(); return ImmutableSet.of(initial).iterator();

View File

@ -36,9 +36,9 @@ import com.google.common.base.Function;
* *
*/ */
public class TransformingMap<K, V1, V2> extends AbstractMap<K, V2> { public class TransformingMap<K, V1, V2> extends AbstractMap<K, V2> {
final Map<K, V1> fromMap; private final Map<K, V1> fromMap;
final Function<? super V1, V2> getFunction; private final Function<? super V1, V2> getFunction;
final Function<? super V2, V1> putFunction; private final Function<? super V2, V1> putFunction;
public TransformingMap(Map<K, V1> fromMap, Function<? super V1, V2> getFunction, Function<? super V2, V1> putFunction) { public TransformingMap(Map<K, V1> fromMap, Function<? super V1, V2> getFunction, Function<? super V2, V1> putFunction) {
this.fromMap = checkNotNull(fromMap); this.fromMap = checkNotNull(fromMap);
@ -85,7 +85,7 @@ public class TransformingMap<K, V1, V2> extends AbstractMap<K, V2> {
} }
class EntrySet extends AbstractSet<Entry<K, V2>> { private class EntrySet extends AbstractSet<Entry<K, V2>> {
@Override @Override
public int size() { public int size() {
return TransformingMap.this.size(); return TransformingMap.this.size();

View File

@ -19,7 +19,6 @@
package org.jclouds.concurrent; package org.jclouds.concurrent;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -30,45 +29,23 @@ import java.util.concurrent.TimeUnit;
* @author kimchy (shay.banon) * @author kimchy (shay.banon)
*/ */
public class DynamicExecutors { 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 <tt>execute</tt> 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 <tt>max</tt> threads will be created. Threads that
* have not been used for a <tt>keepAlive</tt> 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
* <tt>min</tt> 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 * Creates a thread pool, same as in {@link #newScalingThreadPool(int, int, long)}, using the provided ThreadFactory
* provided ThreadFactory to create new threads when needed. * to create new threads when needed.
* *
* @param min * @param min
* the number of threads to keep in the pool, even if they are idle. * the number of threads to keep in the pool, even if they are idle.
* @param max * @param max
* the maximum number of threads to allow in the pool. * the maximum number of threads to allow in the pool.
* @param keepAliveTime * @param keepAliveTime
* when the number of threads is greater than the min, this is the maximum time that * when the number of threads is greater than the min, this is the maximum time that excess idle threads
* excess idle threads will wait for new tasks before terminating (in milliseconds). * will wait for new tasks before terminating (in milliseconds).
* @param threadFactory * @param threadFactory
* the factory to use when creating new threads. * the factory to use when creating new threads.
* @return the newly created thread pool * @return the newly created thread pool
*/ */
public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime, public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime, ThreadFactory threadFactory) {
ThreadFactory threadFactory) {
DynamicThreadPoolExecutor.DynamicQueue<Runnable> queue = new DynamicThreadPoolExecutor.DynamicQueue<Runnable>(); DynamicThreadPoolExecutor.DynamicQueue<Runnable> queue = new DynamicThreadPoolExecutor.DynamicQueue<Runnable>();
ThreadPoolExecutor executor = new DynamicThreadPoolExecutor(min, max, keepAliveTime, ThreadPoolExecutor executor = new DynamicThreadPoolExecutor(min, max, keepAliveTime,
TimeUnit.MILLISECONDS, queue, threadFactory); TimeUnit.MILLISECONDS, queue, threadFactory);
@ -77,128 +54,6 @@ public class DynamicExecutors {
return executor; return executor;
} }
/**
* Creates a thread pool similar to that constructed by
* {@link #newScalingThreadPool(int, int, long)}, but blocks the call to <tt>execute</tt> if the
* queue has reached it's capacity, and all <tt>max</tt> threads are busy handling requests.
* <p/>
* 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<Runnable> queue = new DynamicThreadPoolExecutor.DynamicQueue<Runnable>(
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:
* <tt>Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY</tt>;
* <p/>
* 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:
* <tt>Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY</tt>;
* <p/>
* 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
* <tt>Thread.MIN_PRIORITY, Thread.NORM_PRIORITY</tt> 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. * Cannot instantiate.
*/ */

View File

@ -17,23 +17,23 @@
* under the License. * under the License.
*/ */
/* /*
* Licensed to Elastic Search and Shay Banon under one * Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this * regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the * file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance * "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at * with the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.jclouds.concurrent; package org.jclouds.concurrent;
@ -47,140 +47,138 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
* An {@link ExecutorService} that executes each submitted task using one of * An {@link ExecutorService} that executes each submitted task using one of possibly several pooled threads, normally
* possibly several pooled threads, normally configured using * configured using {@link DynamicExecutors} factory methods.
* {@link DynamicExecutors} factory methods. *
* * @author kimchy (shay.banon)
* @author kimchy (shay.banon) */
*/ class DynamicThreadPoolExecutor extends ThreadPoolExecutor {
public class DynamicThreadPoolExecutor extends ThreadPoolExecutor { /**
/** * number of threads that are actively executing tasks
* number of threads that are actively executing tasks */
*/ private final AtomicInteger activeCount = new AtomicInteger();
private final AtomicInteger activeCount = new AtomicInteger();
public DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); }
}
@Override public int getActiveCount() { @Override
return activeCount.get(); public int getActiveCount() {
} return activeCount.get();
}
@Override protected void beforeExecute(Thread t, Runnable r) { @Override
activeCount.incrementAndGet(); protected void beforeExecute(Thread t, Runnable r) {
} activeCount.incrementAndGet();
}
@Override protected void afterExecute(Runnable r, Throwable t) { @Override
activeCount.decrementAndGet(); protected void afterExecute(Runnable r, Throwable t) {
} activeCount.decrementAndGet();
}
/** /**
* Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It * Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It is well suited for handoff designs, in
* is well suited for handoff designs, in which a tasks is only queued if there * which a tasks is only queued if there is an available thread to pick it up.
* is an available thread to pick it up. * <p/>
* <p/> * This queue is correlated with a thread-pool, and allows insertions to the queue only if there is a free thread
* This queue is correlated with a thread-pool, and allows insertions to the * that can poll this task. Otherwise, the task is rejected and the decision is left up to one of the
* queue only if there is a free thread that can poll this task. Otherwise, the * {@link RejectedExecutionHandler} policies:
* task is rejected and the decision is left up to one of the * <ol>
* {@link RejectedExecutionHandler} policies: * <li> {@link ForceQueuePolicy} - forces the queue to accept the rejected task.</li>
* <ol> * <li> {@link TimedBlockingPolicy} - waits for a given time for the task to be executed.</li>
* <li> {@link ForceQueuePolicy} - forces the queue to accept the rejected task. </li> * </ol>
* <li> {@link TimedBlockingPolicy} - waits for a given time for the task to be *
* executed.</li> * @author kimchy (Shay Banon)
* </ol> */
* static class DynamicQueue<E> extends LinkedBlockingQueue<E> {
* @author kimchy (Shay Banon) private static final long serialVersionUID = 1L;
*/
public static class DynamicQueue<E> extends LinkedBlockingQueue<E> {
/** /**
* The executor this Queue belongs to * The executor this Queue belongs to
*/ */
private transient ThreadPoolExecutor executor; private transient ThreadPoolExecutor executor;
/** /**
* Creates a <tt>DynamicQueue</tt> with a capacity of * Creates a <tt>DynamicQueue</tt> with a capacity of {@link Integer#MAX_VALUE}.
* {@link Integer#MAX_VALUE}. */
*/ public DynamicQueue() {
public DynamicQueue() { super();
super(); }
}
/** /**
* Creates a <tt>DynamicQueue</tt> with the given (fixed) capacity. * Creates a <tt>DynamicQueue</tt> with the given (fixed) capacity.
* *
* @param capacity the capacity of this queue. * @param capacity
*/ * the capacity of this queue.
public DynamicQueue(int capacity) { */
super(capacity); DynamicQueue(int capacity) {
} super(capacity);
}
/** /**
* Sets the executor this queue belongs to. * Sets the executor this queue belongs to.
*/ */
public void setThreadPoolExecutor(ThreadPoolExecutor executor) { public void setThreadPoolExecutor(ThreadPoolExecutor executor) {
this.executor = executor; this.executor = executor;
} }
/** /**
* Inserts the specified element at the tail of this queue if there is at * Inserts the specified element at the tail of this queue if there is at least one available thread to run the
* least one available thread to run the current task. If all pool threads * current task. If all pool threads are actively busy, it rejects the offer.
* are actively busy, it rejects the offer. *
* * @param o
* @param o the element to add. * the element to add.
* @return <tt>true</tt> if it was possible to add the element to this * @return <tt>true</tt> if it was possible to add the element to this queue, else <tt>false</tt>
* queue, else <tt>false</tt> * @see ThreadPoolExecutor#execute(Runnable)
* @see ThreadPoolExecutor#execute(Runnable) */
*/ @Override
@Override public boolean offer(E o) {
public boolean offer(E o) { int allWorkingThreads = executor.getActiveCount() + super.size();
int allWorkingThreads = executor.getActiveCount() + super.size(); return allWorkingThreads < executor.getPoolSize() && super.offer(o);
return allWorkingThreads < executor.getPoolSize() && super.offer(o); }
} }
}
/** /**
* A handler for rejected tasks that adds the specified element to this queue, * A handler for rejected tasks that adds the specified element to this queue, waiting if necessary for space to
* waiting if necessary for space to become available. * become available.
*/ */
public static class ForceQueuePolicy implements RejectedExecutionHandler { static class ForceQueuePolicy implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try { try {
executor.getQueue().put(r); executor.getQueue().put(r);
} catch (InterruptedException e) { } catch (InterruptedException e) {
//should never happen since we never wait // should never happen since we never wait
throw new RejectedExecutionException(e); throw new RejectedExecutionException(e);
} }
} }
} }
/** /**
* A handler for rejected tasks that inserts the specified element into this * A handler for rejected tasks that inserts the specified element into this queue, waiting if necessary up to the
* queue, waiting if necessary up to the specified wait time for space to become * specified wait time for space to become available.
* available. */
*/ static class TimedBlockingPolicy implements RejectedExecutionHandler {
public static class TimedBlockingPolicy implements RejectedExecutionHandler { private final long waitTime;
private final long waitTime;
/** /**
* @param waitTime wait time in milliseconds for space to become available. * @param waitTime
*/ * wait time in milliseconds for space to become available.
public TimedBlockingPolicy(long waitTime) { */
this.waitTime = waitTime; TimedBlockingPolicy(long waitTime) {
} this.waitTime = waitTime;
}
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try { try {
boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS); boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS);
if (!successful) if (!successful)
throw new RejectedExecutionException("Rejected execution after waiting " throw new RejectedExecutionException("Rejected execution after waiting " + waitTime + " ms for task ["
+ waitTime + " ms for task [" + r.getClass() + "] to be executed."); + r.getClass() + "] to be executed.");
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RejectedExecutionException(e); throw new RejectedExecutionException(e);
} }
} }
} }
} }

View File

@ -56,8 +56,6 @@ import com.google.inject.Inject;
*/ */
@Beta @Beta
public class FutureIterables { public class FutureIterables {
@Resource
private static Logger logger = Logger.CONSOLE;
@Inject(optional = true) @Inject(optional = true)
@Named(Constants.PROPERTY_MAX_RETRIES) @Named(Constants.PROPERTY_MAX_RETRIES)
@ -70,16 +68,6 @@ public class FutureIterables {
@Inject(optional = true) @Inject(optional = true)
private static BackoffLimitedRetryHandler retryHandler = BackoffLimitedRetryHandler.INSTANCE; private static BackoffLimitedRetryHandler retryHandler = BackoffLimitedRetryHandler.INSTANCE;
public static <F, T> Iterable<T> transformParallel(final Iterable<F> fromIterable,
final Function<? super F, Future<? extends T>> function) {
return transformParallel(fromIterable, function, org.jclouds.concurrent.MoreExecutors.sameThreadExecutor(), null);
}
public static <F, T> Iterable<T> transformParallel(final Iterable<F> fromIterable,
final Function<? super F, Future<? extends T>> function, ExecutorService exec, @Nullable Long maxTime) {
return transformParallel(fromIterable, function, exec, maxTime, logger, "transforming");
}
public static <F, T> Iterable<T> transformParallel(final Iterable<F> fromIterable, public static <F, T> Iterable<T> transformParallel(final Iterable<F> fromIterable,
final Function<? super F, Future<? extends T>> function, ExecutorService exec, @Nullable Long maxTime, Logger logger, final Function<? super F, Future<? extends T>> function, ExecutorService exec, @Nullable Long maxTime, Logger logger,
String logPrefix) { String logPrefix) {
@ -113,8 +101,8 @@ public class FutureIterables {
} }
//make sure we propagate any authorization exception so that we don't lock out accounts //make sure we propagate any authorization exception so that we don't lock out accounts
if (exceptions.size() > 0) if (exceptions.size() > 0)
return propagateAuthorizationOrOriginalException(new TransformParallelException((Map) responses, exceptions, return propagateAuthorizationOrOriginalException(new TransformParallelException(Map.class.cast(responses),
logPrefix)); exceptions, logPrefix));
return unwrap(responses.values()); return unwrap(responses.values());
} }
@ -180,7 +168,7 @@ public class FutureIterables {
return errorMap; return errorMap;
} }
public static <T> Iterable<T> unwrap(Iterable<Future<? extends T>> values) { private static <T> Iterable<T> unwrap(Iterable<Future<? extends T>> values) {
return transform(values, new Function<Future<? extends T>, T>() { return transform(values, new Function<Future<? extends T>, T>() {
@Override @Override
public T apply(Future<? extends T> from) { public T apply(Future<? extends T> from) {
@ -211,9 +199,4 @@ public class FutureIterables {
return String.format("%s, completed: %d/%d, errors: %d, rate: %dms/op", prefix, complete, size, errors, return String.format("%s, completed: %d/%d, errors: %d, rate: %dms/op", prefix, complete, size, errors,
(long) ((System.currentTimeMillis() - start) / ((double) size))); (long) ((System.currentTimeMillis() - start) / ((double) size)));
} }
protected static boolean timeOut(long start, Long maxTime) {
return maxTime != null ? System.currentTimeMillis() < start + maxTime : false;
}
} }

View File

@ -48,7 +48,7 @@ public class Futures {
private final Future<T> delegate; private final Future<T> delegate;
private final ExecutionList executionList; private final ExecutionList executionList;
public CallGetAndRunExecutionList(Future<T> delegate, ExecutionList executionList) { CallGetAndRunExecutionList(Future<T> delegate, ExecutionList executionList) {
this.delegate = checkNotNull(delegate, "delegate"); this.delegate = checkNotNull(delegate, "delegate");
this.executionList = checkNotNull(executionList, "executionList"); 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 // note that this is done so that we can operate in Google AppEngine which
// restricts thread creation // restricts thread creation
// * to allow us to print debug info about what the delegate was doing // * to allow us to print debug info about what the delegate was doing
public static class FutureListener<T> { private static class FutureListener<T> {
final ExecutorService adapterExecutor; private final ExecutorService adapterExecutor;
// The execution list to hold our listeners. // The execution list to hold our listeners.
private final ExecutionList executionList = new ExecutionList(); private final ExecutionList executionList = new ExecutionList();
@ -98,7 +98,7 @@ public class Futures {
// The delegate future. // The delegate future.
private final Future<T> delegate; private final Future<T> delegate;
static <T> FutureListener<T> create(Future<T> delegate, ExecutorService adapterExecutor) { private static <T> FutureListener<T> create(Future<T> delegate, ExecutorService adapterExecutor) {
return new FutureListener<T>(delegate, adapterExecutor); return new FutureListener<T>(delegate, adapterExecutor);
} }
@ -107,7 +107,7 @@ public class Futures {
this.adapterExecutor = checkNotNull(adapterExecutor, "adapterExecutor"); this.adapterExecutor = checkNotNull(adapterExecutor, "adapterExecutor");
} }
public void addListener(Runnable listener, Executor exec) { private void addListener(Runnable listener, Executor exec) {
executionList.add(listener, exec); executionList.add(listener, exec);
// When a listener is first added, we run a task that will wait for // When a listener is first added, we run a task that will wait for
@ -123,19 +123,15 @@ public class Futures {
} }
} }
Future<T> getFuture() { private Future<T> getFuture() {
return delegate; return delegate;
} }
ExecutorService getExecutor() {
return adapterExecutor;
}
} }
public static class ListenableFutureAdapter<T> extends ForwardingFuture<T> implements ListenableFuture<T> { private static class ListenableFutureAdapter<T> extends ForwardingFuture<T> implements ListenableFuture<T> {
final FutureListener<T> futureListener; private final FutureListener<T> futureListener;
static <T> ListenableFutureAdapter<T> create(Future<T> future, ExecutorService executor) { private static <T> ListenableFutureAdapter<T> create(Future<T> future, ExecutorService executor) {
return new ListenableFutureAdapter<T>(future, executor); return new ListenableFutureAdapter<T>(future, executor);
} }
@ -152,20 +148,19 @@ public class Futures {
public void addListener(Runnable listener, Executor exec) { public void addListener(Runnable listener, Executor exec) {
futureListener.addListener(listener, exec); futureListener.addListener(listener, exec);
} }
} }
public static class LazyListenableFutureFunctionAdapter<I, O> extends ForwardingObject implements private static class LazyListenableFutureFunctionAdapter<I, O> extends ForwardingObject implements
ListenableFuture<O> { ListenableFuture<O> {
private final FutureListener<I> futureListener; private final FutureListener<I> futureListener;
private final Function<? super I, ? extends O> function; private final Function<? super I, ? extends O> function;
static <I, O> LazyListenableFutureFunctionAdapter<I, O> create(Future<I> future, private static <I, O> LazyListenableFutureFunctionAdapter<I, O> create(Future<I> future,
Function<? super I, ? extends O> function, ExecutorService executor) { Function<? super I, ? extends O> function, ExecutorService executor) {
return new LazyListenableFutureFunctionAdapter<I, O>(future, function, executor); return new LazyListenableFutureFunctionAdapter<I, O>(future, function, executor);
} }
static <I, O> LazyListenableFutureFunctionAdapter<I, O> create(FutureListener<I> futureListener, private static <I, O> LazyListenableFutureFunctionAdapter<I, O> create(FutureListener<I> futureListener,
Function<? super I, ? extends O> function) { Function<? super I, ? extends O> function) {
return new LazyListenableFutureFunctionAdapter<I, O>(futureListener, function); return new LazyListenableFutureFunctionAdapter<I, O>(futureListener, function);
} }

View File

@ -29,6 +29,7 @@ import com.google.common.collect.Iterables;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@SuppressWarnings("serial")
public final class TransformParallelException extends RuntimeException { public final class TransformParallelException extends RuntimeException {
private final Map<?, Future<?>> success; private final Map<?, Future<?>> success;

View File

@ -23,12 +23,12 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
public class DescribedFuture<T> implements Future<T> { class DescribedFuture<T> implements Future<T> {
protected final Future<T> delegate; protected final Future<T> delegate;
private final String description; private final String description;
private StackTraceElement[] submissionTrace; private StackTraceElement[] submissionTrace;
public DescribedFuture(Future<T> delegate, String description, StackTraceElement[] submissionTrace) { DescribedFuture(Future<T> delegate, String description, StackTraceElement[] submissionTrace) {
this.delegate = delegate; this.delegate = delegate;
this.description = description; this.description = description;
this.submissionTrace = submissionTrace; this.submissionTrace = submissionTrace;

View File

@ -19,6 +19,7 @@
package org.jclouds.concurrent.config; package org.jclouds.concurrent.config;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.concurrent.config.ExecutorServiceModule.getStackTraceHere;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -86,18 +87,18 @@ public class DescribingExecutorService implements ExecutorService {
@Override @Override
public <T> Future<T> submit(Callable<T> task) { public <T> Future<T> submit(Callable<T> task) {
return new DescribedFuture<T>(delegate.submit(task), task.toString(), ExecutorServiceModule.getStackTraceHere()); return new DescribedFuture<T>(delegate.submit(task), task.toString(), getStackTraceHere());
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
@Override @Override
public Future<?> submit(Runnable task) { 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 @Override
public <T> Future<T> submit(Runnable task, T result) { public <T> Future<T> submit(Runnable task, T result) { // NO_UCD
return new DescribedFuture<T>(delegate.submit(task, result), task.toString(), ExecutorServiceModule.getStackTraceHere()); return new DescribedFuture<T>(delegate.submit(task, result), task.toString(), getStackTraceHere());
} }
@Override @Override

View File

@ -18,6 +18,8 @@
*/ */
package org.jclouds.concurrent.config; 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 static org.jclouds.concurrent.DynamicExecutors.newScalingThreadPool;
import java.io.Closeable; import java.io.Closeable;
@ -32,13 +34,11 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.concurrent.MoreExecutors; import org.jclouds.concurrent.MoreExecutors;
import org.jclouds.concurrent.SingleThreaded; import org.jclouds.concurrent.SingleThreaded;
import org.jclouds.lifecycle.Closer; import org.jclouds.lifecycle.Closer;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -49,19 +49,18 @@ import com.google.inject.Provides;
* Note that this uses threads. * Note that this uses threads.
* *
* <p> * <p>
* This extends the underlying Future to expose a description (the task's toString) and the submission context (stack trace). * This extends the underlying Future to expose a description (the task's toString) and the submission context (stack
* The submission stack trace is appended to relevant stack traces on exceptions that are returned, * trace). The submission stack trace is appended to relevant stack traces on exceptions that are returned, so the user
* so the user can see the logical chain of execution (in the executor, and where it was passed to the executor). * can see the logical chain of execution (in the executor, and where it was passed to the executor).
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@ConfiguresExecutorService @ConfiguresExecutorService
public class ExecutorServiceModule extends AbstractModule { public class ExecutorServiceModule extends AbstractModule {
@VisibleForTesting
static final class ShutdownExecutorOnClose implements Closeable { static final class ShutdownExecutorOnClose implements Closeable {
@Resource @Resource
protected Logger logger = Logger.NULL; private Logger logger = Logger.NULL;
private final ExecutorService service; private final ExecutorService service;
@ -77,32 +76,31 @@ public class ExecutorServiceModule extends AbstractModule {
} }
} }
@VisibleForTesting
final ExecutorService userExecutorFromConstructor; final ExecutorService userExecutorFromConstructor;
@VisibleForTesting
final ExecutorService ioExecutorFromConstructor; final ExecutorService ioExecutorFromConstructor;
@Inject @Inject
public ExecutorServiceModule(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads, public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userThreads,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads) { @Named(PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads) {
this.userExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(userThreads)); this.userExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(userThreads));
this.ioExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(ioThreads)); this.ioExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(ioThreads));
} }
ExecutorService addToStringOnSubmit(ExecutorService executor) { private ExecutorService addToStringOnSubmit(ExecutorService executor) {
if (executor != null) { if (executor != null) {
return new DescribingExecutorService(executor); return new DescribingExecutorService(executor);
} }
return executor; return executor;
} }
ExecutorService checkNotGuavaSameThreadExecutor(ExecutorService executor) { private ExecutorService checkNotGuavaSameThreadExecutor(ExecutorService executor) {
// we detect behavior based on the class // we detect behavior based on the class
if (executor != null && !(executor.getClass().isAnnotationPresent(SingleThreaded.class)) if (executor != null && !(executor.getClass().isAnnotationPresent(SingleThreaded.class))
&& executor.getClass().getSimpleName().indexOf("SameThread") != -1) { && executor.getClass().getSimpleName().indexOf("SameThread") != -1) {
Logger.CONSOLE.warn( Logger.CONSOLE.warn(
"please switch from %s to %s or annotate your same threaded executor with @SingleThreaded", executor "please switch from %s to %s or annotate your same threaded executor with @SingleThreaded", executor
.getClass().getName(), MoreExecutors.SameThreadExecutorService.class.getName()); .getClass().getName(), MoreExecutors.SameThreadExecutorService.class.getName());
return MoreExecutors.sameThreadExecutor(); return MoreExecutors.sameThreadExecutor();
} }
return executor; return executor;
@ -113,13 +111,13 @@ public class ExecutorServiceModule extends AbstractModule {
} }
@Override @Override
protected void configure() { protected void configure() { // NO_UCD
} }
@Provides @Provides
@Singleton @Singleton
@Named(Constants.PROPERTY_USER_THREADS) @Named(PROPERTY_USER_THREADS)
ExecutorService provideExecutorService(@Named(Constants.PROPERTY_USER_THREADS) int count, Closer closer) { ExecutorService provideExecutorService(@Named(PROPERTY_USER_THREADS) int count, Closer closer) { // NO_UCD
if (userExecutorFromConstructor != null) if (userExecutorFromConstructor != null)
return userExecutorFromConstructor; return userExecutorFromConstructor;
return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("user thread %d", count)), closer); return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("user thread %d", count)), closer);
@ -127,45 +125,40 @@ public class ExecutorServiceModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
@Named(Constants.PROPERTY_IO_WORKER_THREADS) @Named(PROPERTY_IO_WORKER_THREADS)
ExecutorService provideIOExecutor(@Named(Constants.PROPERTY_IO_WORKER_THREADS) int count, Closer closer) { ExecutorService provideIOExecutor(@Named(PROPERTY_IO_WORKER_THREADS) int count, Closer closer) { // NO_UCD
if (ioExecutorFromConstructor != null) if (ioExecutorFromConstructor != null)
return ioExecutorFromConstructor; return ioExecutorFromConstructor;
return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("i/o thread %d", count)), closer); return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("i/o thread %d", count)), closer);
} }
@VisibleForTesting
static <T extends ExecutorService> T shutdownOnClose(final T service, Closer closer) { static <T extends ExecutorService> T shutdownOnClose(final T service, Closer closer) {
closer.addToClose(new ShutdownExecutorOnClose(service)); closer.addToClose(new ShutdownExecutorOnClose(service));
return service; return service;
} }
@VisibleForTesting private ExecutorService newCachedThreadPoolNamed(String name) {
ExecutorService newCachedThreadPoolNamed(String name) {
return Executors.newCachedThreadPool(namedThreadFactory(name)); return Executors.newCachedThreadPool(namedThreadFactory(name));
} }
@VisibleForTesting private ExecutorService newThreadPoolNamed(String name, int maxCount) {
ExecutorService newThreadPoolNamed(String name, int maxCount) {
return maxCount == 0 ? newCachedThreadPoolNamed(name) : newScalingThreadPoolNamed(name, maxCount); return maxCount == 0 ? newCachedThreadPoolNamed(name) : newScalingThreadPoolNamed(name, maxCount);
} }
@VisibleForTesting private ExecutorService newScalingThreadPoolNamed(String name, int maxCount) {
ExecutorService newScalingThreadPoolNamed(String name, int maxCount) {
return newScalingThreadPool(1, maxCount, 60L * 1000, namedThreadFactory(name)); 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(); return new ThreadFactoryBuilder().setNameFormat(name).setThreadFactory(Executors.defaultThreadFactory()).build();
} }
/** returns the stack trace at the caller */ /** returns the stack trace at the caller */
static StackTraceElement[] getStackTraceHere() { 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) // Thread.getStackTrace, and the second one is us)
StackTraceElement[] fullSubmissionTrace = Thread.currentThread().getStackTrace(); 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); System.arraycopy(fullSubmissionTrace, 2, cleanedSubmissionTrace, 0, cleanedSubmissionTrace.length);
return cleanedSubmissionTrace; return cleanedSubmissionTrace;
} }

View File

@ -1,7 +1,8 @@
package org.jclouds.concurrent.config; 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.getStackTraceHere;
import static org.jclouds.concurrent.config.ExecutorServiceModule.shutdownOnClose;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.Delayed; import java.util.concurrent.Delayed;
@ -14,10 +15,8 @@ import java.util.concurrent.TimeUnit;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.lifecycle.Closer; import org.jclouds.lifecycle.Closer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -34,86 +33,78 @@ import com.google.inject.Provides;
*/ */
public class ScheduledExecutorServiceModule extends AbstractModule { public class ScheduledExecutorServiceModule extends AbstractModule {
static class DescribingScheduledExecutorService extends DescribingExecutorService implements ScheduledExecutorService { private static class DescribingScheduledExecutorService extends DescribingExecutorService implements
ScheduledExecutorService {
public DescribingScheduledExecutorService(ScheduledExecutorService delegate) { private DescribingScheduledExecutorService(ScheduledExecutorService delegate) {
super(delegate); super(delegate);
} }
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({ "unchecked", "rawtypes" })
@Override @Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).schedule(command, delay, unit),
.schedule(command, delay, unit), command.toString(), getStackTraceHere()); command.toString(), getStackTraceHere());
} }
@Override @Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return new DescribedScheduledFuture<V>(((ScheduledExecutorService) delegate) return new DescribedScheduledFuture<V>(((ScheduledExecutorService) delegate).schedule(callable, delay, unit),
.schedule(callable, delay, unit), callable.toString(), getStackTraceHere()); callable.toString(), getStackTraceHere());
} }
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({ "unchecked", "rawtypes" })
@Override @Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
long period, TimeUnit unit) { return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).scheduleAtFixedRate(command,
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) initialDelay, period, unit), command.toString(), getStackTraceHere());
.scheduleAtFixedRate(command, initialDelay, period, unit), command.toString(), getStackTraceHere()); }
}
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({ "unchecked", "rawtypes" })
@Override @Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
long delay, TimeUnit unit) { return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).scheduleWithFixedDelay(command,
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate) initialDelay, delay, unit), command.toString(), getStackTraceHere());
.scheduleWithFixedDelay(command, initialDelay, delay, unit), command.toString(), getStackTraceHere()); }
} }
}
static class DescribedScheduledFuture<T> extends DescribedFuture<T> implements ScheduledFuture<T> { private static class DescribedScheduledFuture<T> extends DescribedFuture<T> implements ScheduledFuture<T> {
public DescribedScheduledFuture(ScheduledFuture<T> delegate, String description, private DescribedScheduledFuture(ScheduledFuture<T> delegate, String description,
StackTraceElement[] submissionTrace) { StackTraceElement[] submissionTrace) {
super(delegate, description, submissionTrace); super(delegate, description, submissionTrace);
} }
@Override @Override
public long getDelay(TimeUnit unit) { public long getDelay(TimeUnit unit) {
return ((ScheduledFuture<T>) delegate).getDelay(unit); return ((ScheduledFuture<T>) delegate).getDelay(unit);
} }
@Override @Override
public int compareTo(Delayed o) { public int compareTo(Delayed o) {
return ((ScheduledFuture<T>) delegate).compareTo(o); return ((ScheduledFuture<T>) delegate).compareTo(o);
} }
} }
static ScheduledExecutorService addToStringOnSchedule(ScheduledExecutorService executor) { private static ScheduledExecutorService addToStringOnSchedule(ScheduledExecutorService executor) {
if (executor != null) { return (executor != null) ? new DescribingScheduledExecutorService(executor) : executor;
return new DescribingScheduledExecutorService(executor); }
}
return executor;
}
@Provides @Provides
@Singleton @Singleton
@Named(Constants.PROPERTY_SCHEDULER_THREADS) @Named(PROPERTY_SCHEDULER_THREADS)
ScheduledExecutorService provideScheduledExecutor(@Named(Constants.PROPERTY_SCHEDULER_THREADS) final int count, ScheduledExecutorService provideScheduledExecutor(@Named(PROPERTY_SCHEDULER_THREADS) int count, Closer closer) {
final Closer closer) { return shutdownOnClose(addToStringOnSchedule(newScheduledThreadPoolNamed("scheduler thread %d", count)), closer);
return shutdownOnClose(addToStringOnSchedule(newScheduledThreadPoolNamed("scheduler thread %d", count)), closer); }
}
@VisibleForTesting private static ScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) {
static ScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) { ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name)
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name)
.setThreadFactory(Executors.defaultThreadFactory()).build(); .setThreadFactory(Executors.defaultThreadFactory()).build();
return maxCount == 0 ? Executors.newSingleThreadScheduledExecutor(factory) return maxCount == 0 ? Executors.newSingleThreadScheduledExecutor(factory) : Executors.newScheduledThreadPool(
: Executors.newScheduledThreadPool(maxCount, factory); maxCount, factory);
} }
@Override
protected void configure() {
}
@Override
protected void configure() { // NO_UCD
}
} }

View File

@ -53,7 +53,6 @@ public class BindPropertiesToExpandedValues extends AbstractModule {
bindProperties(resolved); bindProperties(resolved);
} }
@SuppressWarnings("unused")
@Provides @Provides
@Singleton @Singleton
protected Properties expanded(FilterStringsBoundToInjectorByName filterStringsBoundByName) { protected Properties expanded(FilterStringsBoundToInjectorByName filterStringsBoundByName) {

View File

@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.inject.name.Names.named; import static com.google.inject.name.Names.named;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.inject.ConfigurationException; import com.google.inject.ConfigurationException;
@ -33,12 +32,11 @@ import com.google.inject.Key;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton
public class ValueOfConfigurationKeyOrNull implements Function<String, String> { public class ValueOfConfigurationKeyOrNull implements Function<String, String> {
protected final Injector injector; private final Injector injector;
@Inject @Inject
public ValueOfConfigurationKeyOrNull(Injector injector) { private ValueOfConfigurationKeyOrNull(Injector injector) {
this.injector = checkNotNull(injector, "injector"); this.injector = checkNotNull(injector, "injector");
} }
@ -51,5 +49,4 @@ public class ValueOfConfigurationKeyOrNull implements Function<String, String> {
return null; return null;
} }
} }
} }

View File

@ -76,15 +76,15 @@ public class Pems {
public static final String PUBLIC_X509_MARKER = "-----BEGIN PUBLIC KEY-----"; public static final String PUBLIC_X509_MARKER = "-----BEGIN PUBLIC KEY-----";
public static final String PUBLIC_PKCS1_MARKER = "-----BEGIN RSA PUBLIC KEY-----"; public static final String PUBLIC_PKCS1_MARKER = "-----BEGIN RSA PUBLIC KEY-----";
public static class PemProcessor<T> implements ByteProcessor<T> { private static class PemProcessor<T> implements ByteProcessor<T> {
public interface ResultParser<T> { private interface ResultParser<T> {
T parseResult(byte[] bytes) throws IOException; T parseResult(byte[] bytes) throws IOException;
} }
private final ByteArrayOutputStream out = new ByteArrayOutputStream(); private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final Map<String, ResultParser<T>> parsers; private final Map<String, ResultParser<T>> parsers;
public PemProcessor(Map<String, ResultParser<T>> parsers) { private PemProcessor(Map<String, ResultParser<T>> parsers) {
this.parsers = checkNotNull(parsers, "parsers"); this.parsers = checkNotNull(parsers, "parsers");
} }

View File

@ -28,12 +28,12 @@ import javax.inject.Singleton;
import com.google.inject.Inject; import com.google.inject.Inject;
@Singleton @Singleton
public class RsaSshKeyPairGenerator implements SshKeyPairGenerator { class RsaSshKeyPairGenerator implements SshKeyPairGenerator {
protected final Crypto crypto; private final Crypto crypto;
protected final SecureRandom secureRandom; private final SecureRandom secureRandom;
@Inject @Inject
public RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) { private RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) {
this.crypto = checkNotNull(crypto, "crypto"); this.crypto = checkNotNull(crypto, "crypto");
this.secureRandom = checkNotNull(secureRandom, "secureRandom"); this.secureRandom = checkNotNull(secureRandom, "secureRandom");
} }

View File

@ -99,7 +99,7 @@ public class Sha512Crypt {
return Function.INSTANCE; return Function.INSTANCE;
} }
public static enum Function implements com.google.common.base.Function<String, String> { private static enum Function implements com.google.common.base.Function<String, String> {
INSTANCE; INSTANCE;
@Override @Override
@ -111,7 +111,6 @@ public class Sha512Crypt {
public String toString() { public String toString() {
return "sha512Crypt()"; return "sha512Crypt()";
} }
} }
private static final String sha512_salt_prefix = "$6$"; 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 * @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 ctx = sha512();
MessageDigest alt_ctx = sha512(); MessageDigest alt_ctx = sha512();

View File

@ -110,7 +110,7 @@ public class SshKeys {
} }
// http://www.ietf.org/rfc/rfc4253.txt // 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 byte1 = in.read();
int byte2 = in.read(); int byte2 = in.read();
int byte3 = in.read(); int byte3 = in.read();
@ -315,7 +315,7 @@ public class SshKeys {
return on(':').join(fixedLength(2).split(base16().lowerCase().encode(hc.asBytes()))); 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 { try {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
writeLengthFirst("ssh-rsa".getBytes(), out); writeLengthFirst("ssh-rsa".getBytes(), out);
@ -328,7 +328,7 @@ public class SshKeys {
} }
// http://www.ietf.org/rfc/rfc4253.txt // 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 >>> 24) & 0xFF);
out.write((array.length >>> 16) & 0xFF); out.write((array.length >>> 16) & 0xFF);
out.write((array.length >>> 8) & 0xFF); out.write((array.length >>> 8) & 0xFF);

View File

@ -34,8 +34,6 @@ import com.google.inject.ImplementedBy;
@ImplementedBy(SimpleDateFormatDateService.class) @ImplementedBy(SimpleDateFormatDateService.class)
public interface DateService { public interface DateService {
Date fromSeconds(long seconds);
String cDateFormat(Date date); String cDateFormat(Date date);
String cDateFormat(); String cDateFormat();

View File

@ -27,12 +27,10 @@ import java.util.regex.Pattern;
*/ */
public class DateUtils { public class DateUtils {
public static final String TZ_REGEX = "([+-][0-9][0-9](:?[0-9][0-9])?|Z)"; 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 + "?");
public 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 // 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) { public static String trimToMillis(String toParse) {
Matcher matcher = MILLIS_PATTERN.matcher(toParse); Matcher matcher = MILLIS_PATTERN.matcher(toParse);
@ -44,7 +42,7 @@ public class DateUtils {
return toParse; 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) { public static String trimTZ(String toParse) {
Matcher matcher = TZ_PATTERN.matcher(toParse); Matcher matcher = TZ_PATTERN.matcher(toParse);

View File

@ -66,11 +66,6 @@ public class SimpleDateFormatDateService implements DateService {
cSimpleDateFormat.setTimeZone(new SimpleTimeZone(0, "GMT")); cSimpleDateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
} }
@Override
public final Date fromSeconds(long seconds) {
return new Date(seconds * 1000);
}
@Override @Override
public final String cDateFormat(Date date) { public final String cDateFormat(Date date) {
synchronized (cSimpleDateFormat) { synchronized (cSimpleDateFormat) {

View File

@ -18,23 +18,12 @@
*/ */
package org.jclouds.domain; 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.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Credentials { public class Credentials {
public static final Credentials NO_CREDENTIALS = new Credentials(null, null);
public static class Builder<T extends Credentials> { public static class Builder<T extends Credentials> {
protected String identity; protected String identity;
protected String credential; protected String credential;
@ -63,21 +52,6 @@ public class Credentials {
this.credential = credential; this.credential = credential;
} }
public static Credentials parse(URI uri) {
checkNotNull(uri, "uri");
List<String> 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<? extends Credentials> toBuilder() { public Builder<? extends Credentials> toBuilder() {
return new Builder<Credentials>().identity(identity).credential(credential); return new Builder<Credentials>().identity(identity).credential(credential);
} }

View File

@ -87,7 +87,7 @@ public class JsonBall implements Comparable<String>, CharSequence {
this.value = quoteStringIfNotNumberOrBoolean(checkNotNull(value, "value")); 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() if (JSON_STRING_PATTERN.matcher(in).find() && !JSON_NUMBER_PATTERN.matcher(in).find()
&& !JSON_BOOLEAN_PATTERN.matcher(in).find()) { && !JSON_BOOLEAN_PATTERN.matcher(in).find()) {
return "\"" + in + "\""; return "\"" + in + "\"";

View File

@ -32,13 +32,13 @@ import com.google.common.collect.ImmutableSet;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class LocationBuilder { public final class LocationBuilder {
protected LocationScope scope; private LocationScope scope;
protected String id; private String id;
protected String description; private String description;
protected Location parent; private Location parent;
protected Set<String> iso3166Codes = ImmutableSet.of(); private Set<String> iso3166Codes = ImmutableSet.of();
protected Map<String, Object> metadata = ImmutableMap.of(); private Map<String, Object> metadata = ImmutableMap.of();
public LocationBuilder scope(LocationScope scope) { public LocationBuilder scope(LocationScope scope) {
this.scope = scope; this.scope = scope;

View File

@ -36,7 +36,6 @@ public enum LocationScope {
* E.g. the DMZ segment, secure segment. * E.g. the DMZ segment, secure segment.
*/ */
NETWORK, NETWORK,
RACK,
HOST; HOST;
} }

View File

@ -18,7 +18,9 @@
*/ */
package org.jclouds.domain; 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 org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Optional; import com.google.common.base.Optional;
@ -28,9 +30,9 @@ import com.google.common.base.Optional;
*/ */
public class LoginCredentials extends Credentials { public class LoginCredentials extends Credentials {
public static boolean isPrivateKeyCredential(String credential) { private static boolean isPrivateKeyCredential(String credential) {
return credential != null 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) { public static LoginCredentials fromCredentials(Credentials creds) {
@ -115,15 +117,7 @@ public class LoginCredentials extends Credentials {
private final Optional<String> password; private final Optional<String> password;
private final Optional<String> privateKey; private final Optional<String> privateKey;
public LoginCredentials(String username, boolean authenticateSudo) { private LoginCredentials(String username, @Nullable Optional<String> password, @Nullable Optional<String> privateKey, boolean authenticateSudo) {
this(username, Optional.<String>absent(), Optional.<String>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<String> password, @Nullable Optional<String> privateKey, boolean authenticateSudo) {
super(username, privateKey != null && privateKey.isPresent() && isPrivateKeyCredential(privateKey.get()) super(username, privateKey != null && privateKey.isPresent() && isPrivateKeyCredential(privateKey.get())
? privateKey.get() ? privateKey.get()
: (password != null && password.isPresent() ? password.get() : null)); : (password != null && password.isPresent() ? password.get() : null));
@ -139,26 +133,12 @@ public class LoginCredentials extends Credentials {
return identity; 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 * @return the password of the login user or null
*/ */
@Nullable @Nullable
public String getPassword() { 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 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 * @return the private ssh key of the user or null
*/ */
@Nullable @Nullable
public String getPrivateKey() { public String getPrivateKey() {
return hasPrivateKey() ? privateKey.get() : null; return (privateKey != null) ? privateKey.orNull() : null;
} }
/** /**
@ -233,7 +199,7 @@ public class LoginCredentials extends Credentials {
@Override @Override
public String toString() { public String toString() {
return "[user=" + getUser() + ", passwordPresent=" + hasPassword() + ", privateKeyPresent=" return "[user=" + getUser() + ", passwordPresent=" + password.isPresent() + ", privateKeyPresent="
+ hasPrivateKey() + ", shouldAuthenticateSudo=" + authenticateSudo + "]"; + privateKey.isPresent() + ", shouldAuthenticateSudo=" + authenticateSudo + "]";
} }
} }

View File

@ -63,22 +63,15 @@ public class LocationImpl implements Location {
@Override @Override
public String toString() { public String toString() {
return string().toString();
}
protected ToStringHelper string() {
ToStringHelper helper = Objects.toStringHelper("").omitNullValues().add("scope", scope).add("id", id) ToStringHelper helper = Objects.toStringHelper("").omitNullValues().add("scope", scope).add("id", id)
.add("description", description); .add("description", description);
if (parent != null) if (parent != null)
helper.add("parent", parent.getId()); helper.add("parent", parent.getId());
if (iso3166Codes.size() > 0) if (iso3166Codes.size() > 0)
helper.add("iso3166Codes", iso3166Codes); helper.add("iso3166Codes", iso3166Codes);
if (metadata.size() > 0) if (metadata.size() > 0)
helper.add("metadata", metadata); helper.add("metadata", metadata);
return helper; return helper.toString();
} }
public LocationImpl(LocationScope scope, String id, String description, @Nullable Location parent, public LocationImpl(LocationScope scope, String id, String description, @Nullable Location parent,

View File

@ -87,8 +87,8 @@ public class JCECrypto implements Crypto {
return provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider); return provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider);
} }
public static final String HmacSHA256 = "HmacSHA256"; private static final String HmacSHA256 = "HmacSHA256";
public static final String HmacSHA1 = "HmacSHA1"; private static final String HmacSHA1 = "HmacSHA1";
@Override @Override
public Mac hmacSHA1(byte[] key) throws InvalidKeyException { public Mac hmacSHA1(byte[] key) throws InvalidKeyException {

View File

@ -19,12 +19,15 @@
package org.jclouds.events.config; 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 java.util.concurrent.ExecutorService;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; 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.config.annotations.AsyncBus;
import org.jclouds.events.handlers.DeadEventLoggingHandler; 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.common.eventbus.EventBus;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes;
/** /**
* Configures the {@link EventBus} to be used in the platform. * Configures the {@link EventBus} to be used in the platform.
* <p> * <p>
* This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for * This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for asynchronous
* asynchronous operations. * operations.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
* *
@ -49,37 +51,34 @@ import com.google.inject.Scopes;
*/ */
@ConfiguresEventBus @ConfiguresEventBus
public class EventBusModule extends AbstractModule { public class EventBusModule extends AbstractModule {
/** /**
* Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch * Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch events to subscribers.
* events to subscribers. */
*/ @Provides
@Provides @Singleton
@Singleton AsyncEventBus provideAsyncEventBus(@Named(PROPERTY_USER_THREADS) ExecutorService executor,
AsyncEventBus provideAsyncEventBus( DeadEventLoggingHandler deadEventsHandler) {// NO_UCD
@Named(Constants.PROPERTY_USER_THREADS) final ExecutorService executor, AsyncEventBus asyncBus = new AsyncEventBus("jclouds-async-event-bus", executor);
final DeadEventLoggingHandler deadEventsHandler) { asyncBus.register(deadEventsHandler);
AsyncEventBus asyncBus = new AsyncEventBus("jclouds-async-event-bus", executor); return asyncBus;
asyncBus.register(deadEventsHandler); }
return asyncBus;
}
/** /**
* Provides asynchronous {@link EventBus}. * Provides asynchronous {@link EventBus}.
*/ */
@Provides @Provides
@Singleton @Singleton
EventBus provideSyncEventBus(final DeadEventLoggingHandler deadEventsHandler) { EventBus provideSyncEventBus(DeadEventLoggingHandler deadEventsHandler) { // NO_UCD
EventBus syncBus = new EventBus("jclouds-sync-event-bus"); EventBus syncBus = new EventBus("jclouds-sync-event-bus");
syncBus.register(deadEventsHandler); syncBus.register(deadEventsHandler);
return syncBus; 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);
}
/**
* 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);
}
} }

View File

@ -35,18 +35,12 @@ import com.google.common.eventbus.Subscribe;
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Singleton @Singleton
public class DeadEventLoggingHandler public class DeadEventLoggingHandler {
{ @Resource
@Resource private Logger logger = Logger.NULL;
private Logger logger = Logger.NULL;
/** @Subscribe
* Due to <a href="http://code.google.com/p/guava-libraries/issues/detail?id=783">Guava Issue public void handleDeadEvent(DeadEvent deadEvent) { // NO_UCD
* 786</a> {@link #handleDeadEvent(DeadEvent)} is marked <code>final</code>to avoid having logger.trace("detected dead event %s", deadEvent.getEvent());
* duplicate events. }
*/
@Subscribe
public final void handleDeadEvent(DeadEvent deadEvent) {
logger.trace("detected dead event %s", deadEvent.getEvent());
}
} }

View File

@ -36,19 +36,18 @@ import com.google.common.util.concurrent.ListenableFuture;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class MapHttp4xxCodesToExceptions implements FutureFallback<Object> { public final class MapHttp4xxCodesToExceptions implements FutureFallback<Object> {
private final PropagateIfRetryAfter propagateIfRetryAfter; private final PropagateIfRetryAfter propagateIfRetryAfter;
@Inject @Inject
protected MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) { MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) { // NO_UCD
this.propagateIfRetryAfter = checkNotNull(propagateIfRetryAfter, "propagateIfRetryAfter"); this.propagateIfRetryAfter = checkNotNull(propagateIfRetryAfter, "propagateIfRetryAfter");
} }
@Override @Override
public ListenableFuture<Object> create(Throwable t) { public ListenableFuture<Object> create(Throwable t) { // NO_UCD
// if we pass here, we aren't a retry-after exception propagateIfRetryAfter.create(t); // if we pass here, we aren't a retry-after exception
propagateIfRetryAfter.create(t);
if (t instanceof HttpResponseException) { if (t instanceof HttpResponseException) {
HttpResponseException responseException = HttpResponseException.class.cast(t); HttpResponseException responseException = HttpResponseException.class.cast(t);
if (responseException.getResponse() != null) if (responseException.getResponse() != null)

View File

@ -139,11 +139,6 @@ public final class Uris {
return this; return this;
} }
public UriBuilder clearPath() {
path = null;
return this;
}
public UriBuilder path(@Nullable String path) { public UriBuilder path(@Nullable String path) {
path = emptyToNull(path); path = emptyToNull(path);
if (path == null) if (path == null)
@ -163,10 +158,6 @@ public final class Uris {
return this; return this;
} }
public UriBuilder query(Map<String, ?> parameters) {
return query(forMap(parameters));
}
public UriBuilder query(@Nullable String queryLine) { public UriBuilder query(@Nullable String queryLine) {
if (query == null) if (query == null)
return clearQuery(); return clearQuery();
@ -194,10 +185,6 @@ public final class Uris {
return addQuery(name, Arrays.asList(checkNotNull(values, "values of %s", name))); return addQuery(name, Arrays.asList(checkNotNull(values, "values of %s", name)));
} }
public UriBuilder addQuery(Map<String, ?> parameters) {
return addQuery(forMap(parameters));
}
public UriBuilder addQuery(Multimap<String, ?> parameters) { public UriBuilder addQuery(Multimap<String, ?> parameters) {
query.putAll(checkNotNull(parameters, "parameters")); query.putAll(checkNotNull(parameters, "parameters"));
return this; return this;
@ -315,7 +302,7 @@ public final class Uris {
} }
} }
public String expand(Map<String, ?> variables) { private String expand(Map<String, ?> variables) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
if (scheme != null) if (scheme != null)
b.append(scheme).append("://"); b.append(scheme).append("://");

View File

@ -205,10 +205,6 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
} }
public abstract static class HandlerForGeneratedRequestWithResult<T> extends HandlerWithResult<T> { public abstract static class HandlerForGeneratedRequestWithResult<T> extends HandlerWithResult<T> {
@Override
protected GeneratedHttpRequest getRequest() {
return (GeneratedHttpRequest) super.getRequest();
}
@Override @Override
public HandlerForGeneratedRequestWithResult<T> setContext(HttpRequest request) { public HandlerForGeneratedRequestWithResult<T> setContext(HttpRequest request) {
@ -216,6 +212,11 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
super.setContext(request); super.setContext(request);
return this; return this;
} }
@Override
protected GeneratedHttpRequest<?> getRequest() {
return (GeneratedHttpRequest<?>) super.getRequest();
}
} }
@Override @Override

View File

@ -53,11 +53,6 @@ public abstract class BaseView extends ForwardingObject implements View {
return (C) backend; return (C) backend;
} }
@Override
public <C extends Context> C unwrap(Class<C> clazz) {
return unwrap (TypeToken.of(checkNotNull(clazz, "clazz")));
}
@Override @Override
public TypeToken<? extends Context> getBackendType() { public TypeToken<? extends Context> getBackendType() {
return backendType; return backendType;

View File

@ -123,7 +123,6 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
this.delegateFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, checkNotNull(serializationFieldNamingPolicy, "fieldNamingPolicy"), checkNotNull(excluder, "excluder")); this.delegateFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, checkNotNull(serializationFieldNamingPolicy, "fieldNamingPolicy"), checkNotNull(excluder, "excluder"));
} }
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
Class<? super T> raw = type.getRawType(); Class<? super T> raw = type.getRawType();
Constructor<? super T> deserializationCtor = constructorFieldNamingPolicy.getDeserializationConstructor(raw); Constructor<? super T> deserializationCtor = constructorFieldNamingPolicy.getDeserializationConstructor(raw);
@ -139,11 +138,11 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
private final class DeserializeWithParameterizedConstructorSerializeWithDelegate<T> extends TypeAdapter<T> { private final class DeserializeWithParameterizedConstructorSerializeWithDelegate<T> extends TypeAdapter<T> {
private final Constructor<? super T> parameterizedCtor; private final Constructor<? super T> parameterizedCtor;
private final Map<String, ParameterReader> parameterReaders; private final Map<String, ParameterReader<?>> parameterReaders;
private final TypeAdapter<T> delegate; private final TypeAdapter<T> delegate;
private DeserializeWithParameterizedConstructorSerializeWithDelegate(TypeAdapter<T> delegate, private DeserializeWithParameterizedConstructorSerializeWithDelegate(TypeAdapter<T> delegate,
Constructor<? super T> parameterizedCtor, Map<String, ParameterReader> parameterReaders) { Constructor<? super T> parameterizedCtor, Map<String, ParameterReader<?>> parameterReaders) {
this.delegate = delegate; this.delegate = delegate;
this.parameterizedCtor = parameterizedCtor; this.parameterizedCtor = parameterizedCtor;
this.parameterReaders = parameterReaders; this.parameterReaders = parameterReaders;
@ -174,7 +173,7 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
while (in.hasNext()) { while (in.hasNext()) {
empty = false; empty = false;
String name = in.nextName(); String name = in.nextName();
ParameterReader parameter = parameterReaders.get(name); ParameterReader<?> parameter = parameterReaders.get(name);
if (parameter == null) { if (parameter == null) {
in.skipValue(); in.skipValue();
} else { } else {
@ -246,20 +245,19 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
} }
} }
@SuppressWarnings("unchecked") private Map<String, ParameterReader<?>> getParameterReaders(Gson context, TypeToken<?> declaring, Constructor<?> constructor) {
private Map<String, ParameterReader> getParameterReaders(Gson context, TypeToken<?> declaring, Constructor<?> constructor) { Map<String, ParameterReader<?>> result = Maps.newLinkedHashMap();
Map<String, ParameterReader> result = Maps.newLinkedHashMap();
for (int index = 0; index < constructor.getGenericParameterTypes().length; index++) { for (int index = 0; index < constructor.getGenericParameterTypes().length; index++) {
Type parameterType = getTypeOfConstructorParameter(declaring, constructor, index); Type parameterType = getTypeOfConstructorParameter(declaring, constructor, index);
TypeAdapter<?> adapter = context.getAdapter(TypeToken.get(parameterType)); TypeAdapter<?> adapter = context.getAdapter(TypeToken.get(parameterType));
String parameterName = constructorFieldNamingPolicy.translateName(constructor, index); String parameterName = constructorFieldNamingPolicy.translateName(constructor, index);
checkArgument(parameterName != null, constructor + " parameter " + 0 + " failed to be named by " + constructorFieldNamingPolicy); checkArgument(parameterName != null, constructor + " parameter " + 0 + " failed to be named by " + constructorFieldNamingPolicy);
ParameterReader parameterReader = new ParameterReader(parameterName, index, adapter); @SuppressWarnings({ "rawtypes", "unchecked" })
ParameterReader previous = result.put(parameterReader.name, parameterReader); 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); checkArgument(previous == null, constructor + " declares multiple JSON parameters named " + parameterReader.name);
} }
return result; return result;
} }

View File

@ -45,7 +45,7 @@ public class BindMapToStringPayload implements MapBinder {
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
checkNotNull(postParams, "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(); Invokable<?, ?> invoked = r.getInvocation().getInvokable();
checkArgument(invoked.isAnnotationPresent(Payload.class), checkArgument(invoked.isAnnotationPresent(Payload.class),
"method %s must have @Payload annotation to use this binder", invoked); "method %s must have @Payload annotation to use this binder", invoked);

View File

@ -18,6 +18,8 @@
*/ */
package org.jclouds; package org.jclouds;
import static java.util.concurrent.Executors.defaultThreadFactory;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService; import java.util.concurrent.CompletionService;
@ -44,7 +46,7 @@ public abstract class PerformanceTest {
@BeforeTest @BeforeTest
public void setupExecutorService() { public void setupExecutorService() {
exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000); exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000, defaultThreadFactory());
} }
@AfterTest @AfterTest

View File

@ -36,32 +36,30 @@ public class ValueOfConfigurationKeyOrNullTest {
@Test @Test
public void testNotThere() { public void testNotThere() {
assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector()).apply("foo"), null); assertEquals(Guice.createInjector().getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), null);
} }
@Test @Test
public void testThere() { public void testThere() {
assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { assertEquals(Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() { protected void configure() {
bindConstant().annotatedWith(Names.named("foo")).to("bar"); bindConstant().annotatedWith(Names.named("foo")).to("bar");
} }
})).apply("foo"), "bar"); }).getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), "bar");
} }
@Test @Test
public void testEmptyIsThere() { public void testEmptyIsThere() {
assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() { assertEquals(Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() { protected void configure() {
bindConstant().annotatedWith(Names.named("foo")).to(""); bindConstant().annotatedWith(Names.named("foo")).to("");
} }
})).apply("foo"), ""); }).getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), "");
} }
} }

View File

@ -42,6 +42,8 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -66,9 +68,9 @@ public class RsaSshKeyPairGeneratorTest {
@Test @Test
public void testApply() { public void testApply() {
Crypto crypto = createMock(Crypto.class); final Crypto crypto = createMock(Crypto.class);
KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class); KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class);
SecureRandom secureRandom = createMock(SecureRandom.class); final SecureRandom secureRandom = createMock(SecureRandom.class);
expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator); expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator);
rsaKeyPairGenerator.initialize(2048, secureRandom); rsaKeyPairGenerator.initialize(2048, secureRandom);
@ -76,7 +78,12 @@ public class RsaSshKeyPairGeneratorTest {
replay(crypto, rsaKeyPairGenerator, secureRandom); 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(), assertEquals(supplier.get(),
ImmutableMap.of("public", openSshKey, "private", PRIVATE_KEY.replaceAll("\n", lineSeparator))); ImmutableMap.of("public", openSshKey, "private", PRIVATE_KEY.replaceAll("\n", lineSeparator)));

View File

@ -174,13 +174,6 @@ public class DateServiceTest extends PerformanceTest {
dateService.iso8601DateFormat(); dateService.iso8601DateFormat();
} }
@Test
void testFromSeconds() {
long seconds = 1254008225;
Date date = dateService.fromSeconds(seconds);
assertEquals(dateService.iso8601SecondsDateFormat(date), "2009-09-26T23:37:05Z");
}
@Test @Test
void testUTCIsGMT() { void testUTCIsGMT() {
assertEquals(dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime(), dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime()); assertEquals(dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime(), dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime());

View File

@ -20,8 +20,6 @@ package org.jclouds.domain;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.net.URI;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
@ -30,69 +28,9 @@ import org.testng.annotations.Test;
@Test(groups = "unit") @Test(groups = "unit")
public class CredentialsTest { 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() { public void testSubClassEquals() {
Credentials creds = new Credentials("user", "pass"); Credentials creds = new Credentials("user", "pass");
assertEquals(creds, new Credentials("user", "pass") { assertEquals(creds, new Credentials("user", "pass") {
}); });
} }
} }

View File

@ -23,7 +23,6 @@ import static org.jclouds.util.Strings2.urlEncode;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.net.URI; import java.net.URI;
import java.util.Map;
import org.testng.annotations.DataProvider; import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -74,18 +73,17 @@ public class UrisTest {
@Test(dataProvider = "strings") @Test(dataProvider = "strings")
public void testQuery(String val) { public void testQuery(String val) {
Map<String, String> query = ImmutableMap.of("moo", val); assertEquals(uriBuilder("https://foo.com:8080").addQuery("moo", val).toString(), "https://foo.com:8080?moo=" + val);
assertEquals(uriBuilder("https://foo.com:8080").query(query).toString(), "https://foo.com:8080?moo=" + val); assertEquals(uriBuilder("https://foo.com:8080").addQuery("moo", val).build().toString(), "https://foo.com:8080?moo="
assertEquals(uriBuilder("https://foo.com:8080").query(query).build().toString(), "https://foo.com:8080?moo="
+ urlEncode(val, '/', ',')); + urlEncode(val, '/', ','));
assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").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?moo=" + val); "https://api.github.com/repos/user?foo=bar&kung=fu&moo=" + val);
assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").query(query).build().toString(), assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").addQuery("moo", val).build().toString(),
"https://api.github.com/repos/user?moo=" + urlEncode(val, '/', ',')); "https://api.github.com/repos/user?foo=bar&kung=fu&moo=" + urlEncode(val, '/', ','));
assertEquals(uriBuilder("https://api.github.com/repos/{user}").query(query).toString(), assertEquals(uriBuilder("https://api.github.com/repos/{user}").addQuery("moo", val).toString(),
"https://api.github.com/repos/{user}?moo=" + val); "https://api.github.com/repos/{user}?moo=" + val);
assertEquals( 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, '/', ',')); "https://api.github.com/repos/bob?moo=" + urlEncode(val, '/', ','));
} }

View File

@ -70,7 +70,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("Ubuntu Server 10.04 (64-bit)") .description("Ubuntu Server 10.04 (64-bit)")
.name("Ubuntu Server 10.04.3") .name("Ubuntu Server 10.04.3")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-4e5b842f") .id("us-east-1/qmi-4e5b842f")
.providerId("qmi-4e5b842f") .providerId("qmi-4e5b842f")
.location(defaultLocation) .location(defaultLocation)
@ -89,7 +89,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("Ubuntu Server 11.10 (64-bit)") .description("Ubuntu Server 11.10 (64-bit)")
.name("Ubuntu Server 11.10") .name("Ubuntu Server 11.10")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-9ac92558") .id("us-east-1/qmi-9ac92558")
.providerId("qmi-9ac92558") .providerId("qmi-9ac92558")
.location(defaultLocation) .location(defaultLocation)
@ -108,7 +108,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("CentOS 5.5 Server 64-bit") .description("CentOS 5.5 Server 64-bit")
.name("CentOS 5.5 Server") .name("CentOS 5.5 Server")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-33a467aa") .id("us-east-1/qmi-33a467aa")
.providerId("qmi-33a467aa") .providerId("qmi-33a467aa")
.location(defaultLocation) .location(defaultLocation)
@ -127,7 +127,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("Debian 6.0 (64-bit)") .description("Debian 6.0 (64-bit)")
.name("Debian 6.0") .name("Debian 6.0")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-f2a9d2ba") .id("us-east-1/qmi-f2a9d2ba")
.providerId("qmi-f2a9d2ba") .providerId("qmi-f2a9d2ba")
.location(defaultLocation) .location(defaultLocation)
@ -146,7 +146,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("CentOS 6.0 (64-bit)") .description("CentOS 6.0 (64-bit)")
.name("CentOS 6.0") .name("CentOS 6.0")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-96f82145") .id("us-east-1/qmi-96f82145")
.providerId("qmi-96f82145") .providerId("qmi-96f82145")
.location(defaultLocation) .location(defaultLocation)
@ -165,7 +165,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("CentOS 6.0 GUI (64-bit)") .description("CentOS 6.0 GUI (64-bit)")
.name("CentOS 6.0 GUI") .name("CentOS 6.0 GUI")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-42e877f6") .id("us-east-1/qmi-42e877f6")
.providerId("qmi-42e877f6") .providerId("qmi-42e877f6")
.location(defaultLocation) .location(defaultLocation)
@ -184,7 +184,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("Ubuntu Server 11.04 (64-bit)") .description("Ubuntu Server 11.04 (64-bit)")
.name("Ubuntu Server 11.04") .name("Ubuntu Server 11.04")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-eed8cea7") .id("us-east-1/qmi-eed8cea7")
.providerId("qmi-eed8cea7") .providerId("qmi-eed8cea7")
.location(defaultLocation) .location(defaultLocation)
@ -204,7 +204,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("Fedora 16 Server") .description("Fedora 16 Server")
.name("Fedora 16 Server") .name("Fedora 16 Server")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-fa4bdae0") .id("us-east-1/qmi-fa4bdae0")
.providerId("qmi-fa4bdae0") .providerId("qmi-fa4bdae0")
.location(defaultLocation) .location(defaultLocation)
@ -223,7 +223,7 @@ public class GreenQloudComputeReviseParsedImageTest {
.arch("paravirtual").build()) .arch("paravirtual").build())
.description("CentOS 5.6 Server GUI 64-bit") .description("CentOS 5.6 Server GUI 64-bit")
.name("CentOS 5.6 GUI") .name("CentOS 5.6 GUI")
.defaultCredentials(new LoginCredentials("root", false)) .defaultCredentials(LoginCredentials.builder().user("root").build())
.id("us-east-1/qmi-93271d32") .id("us-east-1/qmi-93271d32")
.providerId("qmi-93271d32") .providerId("qmi-93271d32")
.location(defaultLocation) .location(defaultLocation)

View File

@ -129,9 +129,11 @@ public class JsonNodeMetadataStore implements NodeMetadataStore {
.tags(jsonMetadata.tags) .tags(jsonMetadata.tags)
.group(jsonMetadata.group) .group(jsonMetadata.group)
.userMetadata(jsonMetadata.userMetadata) .userMetadata(jsonMetadata.userMetadata)
.credentials( .credentials(LoginCredentials.builder()
new LoginCredentials(jsonMetadata.user, jsonMetadata.password, jsonMetadata.privateKey, .user(jsonMetadata.user)
jsonMetadata.authenticateSudo)).build(); .privateKey(jsonMetadata.privateKey)
.password(jsonMetadata.password)
.authenticateSudo(jsonMetadata.authenticateSudo).build()).build();
} }
@Override @Override

View File

@ -146,7 +146,10 @@ public class YamlImage {
return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description) return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description)
.operatingSystem(operatingSystem).status(Image.Status.AVAILABLE) .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(); .build();
} }
}; };

View File

@ -120,9 +120,10 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
String guestOsUser = vm.getExtraData(GUEST_OS_USER); String guestOsUser = vm.getExtraData(GUEST_OS_USER);
String guestOsPassword = vm.getExtraData(GUEST_OS_PASSWORD); String guestOsPassword = vm.getExtraData(GUEST_OS_PASSWORD);
LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true); nodeMetadataBuilder.credentials(LoginCredentials.builder()
nodeMetadataBuilder.credentials(loginCredentials); .user(guestOsUser)
.password(guestOsPassword)
.authenticateSudo(true).build());
return nodeMetadataBuilder.build(); return nodeMetadataBuilder.build();
} }

View File

@ -241,7 +241,10 @@ public class MastersLoadingCache extends AbstractLoadingCache<Image, Master> {
.iso(IsoSpec.builder().sourcePath(localIsoUrl) .iso(IsoSpec.builder().sourcePath(localIsoUrl)
.installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())).build()) .installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())).build())
.network(networkSpec) .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 @Override

View File

@ -181,9 +181,11 @@ public class NodeCreator implements Function<NodeSpec, NodeAndInitialCredentials
nodeMetadataBuilder.publicAddresses(ImmutableSet.of(networkUtils.getIpAddressFromNicSlot(clone.getName(), slot))); nodeMetadataBuilder.publicAddresses(ImmutableSet.of(networkUtils.getIpAddressFromNicSlot(clone.getName(), slot)));
String guestOsUser = clone.getExtraData(GUEST_OS_USER); String guestOsUser = clone.getExtraData(GUEST_OS_USER);
String guestOsPassword = clone.getExtraData(GUEST_OS_PASSWORD); String guestOsPassword = clone.getExtraData(GUEST_OS_PASSWORD);
LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true); nodeMetadataBuilder.credentials(LoginCredentials.builder()
nodeMetadataBuilder.credentials(loginCredentials); .user(guestOsUser)
return nodeMetadataBuilder.build(); .password(guestOsPassword)
.authenticateSudo(true).build());
return nodeMetadataBuilder.build();
} }
private long findSlotForNetworkAttachment(IMachine clone, NetworkAttachmentType networkAttachmentType) { private long findSlotForNetworkAttachment(IMachine clone, NetworkAttachmentType networkAttachmentType) {

View File

@ -67,7 +67,7 @@ public class AWSEC2ImageParserTest {
.description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml") .description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml")
.is64Bit(false).build()) .is64Bit(false).build())
.description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml") .description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml")
.defaultCredentials(new LoginCredentials("ubuntu", false)).id("us-east-1/ami-7e28ca17") .defaultCredentials(LoginCredentials.builder().user("ubuntu").build()).id("us-east-1/ami-7e28ca17")
.providerId("ami-7e28ca17").location(defaultLocation).version("20091130") .providerId("ami-7e28ca17").location(defaultLocation).version("20091130")
.userMetadata(ImmutableMap.of( .userMetadata(ImmutableMap.of(
"owner", "099720109477", "owner", "099720109477",
@ -86,7 +86,7 @@ public class AWSEC2ImageParserTest {
new OperatingSystem.Builder().family(OsFamily.UBUNTU).arch("paravirtual").version("8.04") new OperatingSystem.Builder().family(OsFamily.UBUNTU).arch("paravirtual").version("8.04")
.description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml").is64Bit(false) .description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml").is64Bit(false)
.build()).description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml") .build()).description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml")
.defaultCredentials(new LoginCredentials("ubuntu", false)).id("us-east-1/ami-c0fa1ea9") .defaultCredentials(LoginCredentials.builder().user("ubuntu").build()).id("us-east-1/ami-c0fa1ea9")
.providerId("ami-c0fa1ea9").location(defaultLocation).version("20080905") .providerId("ami-c0fa1ea9").location(defaultLocation).version("20080905")
.userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store")) .userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store"))
.status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus("available").build()); .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus("available").build());
@ -101,7 +101,7 @@ public class AWSEC2ImageParserTest {
.description("099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827") .description("099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827")
.is64Bit(false).build()) .is64Bit(false).build())
.description("099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827") .description("099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827")
.defaultCredentials(new LoginCredentials("ubuntu", false)).id("us-east-1/ami-10f3a255") .defaultCredentials(LoginCredentials.builder().user("ubuntu").build()).id("us-east-1/ami-10f3a255")
.providerId("ami-10f3a255").location(defaultLocation).version("20100827") .providerId("ami-10f3a255").location(defaultLocation).version("20100827")
.userMetadata(ImmutableMap.of( .userMetadata(ImmutableMap.of(
"owner", "099720109477", "owner", "099720109477",
@ -125,7 +125,7 @@ public class AWSEC2ImageParserTest {
.description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml") .description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml")
.is64Bit(false).build()) .is64Bit(false).build())
.description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml") .description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml")
.defaultCredentials(new LoginCredentials("root", false)).id("us-east-1/ami-870de2ee") .defaultCredentials(LoginCredentials.builder().user("root").build()).id("us-east-1/ami-870de2ee")
.providerId("ami-870de2ee").location(defaultLocation).version("5622") .providerId("ami-870de2ee").location(defaultLocation).version("5622")
.userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store")) .userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store"))
.status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build());
@ -144,7 +144,7 @@ public class AWSEC2ImageParserTest {
new OperatingSystem.Builder().family(OsFamily.CENTOS).arch("hvm").version("5.4") new OperatingSystem.Builder().family(OsFamily.CENTOS).arch("hvm").version("5.4")
.description("amazon/EC2 CentOS 5.4 HVM AMI").is64Bit(true).build()) .description("amazon/EC2 CentOS 5.4 HVM AMI").is64Bit(true).build())
.description("EC2 CentOS 5.4 HVM AMI") .description("EC2 CentOS 5.4 HVM AMI")
.defaultCredentials(new LoginCredentials("root", false)).id("us-east-1/ami-7ea24a17") .defaultCredentials(LoginCredentials.builder().user("root").build()).id("us-east-1/ami-7ea24a17")
.providerId("ami-7ea24a17").location(defaultLocation) .providerId("ami-7ea24a17").location(defaultLocation)
.userMetadata(ImmutableMap.of( .userMetadata(ImmutableMap.of(
"owner", "206029621532", "owner", "206029621532",
@ -167,7 +167,7 @@ public class AWSEC2ImageParserTest {
new OperatingSystem.Builder().family(OsFamily.CENTOS).arch("paravirtual").version("5.4") new OperatingSystem.Builder().family(OsFamily.CENTOS).arch("paravirtual").version("5.4")
.description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml").is64Bit(true) .description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml").is64Bit(true)
.build()).description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml") .build()).description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml")
.defaultCredentials(new LoginCredentials("root", false)).id("us-east-1/ami-ccb35ea5") .defaultCredentials(LoginCredentials.builder().user("root").build()).id("us-east-1/ami-ccb35ea5")
.providerId("ami-ccb35ea5").location(defaultLocation).version("4.4.10") .providerId("ami-ccb35ea5").location(defaultLocation).version("4.4.10")
.userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store")) .userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store"))
.status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus("available").build()); .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus("available").build());
@ -194,7 +194,7 @@ public class AWSEC2ImageParserTest {
new OperatingSystem.Builder().family(OsFamily.AMZN_LINUX).arch("paravirtual") new OperatingSystem.Builder().family(OsFamily.AMZN_LINUX).arch("paravirtual")
.version("0.9.7-beta").description("137112412989/amzn-ami-0.9.7-beta.i386-ebs") .version("0.9.7-beta").description("137112412989/amzn-ami-0.9.7-beta.i386-ebs")
.is64Bit(false).build()).description("Amazon") .is64Bit(false).build()).description("Amazon")
.defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-82e4b5c7") .defaultCredentials(LoginCredentials.builder().user("ec2-user").build()).id("us-east-1/ami-82e4b5c7")
.providerId("ami-82e4b5c7").location(defaultLocation).version("0.9.7-beta") .providerId("ami-82e4b5c7").location(defaultLocation).version("0.9.7-beta")
.userMetadata(ImmutableMap.of( .userMetadata(ImmutableMap.of(
"owner", "137112412989", "owner", "137112412989",
@ -213,7 +213,7 @@ public class AWSEC2ImageParserTest {
.version("0.9.7-beta") .version("0.9.7-beta")
.description("amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml").is64Bit(true) .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") .build()).description("Amazon Linux AMI x86_64 S3")
.defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-f2e4b5b7") .defaultCredentials(LoginCredentials.builder().user("ec2-user").build()).id("us-east-1/ami-f2e4b5b7")
.providerId("ami-f2e4b5b7").location(defaultLocation).version("0.9.7-beta") .providerId("ami-f2e4b5b7").location(defaultLocation).version("0.9.7-beta")
.userMetadata(ImmutableMap.of( .userMetadata(ImmutableMap.of(
"owner", "137112412989", "owner", "137112412989",