mirror of https://github.com/apache/jclouds.git
cleaned up code references detected as unnecessary by UEC plugin
This commit is contained in:
parent
cd401757fc
commit
d57197c103
|
@ -80,7 +80,7 @@ public class FirewallClientLiveTest extends BaseCloudStackClientLiveTest {
|
|||
defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()),
|
||||
client, jobComplete, virtualMachineRunning);
|
||||
|
||||
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption())
|
||||
if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
|
||||
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
|
||||
|
||||
} catch (NoSuchElementException e) {
|
||||
|
|
|
@ -95,7 +95,7 @@ public class LoadBalancerClientLiveTest extends BaseCloudStackClientLiveTest {
|
|||
vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network,
|
||||
defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()),
|
||||
client, jobComplete, virtualMachineRunning);
|
||||
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption())
|
||||
if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
|
||||
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
|
||||
}
|
||||
|
||||
|
|
|
@ -181,7 +181,7 @@ public class SecurityGroupClientLiveTest extends BaseCloudStackClientLiveTest {
|
|||
vm = VirtualMachineClientLiveTest.createVirtualMachineWithSecurityGroupInZone(zone.getId(),
|
||||
defaultTemplateOrPreferredInZone(defaultTemplate, client, zone.getId()), group.getId(), client,
|
||||
jobComplete, virtualMachineRunning);
|
||||
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption())
|
||||
if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
|
||||
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
|
||||
// ingress port 22
|
||||
checkSSH(HostAndPort.fromParts(vm.getIPAddress(), 22));
|
||||
|
|
|
@ -284,7 +284,7 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest {
|
|||
}
|
||||
|
||||
private void conditionallyCheckSSH() {
|
||||
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption())
|
||||
if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
|
||||
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
|
||||
assert HostSpecifier.isValid(vm.getIPAddress());
|
||||
if (!InetAddresses2.isPrivateIPAddress(vm.getIPAddress())) {
|
||||
|
|
|
@ -66,7 +66,7 @@ public class StaticNATVirtualMachineInNetworkLiveTest extends NATClientLiveTest
|
|||
vm = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network,
|
||||
defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete,
|
||||
virtualMachineRunning);
|
||||
if (vm.getPassword() != null && !loginCredentials.hasPasswordOption())
|
||||
if (vm.getPassword() != null && loginCredentials.getOptionalPassword() == null)
|
||||
loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();
|
||||
} catch (NoSuchElementException e) {
|
||||
networksDisabled = true;
|
||||
|
|
|
@ -166,7 +166,7 @@ public class EC2TemplateBuilderTest {
|
|||
|
||||
final Image image = new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location)
|
||||
.operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true))
|
||||
.description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false))
|
||||
.description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.status(Image.Status.AVAILABLE)
|
||||
.build();
|
||||
Map<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(
|
||||
new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location)
|
||||
.operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true))
|
||||
.description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false))
|
||||
.description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.status(Image.Status.AVAILABLE)
|
||||
.build(),
|
||||
new ImageBuilder().providerId("normal-image").name("image").id("us-east-1/normal-image").location(location)
|
||||
.operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "paravirtual", "ubuntu", true))
|
||||
.description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false))
|
||||
.description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.status(Image.Status.AVAILABLE)
|
||||
.build()));
|
||||
|
||||
|
|
|
@ -67,7 +67,7 @@ public class EC2ImageParserTest {
|
|||
assertImageEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem(
|
||||
new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description(
|
||||
"137112412989/amzn-ami-0.9.7-beta.i386-ebs").is64Bit(false).build()).description("Amazon")
|
||||
.defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-82e4b5c7").name(
|
||||
.defaultCredentials(LoginCredentials.builder().user("ec2-user").build()).id("us-east-1/ami-82e4b5c7").name(
|
||||
"amzn-ami-0.9.7-beta.i386-ebs").providerId("ami-82e4b5c7").location(defaultLocation)
|
||||
.userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status(
|
||||
Status.AVAILABLE).backendStatus("available").build());
|
||||
|
@ -75,7 +75,7 @@ public class EC2ImageParserTest {
|
|||
assertImageEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem(
|
||||
new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description(
|
||||
"amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml").is64Bit(true).build())
|
||||
.description("Amazon Linux AMI x86_64 S3").defaultCredentials(new LoginCredentials("ec2-user", false))
|
||||
.description("Amazon Linux AMI x86_64 S3").defaultCredentials(LoginCredentials.builder().user("ec2-user").build())
|
||||
.id("us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").name("amzn-ami-0.9.7-beta.x86_64-S3").location(
|
||||
defaultLocation)
|
||||
.userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status(
|
||||
|
@ -86,7 +86,7 @@ public class EC2ImageParserTest {
|
|||
"amazon/NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10")
|
||||
.is64Bit(true).build())
|
||||
.description("Microsoft Windows Server 2008 R2 SP1 Datacenter 64-bit Multi-language AMI provided by Amazon")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/ami-85457ff1").providerId("ami-85457ff1").name("NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10")
|
||||
.location(defaultLocation)
|
||||
.userMetadata(ImmutableMap.of("owner", "801119661308", "rootDeviceType", "ebs"))
|
||||
|
|
|
@ -237,9 +237,7 @@ public class RunningInstanceToNodeMetadataTest {
|
|||
}
|
||||
|
||||
protected RunningInstance firstInstanceFromResource(String resource) {
|
||||
RunningInstance server = Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest
|
||||
.parseRunningInstances(resource), 0), 0);
|
||||
return server;
|
||||
return Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest.parseRunningInstances(resource), 0), 0);
|
||||
}
|
||||
|
||||
protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware,
|
||||
|
|
|
@ -71,7 +71,7 @@ public class NovaReviseParsedImageTest {
|
|||
.build())
|
||||
.name("Ubuntu Maverick 10.10 Server 64-bit 20111212")
|
||||
.description("")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/ami-000004d6")
|
||||
.providerId("ami-000004d6")
|
||||
.location(defaultLocation)
|
||||
|
|
|
@ -45,8 +45,8 @@ import com.google.inject.name.Names;
|
|||
// surefire
|
||||
@Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest")
|
||||
public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest {
|
||||
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = new ValueOfConfigurationKeyOrNull(
|
||||
Guice.createInjector());
|
||||
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = Guice.createInjector().getInstance(
|
||||
ValueOfConfigurationKeyOrNull.class);
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testIllegalArgumentWhenResourcesEmpty() {
|
||||
|
@ -91,16 +91,14 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest
|
|||
ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null);
|
||||
ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null);
|
||||
|
||||
assertEquals(new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(
|
||||
new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*");
|
||||
}
|
||||
|
||||
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
|
||||
reference2)), reference2);
|
||||
assertEquals(
|
||||
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(
|
||||
new AbstractModule() {
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*");
|
||||
}
|
||||
}).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<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 reference2 = new ReferenceTypeImpl("hail mary", null, null);
|
||||
|
||||
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(new ValueOfConfigurationKeyOrNull(
|
||||
Guice.createInjector(new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*");
|
||||
}
|
||||
|
||||
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
|
||||
reference2));
|
||||
|
||||
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(new AbstractModule() {
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*");
|
||||
}
|
||||
}).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<ReferenceType> alwaysTrue())
|
||||
.apply(ImmutableList.<ReferenceType> of(reference1, reference2));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -45,8 +45,8 @@ import com.google.inject.name.Names;
|
|||
// surefire
|
||||
@Test(groups = "unit", testName = "OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest")
|
||||
public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest {
|
||||
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = new ValueOfConfigurationKeyOrNull(
|
||||
Guice.createInjector());
|
||||
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull = Guice.createInjector().getInstance(
|
||||
ValueOfConfigurationKeyOrNull.class);
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testIllegalArgumentWhenResourcesEmpty() {
|
||||
|
@ -91,16 +91,14 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefaultTest
|
|||
ReferenceType reference1 = new ReferenceTypeImpl("travis tritt", null, null);
|
||||
ReferenceType reference2 = new ReferenceTypeImpl("hail mary", null, null);
|
||||
|
||||
assertEquals(new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(
|
||||
new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*");
|
||||
}
|
||||
|
||||
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
|
||||
reference2)), reference2);
|
||||
assertEquals(
|
||||
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(
|
||||
new AbstractModule() {
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*mary.*");
|
||||
}
|
||||
}).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<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 reference2 = new ReferenceTypeImpl("hail mary", null, null);
|
||||
|
||||
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(new ValueOfConfigurationKeyOrNull(
|
||||
Guice.createInjector(new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*");
|
||||
}
|
||||
|
||||
})), "foo", Predicates.<ReferenceType> alwaysTrue()).apply(ImmutableList.<ReferenceType> of(reference1,
|
||||
reference2));
|
||||
|
||||
new OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault(Guice.createInjector(new AbstractModule() {
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to(".*happy.*");
|
||||
}
|
||||
}).getInstance(ValueOfConfigurationKeyOrNull.class), "foo", Predicates.<ReferenceType> alwaysTrue())
|
||||
.apply(ImmutableList.<ReferenceType> of(reference1, reference2));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -86,7 +86,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
|
|||
public void testWithoutInitThrowsIllegalStateException() {
|
||||
Statement command = exec("doFoo");
|
||||
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials(
|
||||
new LoginCredentials("tester", "testpassword!", null, false)).build();
|
||||
LoginCredentials.builder().user("tester").password("testpassword!").build()).build();
|
||||
|
||||
SshClient sshClient = createMock(SshClient.class);
|
||||
|
||||
|
@ -153,7 +153,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
|
|||
public void testWithSudoPassword() {
|
||||
Statement command = exec("doFoo");
|
||||
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials(
|
||||
new LoginCredentials("tester", "testpassword!", null, true)).build();
|
||||
LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build();
|
||||
|
||||
SshClient sshClient = createMock(SshClient.class);
|
||||
|
||||
|
@ -206,7 +206,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
|
|||
public void testDoublecheckStatusInCaseTransientlyWrong() {
|
||||
Statement command = exec("doFoo");
|
||||
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials(
|
||||
new LoginCredentials("tester", "testpassword!", null, true)).build();
|
||||
LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build();
|
||||
|
||||
SshClient sshClient = createMock(SshClient.class);
|
||||
|
||||
|
@ -256,7 +256,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
|
|||
public void testNotRoot() {
|
||||
Statement command = exec("doFoo");
|
||||
NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials(
|
||||
new LoginCredentials("tester", "testpassword!", null, true)).build();
|
||||
LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build();
|
||||
|
||||
SshClient sshClient = createMock(SshClient.class);
|
||||
|
||||
|
@ -302,11 +302,10 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
|
|||
verify(sshClient);
|
||||
}
|
||||
|
||||
|
||||
public void testBadReturnCode() {
|
||||
Statement command = exec("doFoo");
|
||||
NodeMetadata node = new NodeMetadataBuilder().ids("badreturncode").status(Status.RUNNING).credentials(
|
||||
new LoginCredentials("tester", "testpassword!", null, true)).build();
|
||||
LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()).build();
|
||||
|
||||
SshClient sshClient = createMock(SshClient.class);
|
||||
|
||||
|
|
|
@ -57,7 +57,7 @@ public class RunScriptOnNodeUsingSshTest {
|
|||
}
|
||||
};
|
||||
node = createMock(NodeMetadata.class);
|
||||
expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "notalot", null, false)).atLeastOnce();
|
||||
expect(node.getCredentials()).andReturn(LoginCredentials.builder().user("tester").password("notalot").build()).atLeastOnce();
|
||||
replay(node);
|
||||
}
|
||||
|
||||
|
@ -97,7 +97,7 @@ public class RunScriptOnNodeUsingSshTest {
|
|||
|
||||
public void simpleRootTestWithSudoPassword() {
|
||||
node = createMock(NodeMetadata.class);
|
||||
expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "testpassword!", null, true))
|
||||
expect(node.getCredentials()).andReturn(LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build())
|
||||
.atLeastOnce();
|
||||
replay(node);
|
||||
RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"),
|
||||
|
|
|
@ -48,19 +48,16 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(null);
|
||||
expect(template.getOptions()).andReturn(new TemplateOptions());
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
verify(template, image);
|
||||
}
|
||||
|
||||
public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build();
|
||||
|
||||
public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() {
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
||||
|
@ -68,19 +65,14 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(null);
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
verify(template, image);
|
||||
}
|
||||
|
||||
public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
||||
|
@ -88,53 +80,40 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(expected);
|
||||
expect(template.getOptions()).andReturn(new TemplateOptions());
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
verify(template, image);
|
||||
}
|
||||
|
||||
public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
||||
expect(template.getImage()).andReturn(image);
|
||||
expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false));
|
||||
expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("user").password("password").build());
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
|
||||
verify(template, image);
|
||||
}
|
||||
|
||||
public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
||||
expect(template.getImage()).andReturn(image);
|
||||
expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false));
|
||||
expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password2").build());
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password"));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
verify(template, image);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -51,18 +51,16 @@ public class PrioritizeCredentialsFromTemplateTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(null);
|
||||
expect(template.getOptions()).andReturn(new TemplateOptions());
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, null), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() {
|
||||
LoginCredentials expected = new LoginCredentials("foo", "bar", null, false);
|
||||
LoginCredentials expected = LoginCredentials.builder().user("foo").password("bar").build();
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
@ -71,18 +69,16 @@ public class PrioritizeCredentialsFromTemplateTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(null);
|
||||
expect(template.getOptions()).andReturn(new TemplateOptions());
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, expected), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build();
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
@ -91,16 +87,14 @@ public class PrioritizeCredentialsFromTemplateTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(null);
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected);
|
||||
assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void testWhenCredentialsNotPresentInImageReturnsCredentialFromTemplateOptionsAndUserFromParameter() {
|
||||
Credentials expected = new Credentials("ubuntu", "password");
|
||||
|
||||
|
@ -111,18 +105,16 @@ public class PrioritizeCredentialsFromTemplateTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(null);
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, new LoginCredentials("foo", "password", null, false)), expected);
|
||||
assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("password").build()), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build();
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
@ -131,16 +123,14 @@ public class PrioritizeCredentialsFromTemplateTest {
|
|||
expect(image.getDefaultCredentials()).andReturn(expected);
|
||||
expect(template.getOptions()).andReturn(new TemplateOptions());
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected);
|
||||
assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptionsAndNotParameter() {
|
||||
Credentials expected = new Credentials("ubuntu", "password");
|
||||
|
||||
|
@ -148,36 +138,31 @@ public class PrioritizeCredentialsFromTemplateTest {
|
|||
Template template = createMock(Template.class);
|
||||
|
||||
expect(template.getImage()).andReturn(image);
|
||||
expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false));
|
||||
expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password").build());
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected);
|
||||
|
||||
verify(template, image);
|
||||
}
|
||||
|
||||
|
||||
public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() {
|
||||
LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
|
||||
LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").build();
|
||||
|
||||
Image image = createMock(Image.class);
|
||||
Template template = createMock(Template.class);
|
||||
|
||||
expect(template.getImage()).andReturn(image);
|
||||
expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false));
|
||||
expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password2").build());
|
||||
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password"));
|
||||
|
||||
replay(template);
|
||||
replay(image);
|
||||
replay(template, image);
|
||||
|
||||
assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected);
|
||||
assertEquals(fn.apply(template, LoginCredentials.builder().user("foo").password("bar").build()), expected);
|
||||
|
||||
verify(template);
|
||||
verify(image);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -39,12 +39,12 @@ import com.google.common.collect.ImmutableMap;
|
|||
*/
|
||||
@Test(groups = "unit", testName = "ReturnCredentialsBoundToImageTest")
|
||||
public class ReturnCredentialsBoundToImageTest {
|
||||
LoginCredentials creds = LoginCredentials.builder().user("ubuntu").password("foo").build();
|
||||
|
||||
public void testDefaultIsToReturnConfiguredCredential() {
|
||||
Image image = createMock(Image.class);
|
||||
replay(image);
|
||||
|
||||
LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false);
|
||||
assertEquals(new ReturnCredentialsBoundToImage(creds, ImmutableMap.<String, Credentials> of(), ImmutableMap
|
||||
.<OsFamily, LoginCredentials> of()).apply(image), creds);
|
||||
|
||||
|
@ -57,7 +57,6 @@ public class ReturnCredentialsBoundToImageTest {
|
|||
expect(image.getId()).andReturn("1").times(2);
|
||||
replay(image);
|
||||
|
||||
LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false);
|
||||
assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap.<String, Credentials> of("image#1", creds),
|
||||
ImmutableMap.<OsFamily, LoginCredentials> of()).apply(image), creds);
|
||||
|
||||
|
|
|
@ -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
|
||||
public ListenableFuture<ImmutableList<Object>> create(Throwable t) {
|
||||
return valOnNotFoundOr404(ImmutableList.of(), checkNotNull(t, "throwable"));
|
||||
|
@ -145,7 +145,7 @@ public final class Fallbacks {
|
|||
}
|
||||
}
|
||||
|
||||
public static final class EmptyMultimapOnNotFoundOr404 implements FutureFallback<ImmutableMultimap<Object, Object>> {
|
||||
public static final class EmptyMultimapOnNotFoundOr404 implements FutureFallback<ImmutableMultimap<Object, Object>> { // NO_UCD (unused code)
|
||||
@Override
|
||||
public ListenableFuture<ImmutableMultimap<Object, Object>> create(Throwable t) {
|
||||
return valOnNotFoundOr404(ImmutableMultimap.of(), checkNotNull(t, "throwable"));
|
||||
|
|
|
@ -48,7 +48,7 @@ public interface View {
|
|||
*
|
||||
* ex.
|
||||
* <pre>
|
||||
* RestContext<NovaClient, NovaAsyncClient> backendApi = computeContext.unwrap(NovaApiMetadata.CONTEXT_TOKEN);
|
||||
* RestContext<NovaApi, NovaAsyncApi> backendApi = computeContext.unwrap(NovaApiMetadata.CONTEXT_TOKEN);
|
||||
* </pre>
|
||||
* @param type
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* 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())}
|
||||
*
|
||||
|
|
|
@ -41,7 +41,7 @@ import com.google.common.reflect.TypeToken;
|
|||
*/
|
||||
public class Apis {
|
||||
|
||||
public static enum IdFunction implements Function<ApiMetadata, String> {
|
||||
private static enum IdFunction implements Function<ApiMetadata, String> {
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
|
|
|
@ -79,22 +79,21 @@ public abstract class BaseApiMetadata implements ApiMetadata {
|
|||
public static abstract class Builder<T extends Builder<T>> implements ApiMetadata.Builder<T> {
|
||||
protected abstract T self();
|
||||
|
||||
protected String id;
|
||||
protected String name;
|
||||
protected Set<TypeToken<? extends View>> views = ImmutableSet.of();
|
||||
protected String endpointName = "https endpoint";
|
||||
protected String identityName;
|
||||
protected Optional<String> credentialName = Optional.absent();
|
||||
protected String version = "";
|
||||
protected Optional<String> buildVersion = Optional.of("");
|
||||
protected Optional<String> defaultEndpoint = Optional.absent();
|
||||
protected Optional<String> defaultIdentity = Optional.absent();
|
||||
protected Optional<String> defaultCredential = Optional.absent();
|
||||
protected Properties defaultProperties = BaseApiMetadata.defaultProperties();
|
||||
protected URI documentation;
|
||||
//
|
||||
protected TypeToken<? extends Context> context = TypeToken.of(Context.class);
|
||||
protected Set<Class<? extends Module>> defaultModules = ImmutableSet.of();
|
||||
private String id;
|
||||
private String name;
|
||||
private Set<TypeToken<? extends View>> views = ImmutableSet.of();
|
||||
private String endpointName = "https endpoint";
|
||||
private String identityName;
|
||||
private Optional<String> credentialName = Optional.absent();
|
||||
private String version = "";
|
||||
private Optional<String> buildVersion = Optional.of("");
|
||||
private Optional<String> defaultEndpoint = Optional.absent();
|
||||
private Optional<String> defaultIdentity = Optional.absent();
|
||||
private Optional<String> defaultCredential = Optional.absent();
|
||||
private Properties defaultProperties = BaseApiMetadata.defaultProperties();
|
||||
private URI documentation;
|
||||
private TypeToken<? extends Context> context = TypeToken.of(Context.class);
|
||||
private Set<Class<? extends Module>> defaultModules = ImmutableSet.of();
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
|
@ -265,21 +264,21 @@ public abstract class BaseApiMetadata implements ApiMetadata {
|
|||
}
|
||||
}
|
||||
|
||||
protected final String id;
|
||||
protected final String name;
|
||||
protected final Set<TypeToken<? extends View>> views;
|
||||
protected final String endpointName;
|
||||
protected final String identityName;
|
||||
protected final Optional<String> credentialName;
|
||||
protected final String version;
|
||||
protected final Optional<String> buildVersion;
|
||||
protected final Optional<String> defaultEndpoint;
|
||||
protected final Optional<String> defaultIdentity;
|
||||
protected final Optional<String> defaultCredential;
|
||||
protected final Properties defaultProperties;
|
||||
protected final URI documentation;
|
||||
protected final TypeToken<? extends Context> context;
|
||||
protected final Set<Class<? extends Module>> defaultModules;
|
||||
private final String id;
|
||||
private final String name;
|
||||
private final Set<TypeToken<? extends View>> views;
|
||||
private final String endpointName;
|
||||
private final String identityName;
|
||||
private final Optional<String> credentialName;
|
||||
private final String version;
|
||||
private final Optional<String> buildVersion;
|
||||
private final Optional<String> defaultEndpoint;
|
||||
private final Optional<String> defaultIdentity;
|
||||
private final Optional<String> defaultCredential;
|
||||
private final Properties defaultProperties;
|
||||
private final URI documentation;
|
||||
private final TypeToken<? extends Context> context;
|
||||
private final Set<Class<? extends Module>> defaultModules;
|
||||
|
||||
protected BaseApiMetadata(Builder<?> builder) {
|
||||
this(builder.id, builder.name, builder.views, builder.endpointName, builder.identityName, builder.credentialName,
|
||||
|
@ -288,7 +287,7 @@ public abstract class BaseApiMetadata implements ApiMetadata {
|
|||
builder.defaultModules);
|
||||
}
|
||||
|
||||
public BaseApiMetadata(String id, String name, Set<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> defaultEndpoint, Optional<String> defaultIdentity, Optional<String> defaultCredential,
|
||||
Properties defaultProperties, URI documentation, TypeToken<? extends Context> context,
|
||||
|
|
|
@ -21,7 +21,6 @@ package org.jclouds.cache;
|
|||
import java.util.Map;
|
||||
|
||||
import com.google.common.annotations.Beta;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
|
||||
|
@ -56,24 +55,4 @@ public abstract class ForwardingCacheLoader<K, V> extends CacheLoader<K, V> {
|
|||
public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
|
||||
return delegate().loadAll(keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* A simplified version of {@link ForwardingCacheLoader} where subclasses can pass in an already
|
||||
* constructed {@link CacheLoader} as the delegate.
|
||||
*
|
||||
*/
|
||||
@Beta
|
||||
public static class SimpleForwardingCacheLoader<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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -85,9 +85,9 @@ public class RetryingCacheLoaderDecorator<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");
|
||||
}
|
||||
|
||||
|
@ -107,7 +107,7 @@ public class RetryingCacheLoaderDecorator<K, V> {
|
|||
private int maxTries = 5;
|
||||
private final Class<? extends Throwable> retryableThrowable;
|
||||
|
||||
protected BackoffExponentiallyAndRetryOnThrowableCacheLoaderDecorator(Class<? extends Throwable> retryableThrowable) {
|
||||
private BackoffExponentiallyAndRetryOnThrowableCacheLoaderDecorator(Class<? extends Throwable> retryableThrowable) {
|
||||
this.retryableThrowable = checkNotNull(retryableThrowable, "retryableThrowable");
|
||||
}
|
||||
|
||||
|
|
|
@ -81,7 +81,7 @@ class BackoffExponentiallyAndRetryOnThrowableCallable<T> extends ForwardingObjec
|
|||
throw currentException;
|
||||
}
|
||||
|
||||
void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max) {
|
||||
private void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max) {
|
||||
long delayMs = (long) (period * Math.pow(failureCount, pow));
|
||||
delayMs = delayMs > maxPeriod ? maxPeriod : delayMs;
|
||||
try {
|
||||
|
|
|
@ -25,13 +25,10 @@ import org.jclouds.javax.annotation.Nullable;
|
|||
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();
|
||||
|
||||
public abstract V getValue();
|
||||
|
||||
public V setValue(V value) {
|
||||
@Override
|
||||
public V setValue(V value) { // NO_UCD
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
|
@ -51,9 +48,6 @@ public abstract class AbstractMapEntry<K, V> implements Entry<K, V> {
|
|||
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string representation of the form <code>{key}={value}</code>.
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return getKey() + "=" + getValue();
|
||||
|
|
|
@ -53,13 +53,13 @@ public class AdvanceUntilEmptyIterable<E> extends FluentIterable<FluentIterable<
|
|||
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 transient FluentIterable<E> current;
|
||||
private transient boolean unread = true;
|
||||
|
||||
AdvanceUntilEmptyIterator(Supplier<FluentIterable<E>> nextIterable) {
|
||||
private AdvanceUntilEmptyIterator(Supplier<FluentIterable<E>> nextIterable) {
|
||||
this.nextIterable = checkNotNull(nextIterable, "next iterable");
|
||||
}
|
||||
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -39,8 +39,8 @@ import com.google.common.io.InputSupplier;
|
|||
*
|
||||
*/
|
||||
public class InputSupplierMap<K, V> extends AbstractMap<K, V> {
|
||||
final Map<K, InputSupplier<V>> toMap;
|
||||
final Function<V, InputSupplier<V>> putFunction;
|
||||
private final Map<K, InputSupplier<V>> toMap;
|
||||
private final Function<V, InputSupplier<V>> putFunction;
|
||||
|
||||
public InputSupplierMap(Map<K, InputSupplier<V>> toMap, Function<V, InputSupplier<V>> putFunction) {
|
||||
this.toMap = checkNotNull(toMap);
|
||||
|
@ -91,10 +91,9 @@ public class InputSupplierMap<K, V> extends AbstractMap<K, V> {
|
|||
@Override
|
||||
public Set<Entry<K, V>> entrySet() {
|
||||
return new EntrySet();
|
||||
|
||||
}
|
||||
|
||||
class EntrySet extends AbstractSet<Entry<K, V>> {
|
||||
private class EntrySet extends AbstractSet<Entry<K, V>> {
|
||||
@Override
|
||||
public int size() {
|
||||
return InputSupplierMap.this.size();
|
||||
|
|
|
@ -86,7 +86,20 @@ public class IterableWithMarkers {
|
|||
public Optional<Object> nextMarker() {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -35,17 +35,7 @@ import com.google.common.collect.ImmutableSet;
|
|||
*/
|
||||
@Beta
|
||||
public class PagedIterables {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static final PagedIterable EMPTY = new PagedIterable() {
|
||||
|
||||
@Override
|
||||
public Iterator<IterableWithMarker> iterator() {
|
||||
return ImmutableSet.of(IterableWithMarkers.EMPTY).iterator();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @param only
|
||||
* the only page of data
|
||||
|
@ -154,7 +144,7 @@ public class PagedIterables {
|
|||
* @return iterable current data which continues if the user iterates beyond
|
||||
* the first page
|
||||
*/
|
||||
public static <T> Iterator<IterableWithMarker<T>> advancingIterator(IterableWithMarker<T> initial,
|
||||
private static <T> Iterator<IterableWithMarker<T>> advancingIterator(IterableWithMarker<T> initial,
|
||||
Function<Object, IterableWithMarker<T>> markerToNext) {
|
||||
if (!initial.nextMarker().isPresent()) {
|
||||
return ImmutableSet.of(initial).iterator();
|
||||
|
|
|
@ -36,9 +36,9 @@ import com.google.common.base.Function;
|
|||
*
|
||||
*/
|
||||
public class TransformingMap<K, V1, V2> extends AbstractMap<K, V2> {
|
||||
final Map<K, V1> fromMap;
|
||||
final Function<? super V1, V2> getFunction;
|
||||
final Function<? super V2, V1> putFunction;
|
||||
private final Map<K, V1> fromMap;
|
||||
private final Function<? super V1, V2> getFunction;
|
||||
private final 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);
|
||||
|
@ -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
|
||||
public int size() {
|
||||
return TransformingMap.this.size();
|
||||
|
|
|
@ -19,7 +19,6 @@
|
|||
package org.jclouds.concurrent;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
@ -30,45 +29,23 @@ import java.util.concurrent.TimeUnit;
|
|||
* @author kimchy (shay.banon)
|
||||
*/
|
||||
public class DynamicExecutors {
|
||||
/**
|
||||
* Creates a thread pool that creates new threads as needed, but will reuse previously
|
||||
* constructed threads when they are available. Calls to <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
|
||||
* provided ThreadFactory to create new threads when needed.
|
||||
* Creates a thread pool, same as in {@link #newScalingThreadPool(int, int, long)}, using the provided ThreadFactory
|
||||
* to create new threads when needed.
|
||||
*
|
||||
* @param min
|
||||
* the number of threads to keep in the pool, even if they are idle.
|
||||
* @param max
|
||||
* the maximum number of threads to allow in the pool.
|
||||
* @param keepAliveTime
|
||||
* when the number of threads is greater than the min, this is the maximum time that
|
||||
* excess idle threads will wait for new tasks before terminating (in milliseconds).
|
||||
* when the number of threads is greater than the min, this is the maximum time that excess idle threads
|
||||
* will wait for new tasks before terminating (in milliseconds).
|
||||
* @param threadFactory
|
||||
* the factory to use when creating new threads.
|
||||
* @return the newly created thread pool
|
||||
*/
|
||||
public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime,
|
||||
ThreadFactory threadFactory) {
|
||||
public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime, ThreadFactory threadFactory) {
|
||||
DynamicThreadPoolExecutor.DynamicQueue<Runnable> queue = new DynamicThreadPoolExecutor.DynamicQueue<Runnable>();
|
||||
ThreadPoolExecutor executor = new DynamicThreadPoolExecutor(min, max, keepAliveTime,
|
||||
TimeUnit.MILLISECONDS, queue, threadFactory);
|
||||
|
@ -77,128 +54,6 @@ public class DynamicExecutors {
|
|||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a thread pool similar to that constructed by
|
||||
* {@link #newScalingThreadPool(int, int, long)}, but blocks the call to <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.
|
||||
*/
|
||||
|
|
|
@ -17,23 +17,23 @@
|
|||
* under the License.
|
||||
*/
|
||||
/*
|
||||
* Licensed to Elastic Search and Shay Banon under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. Elastic Search licenses this
|
||||
* file to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
* Licensed to Elastic Search and Shay Banon under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. Elastic Search licenses this
|
||||
* file to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.jclouds.concurrent;
|
||||
|
||||
|
@ -47,140 +47,138 @@ import java.util.concurrent.TimeUnit;
|
|||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* An {@link ExecutorService} that executes each submitted task using one of
|
||||
* possibly several pooled threads, normally configured using
|
||||
* {@link DynamicExecutors} factory methods.
|
||||
*
|
||||
* @author kimchy (shay.banon)
|
||||
*/
|
||||
public class DynamicThreadPoolExecutor extends ThreadPoolExecutor {
|
||||
/**
|
||||
* number of threads that are actively executing tasks
|
||||
*/
|
||||
private final AtomicInteger activeCount = new AtomicInteger();
|
||||
* An {@link ExecutorService} that executes each submitted task using one of possibly several pooled threads, normally
|
||||
* configured using {@link DynamicExecutors} factory methods.
|
||||
*
|
||||
* @author kimchy (shay.banon)
|
||||
*/
|
||||
class DynamicThreadPoolExecutor extends ThreadPoolExecutor {
|
||||
/**
|
||||
* number of threads that are actively executing tasks
|
||||
*/
|
||||
private final AtomicInteger activeCount = new AtomicInteger();
|
||||
|
||||
public DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
|
||||
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue,
|
||||
ThreadFactory threadFactory) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
|
||||
}
|
||||
DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
|
||||
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
|
||||
}
|
||||
|
||||
@Override public int getActiveCount() {
|
||||
return activeCount.get();
|
||||
}
|
||||
@Override
|
||||
public int getActiveCount() {
|
||||
return activeCount.get();
|
||||
}
|
||||
|
||||
@Override protected void beforeExecute(Thread t, Runnable r) {
|
||||
activeCount.incrementAndGet();
|
||||
}
|
||||
@Override
|
||||
protected void beforeExecute(Thread t, Runnable r) {
|
||||
activeCount.incrementAndGet();
|
||||
}
|
||||
|
||||
@Override protected void afterExecute(Runnable r, Throwable t) {
|
||||
activeCount.decrementAndGet();
|
||||
}
|
||||
@Override
|
||||
protected void afterExecute(Runnable r, Throwable t) {
|
||||
activeCount.decrementAndGet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It
|
||||
* is well suited for handoff designs, in which a tasks is only queued if there
|
||||
* is an available thread to pick it up.
|
||||
* <p/>
|
||||
* This queue is correlated with a thread-pool, and allows insertions to the
|
||||
* queue only if there is a free thread that can poll this task. Otherwise, the
|
||||
* task is rejected and the decision is left up to one of the
|
||||
* {@link RejectedExecutionHandler} policies:
|
||||
* <ol>
|
||||
* <li> {@link ForceQueuePolicy} - forces the queue to accept the rejected task. </li>
|
||||
* <li> {@link TimedBlockingPolicy} - waits for a given time for the task to be
|
||||
* executed.</li>
|
||||
* </ol>
|
||||
*
|
||||
* @author kimchy (Shay Banon)
|
||||
*/
|
||||
public static class DynamicQueue<E> extends LinkedBlockingQueue<E> {
|
||||
/**
|
||||
* Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It is well suited for handoff designs, in
|
||||
* which a tasks is only queued if there is an available thread to pick it up.
|
||||
* <p/>
|
||||
* This queue is correlated with a thread-pool, and allows insertions to the queue only if there is a free thread
|
||||
* that can poll this task. Otherwise, the task is rejected and the decision is left up to one of the
|
||||
* {@link RejectedExecutionHandler} policies:
|
||||
* <ol>
|
||||
* <li> {@link ForceQueuePolicy} - forces the queue to accept the rejected task.</li>
|
||||
* <li> {@link TimedBlockingPolicy} - waits for a given time for the task to be executed.</li>
|
||||
* </ol>
|
||||
*
|
||||
* @author kimchy (Shay Banon)
|
||||
*/
|
||||
static class DynamicQueue<E> extends LinkedBlockingQueue<E> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* The executor this Queue belongs to
|
||||
*/
|
||||
private transient ThreadPoolExecutor executor;
|
||||
/**
|
||||
* The executor this Queue belongs to
|
||||
*/
|
||||
private transient ThreadPoolExecutor executor;
|
||||
|
||||
/**
|
||||
* Creates a <tt>DynamicQueue</tt> with a capacity of
|
||||
* {@link Integer#MAX_VALUE}.
|
||||
*/
|
||||
public DynamicQueue() {
|
||||
super();
|
||||
}
|
||||
/**
|
||||
* Creates a <tt>DynamicQueue</tt> with a capacity of {@link Integer#MAX_VALUE}.
|
||||
*/
|
||||
public DynamicQueue() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <tt>DynamicQueue</tt> with the given (fixed) capacity.
|
||||
*
|
||||
* @param capacity the capacity of this queue.
|
||||
*/
|
||||
public DynamicQueue(int capacity) {
|
||||
super(capacity);
|
||||
}
|
||||
/**
|
||||
* Creates a <tt>DynamicQueue</tt> with the given (fixed) capacity.
|
||||
*
|
||||
* @param capacity
|
||||
* the capacity of this queue.
|
||||
*/
|
||||
DynamicQueue(int capacity) {
|
||||
super(capacity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the executor this queue belongs to.
|
||||
*/
|
||||
public void setThreadPoolExecutor(ThreadPoolExecutor executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
/**
|
||||
* Sets the executor this queue belongs to.
|
||||
*/
|
||||
public void setThreadPoolExecutor(ThreadPoolExecutor executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the specified element at the tail of this queue if there is at
|
||||
* least one available thread to run the current task. If all pool threads
|
||||
* are actively busy, it rejects the offer.
|
||||
*
|
||||
* @param o the element to add.
|
||||
* @return <tt>true</tt> if it was possible to add the element to this
|
||||
* queue, else <tt>false</tt>
|
||||
* @see ThreadPoolExecutor#execute(Runnable)
|
||||
*/
|
||||
@Override
|
||||
public boolean offer(E o) {
|
||||
int allWorkingThreads = executor.getActiveCount() + super.size();
|
||||
return allWorkingThreads < executor.getPoolSize() && super.offer(o);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Inserts the specified element at the tail of this queue if there is at least one available thread to run the
|
||||
* current task. If all pool threads are actively busy, it rejects the offer.
|
||||
*
|
||||
* @param o
|
||||
* the element to add.
|
||||
* @return <tt>true</tt> if it was possible to add the element to this queue, else <tt>false</tt>
|
||||
* @see ThreadPoolExecutor#execute(Runnable)
|
||||
*/
|
||||
@Override
|
||||
public boolean offer(E o) {
|
||||
int allWorkingThreads = executor.getActiveCount() + super.size();
|
||||
return allWorkingThreads < executor.getPoolSize() && super.offer(o);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler for rejected tasks that adds the specified element to this queue,
|
||||
* waiting if necessary for space to become available.
|
||||
*/
|
||||
public static class ForceQueuePolicy implements RejectedExecutionHandler {
|
||||
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
|
||||
try {
|
||||
executor.getQueue().put(r);
|
||||
} catch (InterruptedException e) {
|
||||
//should never happen since we never wait
|
||||
throw new RejectedExecutionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A handler for rejected tasks that adds the specified element to this queue, waiting if necessary for space to
|
||||
* become available.
|
||||
*/
|
||||
static class ForceQueuePolicy implements RejectedExecutionHandler {
|
||||
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
|
||||
try {
|
||||
executor.getQueue().put(r);
|
||||
} catch (InterruptedException e) {
|
||||
// should never happen since we never wait
|
||||
throw new RejectedExecutionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler for rejected tasks that inserts the specified element into this
|
||||
* queue, waiting if necessary up to the specified wait time for space to become
|
||||
* available.
|
||||
*/
|
||||
public static class TimedBlockingPolicy implements RejectedExecutionHandler {
|
||||
private final long waitTime;
|
||||
/**
|
||||
* A handler for rejected tasks that inserts the specified element into this queue, waiting if necessary up to the
|
||||
* specified wait time for space to become available.
|
||||
*/
|
||||
static class TimedBlockingPolicy implements RejectedExecutionHandler {
|
||||
private final long waitTime;
|
||||
|
||||
/**
|
||||
* @param waitTime wait time in milliseconds for space to become available.
|
||||
*/
|
||||
public TimedBlockingPolicy(long waitTime) {
|
||||
this.waitTime = waitTime;
|
||||
}
|
||||
/**
|
||||
* @param waitTime
|
||||
* wait time in milliseconds for space to become available.
|
||||
*/
|
||||
TimedBlockingPolicy(long waitTime) {
|
||||
this.waitTime = waitTime;
|
||||
}
|
||||
|
||||
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
|
||||
try {
|
||||
boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS);
|
||||
if (!successful)
|
||||
throw new RejectedExecutionException("Rejected execution after waiting "
|
||||
+ waitTime + " ms for task [" + r.getClass() + "] to be executed.");
|
||||
} catch (InterruptedException e) {
|
||||
throw new RejectedExecutionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
|
||||
try {
|
||||
boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS);
|
||||
if (!successful)
|
||||
throw new RejectedExecutionException("Rejected execution after waiting " + waitTime + " ms for task ["
|
||||
+ r.getClass() + "] to be executed.");
|
||||
} catch (InterruptedException e) {
|
||||
throw new RejectedExecutionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -56,8 +56,6 @@ import com.google.inject.Inject;
|
|||
*/
|
||||
@Beta
|
||||
public class FutureIterables {
|
||||
@Resource
|
||||
private static Logger logger = Logger.CONSOLE;
|
||||
|
||||
@Inject(optional = true)
|
||||
@Named(Constants.PROPERTY_MAX_RETRIES)
|
||||
|
@ -69,17 +67,7 @@ public class FutureIterables {
|
|||
|
||||
@Inject(optional = true)
|
||||
private static BackoffLimitedRetryHandler retryHandler = BackoffLimitedRetryHandler.INSTANCE;
|
||||
|
||||
public static <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,
|
||||
final Function<? super F, Future<? extends T>> function, ExecutorService exec, @Nullable Long maxTime, Logger logger,
|
||||
String logPrefix) {
|
||||
|
@ -113,8 +101,8 @@ public class FutureIterables {
|
|||
}
|
||||
//make sure we propagate any authorization exception so that we don't lock out accounts
|
||||
if (exceptions.size() > 0)
|
||||
return propagateAuthorizationOrOriginalException(new TransformParallelException((Map) responses, exceptions,
|
||||
logPrefix));
|
||||
return propagateAuthorizationOrOriginalException(new TransformParallelException(Map.class.cast(responses),
|
||||
exceptions, logPrefix));
|
||||
|
||||
return unwrap(responses.values());
|
||||
}
|
||||
|
@ -180,7 +168,7 @@ public class FutureIterables {
|
|||
return errorMap;
|
||||
}
|
||||
|
||||
public static <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>() {
|
||||
@Override
|
||||
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,
|
||||
(long) ((System.currentTimeMillis() - start) / ((double) size)));
|
||||
}
|
||||
|
||||
protected static boolean timeOut(long start, Long maxTime) {
|
||||
return maxTime != null ? System.currentTimeMillis() < start + maxTime : false;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -48,7 +48,7 @@ public class Futures {
|
|||
private final Future<T> delegate;
|
||||
private final ExecutionList executionList;
|
||||
|
||||
public CallGetAndRunExecutionList(Future<T> delegate, ExecutionList executionList) {
|
||||
CallGetAndRunExecutionList(Future<T> delegate, ExecutionList executionList) {
|
||||
this.delegate = checkNotNull(delegate, "delegate");
|
||||
this.executionList = checkNotNull(executionList, "executionList");
|
||||
}
|
||||
|
@ -84,9 +84,9 @@ public class Futures {
|
|||
// note that this is done so that we can operate in Google AppEngine which
|
||||
// restricts thread creation
|
||||
// * to allow us to print debug info about what the delegate was doing
|
||||
public static class FutureListener<T> {
|
||||
private static class FutureListener<T> {
|
||||
|
||||
final ExecutorService adapterExecutor;
|
||||
private final ExecutorService adapterExecutor;
|
||||
|
||||
// The execution list to hold our listeners.
|
||||
private final ExecutionList executionList = new ExecutionList();
|
||||
|
@ -98,7 +98,7 @@ public class Futures {
|
|||
// The delegate future.
|
||||
private final Future<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);
|
||||
}
|
||||
|
||||
|
@ -107,7 +107,7 @@ public class Futures {
|
|||
this.adapterExecutor = checkNotNull(adapterExecutor, "adapterExecutor");
|
||||
}
|
||||
|
||||
public void addListener(Runnable listener, Executor exec) {
|
||||
private void addListener(Runnable listener, Executor exec) {
|
||||
executionList.add(listener, exec);
|
||||
|
||||
// When a listener is first added, we run a task that will wait for
|
||||
|
@ -123,19 +123,15 @@ public class Futures {
|
|||
}
|
||||
}
|
||||
|
||||
Future<T> getFuture() {
|
||||
private Future<T> getFuture() {
|
||||
return delegate;
|
||||
}
|
||||
|
||||
ExecutorService getExecutor() {
|
||||
return adapterExecutor;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ListenableFutureAdapter<T> extends ForwardingFuture<T> implements ListenableFuture<T> {
|
||||
final FutureListener<T> futureListener;
|
||||
private static class ListenableFutureAdapter<T> extends ForwardingFuture<T> implements ListenableFuture<T> {
|
||||
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);
|
||||
}
|
||||
|
||||
|
@ -152,20 +148,19 @@ public class Futures {
|
|||
public void addListener(Runnable listener, Executor 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> {
|
||||
private final FutureListener<I> futureListener;
|
||||
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) {
|
||||
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) {
|
||||
return new LazyListenableFutureFunctionAdapter<I, O>(futureListener, function);
|
||||
}
|
||||
|
|
|
@ -29,6 +29,7 @@ import com.google.common.collect.Iterables;
|
|||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public final class TransformParallelException extends RuntimeException {
|
||||
|
||||
private final Map<?, Future<?>> success;
|
||||
|
|
|
@ -23,12 +23,12 @@ import java.util.concurrent.Future;
|
|||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
public class DescribedFuture<T> implements Future<T> {
|
||||
class DescribedFuture<T> implements Future<T> {
|
||||
protected final Future<T> delegate;
|
||||
private final String description;
|
||||
private StackTraceElement[] submissionTrace;
|
||||
|
||||
public DescribedFuture(Future<T> delegate, String description, StackTraceElement[] submissionTrace) {
|
||||
DescribedFuture(Future<T> delegate, String description, StackTraceElement[] submissionTrace) {
|
||||
this.delegate = delegate;
|
||||
this.description = description;
|
||||
this.submissionTrace = submissionTrace;
|
||||
|
|
|
@ -19,6 +19,7 @@
|
|||
package org.jclouds.concurrent.config;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
import static org.jclouds.concurrent.config.ExecutorServiceModule.getStackTraceHere;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
@ -86,18 +87,18 @@ public class DescribingExecutorService implements ExecutorService {
|
|||
|
||||
@Override
|
||||
public <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" })
|
||||
@Override
|
||||
public Future<?> submit(Runnable task) {
|
||||
return new DescribedFuture(delegate.submit(task), task.toString(), ExecutorServiceModule.getStackTraceHere());
|
||||
return new DescribedFuture(delegate.submit(task), task.toString(), getStackTraceHere());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Future<T> submit(Runnable task, T result) {
|
||||
return new DescribedFuture<T>(delegate.submit(task, result), task.toString(), ExecutorServiceModule.getStackTraceHere());
|
||||
public <T> Future<T> submit(Runnable task, T result) { // NO_UCD
|
||||
return new DescribedFuture<T>(delegate.submit(task, result), task.toString(), getStackTraceHere());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -18,6 +18,8 @@
|
|||
*/
|
||||
package org.jclouds.concurrent.config;
|
||||
|
||||
import static org.jclouds.Constants.PROPERTY_IO_WORKER_THREADS;
|
||||
import static org.jclouds.Constants.PROPERTY_USER_THREADS;
|
||||
import static org.jclouds.concurrent.DynamicExecutors.newScalingThreadPool;
|
||||
|
||||
import java.io.Closeable;
|
||||
|
@ -32,13 +34,11 @@ import javax.inject.Inject;
|
|||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.Constants;
|
||||
import org.jclouds.concurrent.MoreExecutors;
|
||||
import org.jclouds.concurrent.SingleThreaded;
|
||||
import org.jclouds.lifecycle.Closer;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.util.concurrent.ThreadFactoryBuilder;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Provides;
|
||||
|
@ -47,21 +47,20 @@ import com.google.inject.Provides;
|
|||
* Configures {@link ExecutorService}.
|
||||
*
|
||||
* Note that this uses threads.
|
||||
*
|
||||
*
|
||||
* <p>
|
||||
* This extends the underlying Future to expose a description (the task's toString) and the submission context (stack trace).
|
||||
* The submission stack trace is appended to relevant stack traces on exceptions that are returned,
|
||||
* so the user can see the logical chain of execution (in the executor, and where it was passed to the executor).
|
||||
* This extends the underlying Future to expose a description (the task's toString) and the submission context (stack
|
||||
* trace). The submission stack trace is appended to relevant stack traces on exceptions that are returned, so the user
|
||||
* can see the logical chain of execution (in the executor, and where it was passed to the executor).
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@ConfiguresExecutorService
|
||||
public class ExecutorServiceModule extends AbstractModule {
|
||||
|
||||
@VisibleForTesting
|
||||
static final class ShutdownExecutorOnClose implements Closeable {
|
||||
@Resource
|
||||
protected Logger logger = Logger.NULL;
|
||||
private Logger logger = Logger.NULL;
|
||||
|
||||
private final ExecutorService service;
|
||||
|
||||
|
@ -77,32 +76,31 @@ public class ExecutorServiceModule extends AbstractModule {
|
|||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
final ExecutorService userExecutorFromConstructor;
|
||||
@VisibleForTesting
|
||||
|
||||
final ExecutorService ioExecutorFromConstructor;
|
||||
|
||||
@Inject
|
||||
public ExecutorServiceModule(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads,
|
||||
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads) {
|
||||
public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userThreads,
|
||||
@Named(PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads) {
|
||||
this.userExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(userThreads));
|
||||
this.ioExecutorFromConstructor = addToStringOnSubmit(checkNotGuavaSameThreadExecutor(ioThreads));
|
||||
}
|
||||
|
||||
ExecutorService addToStringOnSubmit(ExecutorService executor) {
|
||||
private ExecutorService addToStringOnSubmit(ExecutorService executor) {
|
||||
if (executor != null) {
|
||||
return new DescribingExecutorService(executor);
|
||||
}
|
||||
return executor;
|
||||
}
|
||||
|
||||
ExecutorService checkNotGuavaSameThreadExecutor(ExecutorService executor) {
|
||||
private ExecutorService checkNotGuavaSameThreadExecutor(ExecutorService executor) {
|
||||
// we detect behavior based on the class
|
||||
if (executor != null && !(executor.getClass().isAnnotationPresent(SingleThreaded.class))
|
||||
&& executor.getClass().getSimpleName().indexOf("SameThread") != -1) {
|
||||
&& executor.getClass().getSimpleName().indexOf("SameThread") != -1) {
|
||||
Logger.CONSOLE.warn(
|
||||
"please switch from %s to %s or annotate your same threaded executor with @SingleThreaded", executor
|
||||
.getClass().getName(), MoreExecutors.SameThreadExecutorService.class.getName());
|
||||
"please switch from %s to %s or annotate your same threaded executor with @SingleThreaded", executor
|
||||
.getClass().getName(), MoreExecutors.SameThreadExecutorService.class.getName());
|
||||
return MoreExecutors.sameThreadExecutor();
|
||||
}
|
||||
return executor;
|
||||
|
@ -113,13 +111,13 @@ public class ExecutorServiceModule extends AbstractModule {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
protected void configure() { // NO_UCD
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@Named(Constants.PROPERTY_USER_THREADS)
|
||||
ExecutorService provideExecutorService(@Named(Constants.PROPERTY_USER_THREADS) int count, Closer closer) {
|
||||
@Named(PROPERTY_USER_THREADS)
|
||||
ExecutorService provideExecutorService(@Named(PROPERTY_USER_THREADS) int count, Closer closer) { // NO_UCD
|
||||
if (userExecutorFromConstructor != null)
|
||||
return userExecutorFromConstructor;
|
||||
return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("user thread %d", count)), closer);
|
||||
|
@ -127,47 +125,42 @@ public class ExecutorServiceModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
@Named(Constants.PROPERTY_IO_WORKER_THREADS)
|
||||
ExecutorService provideIOExecutor(@Named(Constants.PROPERTY_IO_WORKER_THREADS) int count, Closer closer) {
|
||||
@Named(PROPERTY_IO_WORKER_THREADS)
|
||||
ExecutorService provideIOExecutor(@Named(PROPERTY_IO_WORKER_THREADS) int count, Closer closer) { // NO_UCD
|
||||
if (ioExecutorFromConstructor != null)
|
||||
return ioExecutorFromConstructor;
|
||||
return shutdownOnClose(addToStringOnSubmit(newThreadPoolNamed("i/o thread %d", count)), closer);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static <T extends ExecutorService> T shutdownOnClose(final T service, Closer closer) {
|
||||
closer.addToClose(new ShutdownExecutorOnClose(service));
|
||||
return service;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ExecutorService newCachedThreadPoolNamed(String name) {
|
||||
private ExecutorService newCachedThreadPoolNamed(String name) {
|
||||
return Executors.newCachedThreadPool(namedThreadFactory(name));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ExecutorService newThreadPoolNamed(String name, int maxCount) {
|
||||
private ExecutorService newThreadPoolNamed(String name, int maxCount) {
|
||||
return maxCount == 0 ? newCachedThreadPoolNamed(name) : newScalingThreadPoolNamed(name, maxCount);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ExecutorService newScalingThreadPoolNamed(String name, int maxCount) {
|
||||
private ExecutorService newScalingThreadPoolNamed(String name, int maxCount) {
|
||||
return newScalingThreadPool(1, maxCount, 60L * 1000, namedThreadFactory(name));
|
||||
}
|
||||
|
||||
protected ThreadFactory namedThreadFactory(String name) {
|
||||
private ThreadFactory namedThreadFactory(String name) {
|
||||
return new ThreadFactoryBuilder().setNameFormat(name).setThreadFactory(Executors.defaultThreadFactory()).build();
|
||||
}
|
||||
|
||||
|
||||
/** returns the stack trace at the caller */
|
||||
static StackTraceElement[] getStackTraceHere() {
|
||||
// remove the first two items in the stack trace (because the first one refers to the call to
|
||||
// remove the first two items in the stack trace (because the first one refers to the call to
|
||||
// Thread.getStackTrace, and the second one is us)
|
||||
StackTraceElement[] fullSubmissionTrace = Thread.currentThread().getStackTrace();
|
||||
StackTraceElement[] cleanedSubmissionTrace = new StackTraceElement[fullSubmissionTrace.length-2];
|
||||
StackTraceElement[] cleanedSubmissionTrace = new StackTraceElement[fullSubmissionTrace.length - 2];
|
||||
System.arraycopy(fullSubmissionTrace, 2, cleanedSubmissionTrace, 0, cleanedSubmissionTrace.length);
|
||||
return cleanedSubmissionTrace;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
package org.jclouds.concurrent.config;
|
||||
|
||||
import static org.jclouds.concurrent.config.ExecutorServiceModule.shutdownOnClose;
|
||||
import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS;
|
||||
import static org.jclouds.concurrent.config.ExecutorServiceModule.getStackTraceHere;
|
||||
import static org.jclouds.concurrent.config.ExecutorServiceModule.shutdownOnClose;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Delayed;
|
||||
|
@ -14,10 +15,8 @@ import java.util.concurrent.TimeUnit;
|
|||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.Constants;
|
||||
import org.jclouds.lifecycle.Closer;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.util.concurrent.ThreadFactoryBuilder;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Provides;
|
||||
|
@ -30,90 +29,82 @@ import com.google.inject.Provides;
|
|||
* @author Ignasi Barrera
|
||||
*
|
||||
* @see ExecutorServiceModule
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class ScheduledExecutorServiceModule extends AbstractModule {
|
||||
|
||||
static class DescribingScheduledExecutorService extends DescribingExecutorService implements ScheduledExecutorService {
|
||||
private static class DescribingScheduledExecutorService extends DescribingExecutorService implements
|
||||
ScheduledExecutorService {
|
||||
|
||||
public DescribingScheduledExecutorService(ScheduledExecutorService delegate) {
|
||||
super(delegate);
|
||||
}
|
||||
private DescribingScheduledExecutorService(ScheduledExecutorService delegate) {
|
||||
super(delegate);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override
|
||||
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate)
|
||||
.schedule(command, delay, unit), command.toString(), getStackTraceHere());
|
||||
}
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Override
|
||||
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).schedule(command, delay, unit),
|
||||
command.toString(), getStackTraceHere());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture<V>(((ScheduledExecutorService) delegate)
|
||||
.schedule(callable, delay, unit), callable.toString(), getStackTraceHere());
|
||||
}
|
||||
@Override
|
||||
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture<V>(((ScheduledExecutorService) delegate).schedule(callable, delay, unit),
|
||||
callable.toString(), getStackTraceHere());
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,
|
||||
long period, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate)
|
||||
.scheduleAtFixedRate(command, initialDelay, period, unit), command.toString(), getStackTraceHere());
|
||||
}
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).scheduleAtFixedRate(command,
|
||||
initialDelay, period, unit), command.toString(), getStackTraceHere());
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
|
||||
long delay, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate)
|
||||
.scheduleWithFixedDelay(command, initialDelay, delay, unit), command.toString(), getStackTraceHere());
|
||||
}
|
||||
}
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
|
||||
return new DescribedScheduledFuture(((ScheduledExecutorService) delegate).scheduleWithFixedDelay(command,
|
||||
initialDelay, delay, unit), command.toString(), getStackTraceHere());
|
||||
}
|
||||
}
|
||||
|
||||
static class DescribedScheduledFuture<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) {
|
||||
super(delegate, description, submissionTrace);
|
||||
}
|
||||
super(delegate, description, submissionTrace);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getDelay(TimeUnit unit) {
|
||||
return ((ScheduledFuture<T>) delegate).getDelay(unit);
|
||||
}
|
||||
@Override
|
||||
public long getDelay(TimeUnit unit) {
|
||||
return ((ScheduledFuture<T>) delegate).getDelay(unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Delayed o) {
|
||||
return ((ScheduledFuture<T>) delegate).compareTo(o);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public int compareTo(Delayed o) {
|
||||
return ((ScheduledFuture<T>) delegate).compareTo(o);
|
||||
}
|
||||
}
|
||||
|
||||
static ScheduledExecutorService addToStringOnSchedule(ScheduledExecutorService executor) {
|
||||
if (executor != null) {
|
||||
return new DescribingScheduledExecutorService(executor);
|
||||
}
|
||||
return executor;
|
||||
}
|
||||
private static ScheduledExecutorService addToStringOnSchedule(ScheduledExecutorService executor) {
|
||||
return (executor != null) ? new DescribingScheduledExecutorService(executor) : executor;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@Named(Constants.PROPERTY_SCHEDULER_THREADS)
|
||||
ScheduledExecutorService provideScheduledExecutor(@Named(Constants.PROPERTY_SCHEDULER_THREADS) final int count,
|
||||
final Closer closer) {
|
||||
return shutdownOnClose(addToStringOnSchedule(newScheduledThreadPoolNamed("scheduler thread %d", count)), closer);
|
||||
}
|
||||
@Provides
|
||||
@Singleton
|
||||
@Named(PROPERTY_SCHEDULER_THREADS)
|
||||
ScheduledExecutorService provideScheduledExecutor(@Named(PROPERTY_SCHEDULER_THREADS) int count, Closer closer) {
|
||||
return shutdownOnClose(addToStringOnSchedule(newScheduledThreadPoolNamed("scheduler thread %d", count)), closer);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static ScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) {
|
||||
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name)
|
||||
private static ScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) {
|
||||
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name)
|
||||
.setThreadFactory(Executors.defaultThreadFactory()).build();
|
||||
return maxCount == 0 ? Executors.newSingleThreadScheduledExecutor(factory)
|
||||
: Executors.newScheduledThreadPool(maxCount, factory);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
|
||||
}
|
||||
return maxCount == 0 ? Executors.newSingleThreadScheduledExecutor(factory) : Executors.newScheduledThreadPool(
|
||||
maxCount, factory);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure() { // NO_UCD
|
||||
}
|
||||
}
|
||||
|
|
|
@ -53,7 +53,6 @@ public class BindPropertiesToExpandedValues extends AbstractModule {
|
|||
bindProperties(resolved);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@Provides
|
||||
@Singleton
|
||||
protected Properties expanded(FilterStringsBoundToInjectorByName filterStringsBoundByName) {
|
||||
|
|
|
@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
|
|||
import static com.google.inject.name.Names.named;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.inject.ConfigurationException;
|
||||
|
@ -33,12 +32,11 @@ import com.google.inject.Key;
|
|||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class ValueOfConfigurationKeyOrNull implements Function<String, String> {
|
||||
protected final Injector injector;
|
||||
private final Injector injector;
|
||||
|
||||
@Inject
|
||||
public ValueOfConfigurationKeyOrNull(Injector injector) {
|
||||
private ValueOfConfigurationKeyOrNull(Injector injector) {
|
||||
this.injector = checkNotNull(injector, "injector");
|
||||
}
|
||||
|
||||
|
@ -51,5 +49,4 @@ public class ValueOfConfigurationKeyOrNull implements Function<String, String> {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -76,15 +76,15 @@ public class Pems {
|
|||
public static final String PUBLIC_X509_MARKER = "-----BEGIN PUBLIC KEY-----";
|
||||
public static final String PUBLIC_PKCS1_MARKER = "-----BEGIN RSA PUBLIC KEY-----";
|
||||
|
||||
public static class PemProcessor<T> implements ByteProcessor<T> {
|
||||
public interface ResultParser<T> {
|
||||
private static class PemProcessor<T> implements ByteProcessor<T> {
|
||||
private interface ResultParser<T> {
|
||||
T parseResult(byte[] bytes) throws IOException;
|
||||
}
|
||||
|
||||
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
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");
|
||||
}
|
||||
|
||||
|
|
|
@ -28,12 +28,12 @@ import javax.inject.Singleton;
|
|||
import com.google.inject.Inject;
|
||||
|
||||
@Singleton
|
||||
public class RsaSshKeyPairGenerator implements SshKeyPairGenerator {
|
||||
protected final Crypto crypto;
|
||||
protected final SecureRandom secureRandom;
|
||||
class RsaSshKeyPairGenerator implements SshKeyPairGenerator {
|
||||
private final Crypto crypto;
|
||||
private final SecureRandom secureRandom;
|
||||
|
||||
@Inject
|
||||
public RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) {
|
||||
private RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) {
|
||||
this.crypto = checkNotNull(crypto, "crypto");
|
||||
this.secureRandom = checkNotNull(secureRandom, "secureRandom");
|
||||
}
|
||||
|
|
|
@ -99,7 +99,7 @@ public class Sha512Crypt {
|
|||
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;
|
||||
|
||||
@Override
|
||||
|
@ -111,7 +111,6 @@ public class Sha512Crypt {
|
|||
public String toString() {
|
||||
return "sha512Crypt()";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final String sha512_salt_prefix = "$6$";
|
||||
|
@ -141,7 +140,7 @@ public class Sha512Crypt {
|
|||
*
|
||||
* @return The Sha512 Unix Crypt hash text for the password
|
||||
*/
|
||||
public static String makeShadowLine(String password, @Nullable String shadowPrefix) {
|
||||
static String makeShadowLine(String password, @Nullable String shadowPrefix) {
|
||||
MessageDigest ctx = sha512();
|
||||
MessageDigest alt_ctx = sha512();
|
||||
|
||||
|
|
|
@ -110,7 +110,7 @@ public class SshKeys {
|
|||
}
|
||||
|
||||
// http://www.ietf.org/rfc/rfc4253.txt
|
||||
static byte[] readLengthFirst(InputStream in) throws IOException {
|
||||
private static byte[] readLengthFirst(InputStream in) throws IOException {
|
||||
int byte1 = in.read();
|
||||
int byte2 = in.read();
|
||||
int byte3 = in.read();
|
||||
|
@ -315,7 +315,7 @@ public class SshKeys {
|
|||
return on(':').join(fixedLength(2).split(base16().lowerCase().encode(hc.asBytes())));
|
||||
}
|
||||
|
||||
public static byte[] keyBlob(BigInteger publicExponent, BigInteger modulus) {
|
||||
private static byte[] keyBlob(BigInteger publicExponent, BigInteger modulus) {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
writeLengthFirst("ssh-rsa".getBytes(), out);
|
||||
|
@ -328,7 +328,7 @@ public class SshKeys {
|
|||
}
|
||||
|
||||
// http://www.ietf.org/rfc/rfc4253.txt
|
||||
static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException {
|
||||
private static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException {
|
||||
out.write((array.length >>> 24) & 0xFF);
|
||||
out.write((array.length >>> 16) & 0xFF);
|
||||
out.write((array.length >>> 8) & 0xFF);
|
||||
|
|
|
@ -34,8 +34,6 @@ import com.google.inject.ImplementedBy;
|
|||
@ImplementedBy(SimpleDateFormatDateService.class)
|
||||
public interface DateService {
|
||||
|
||||
Date fromSeconds(long seconds);
|
||||
|
||||
String cDateFormat(Date date);
|
||||
|
||||
String cDateFormat();
|
||||
|
|
|
@ -27,12 +27,10 @@ import java.util.regex.Pattern;
|
|||
*/
|
||||
public class DateUtils {
|
||||
|
||||
public static final String TZ_REGEX = "([+-][0-9][0-9](:?[0-9][0-9])?|Z)";
|
||||
|
||||
public static final Pattern MILLIS_PATTERN = Pattern.compile("(.*\\.[0-9][0-9][0-9])[0-9]*" + TZ_REGEX + "?");
|
||||
|
||||
private static final String TZ_REGEX = "([+-][0-9][0-9](:?[0-9][0-9])?|Z)";
|
||||
private static final Pattern MILLIS_PATTERN = Pattern.compile("(.*\\.[0-9][0-9][0-9])[0-9]*" + TZ_REGEX + "?");
|
||||
// This regexp will match all TZ forms that are valid is ISO 8601
|
||||
public static final Pattern TZ_PATTERN = Pattern.compile("(.*)" + TZ_REGEX + "$");
|
||||
private static final Pattern TZ_PATTERN = Pattern.compile("(.*)" + TZ_REGEX + "$");
|
||||
|
||||
public static String trimToMillis(String toParse) {
|
||||
Matcher matcher = MILLIS_PATTERN.matcher(toParse);
|
||||
|
@ -44,7 +42,7 @@ public class DateUtils {
|
|||
return toParse;
|
||||
}
|
||||
|
||||
public static final Pattern SECOND_PATTERN = Pattern.compile(".*[0-2][0-9]:00");
|
||||
private static final Pattern SECOND_PATTERN = Pattern.compile(".*[0-2][0-9]:00");
|
||||
|
||||
public static String trimTZ(String toParse) {
|
||||
Matcher matcher = TZ_PATTERN.matcher(toParse);
|
||||
|
|
|
@ -66,11 +66,6 @@ public class SimpleDateFormatDateService implements DateService {
|
|||
cSimpleDateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public final Date fromSeconds(long seconds) {
|
||||
return new Date(seconds * 1000);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String cDateFormat(Date date) {
|
||||
synchronized (cSimpleDateFormat) {
|
||||
|
|
|
@ -18,23 +18,12 @@
|
|||
*/
|
||||
package org.jclouds.domain;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
import org.jclouds.util.Strings2;
|
||||
|
||||
import com.google.common.base.Objects;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
/**
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public class Credentials {
|
||||
public static final Credentials NO_CREDENTIALS = new Credentials(null, null);
|
||||
|
||||
public static class Builder<T extends Credentials> {
|
||||
protected String identity;
|
||||
protected String credential;
|
||||
|
@ -63,21 +52,6 @@ public class Credentials {
|
|||
this.credential = credential;
|
||||
}
|
||||
|
||||
public static Credentials parse(URI uri) {
|
||||
checkNotNull(uri, "uri");
|
||||
List<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() {
|
||||
return new Builder<Credentials>().identity(identity).credential(credential);
|
||||
}
|
||||
|
|
|
@ -87,7 +87,7 @@ public class JsonBall implements Comparable<String>, CharSequence {
|
|||
this.value = quoteStringIfNotNumberOrBoolean(checkNotNull(value, "value"));
|
||||
}
|
||||
|
||||
static String quoteStringIfNotNumberOrBoolean(String in) {
|
||||
private static String quoteStringIfNotNumberOrBoolean(String in) {
|
||||
if (JSON_STRING_PATTERN.matcher(in).find() && !JSON_NUMBER_PATTERN.matcher(in).find()
|
||||
&& !JSON_BOOLEAN_PATTERN.matcher(in).find()) {
|
||||
return "\"" + in + "\"";
|
||||
|
|
|
@ -32,13 +32,13 @@ import com.google.common.collect.ImmutableSet;
|
|||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public class LocationBuilder {
|
||||
protected LocationScope scope;
|
||||
protected String id;
|
||||
protected String description;
|
||||
protected Location parent;
|
||||
protected Set<String> iso3166Codes = ImmutableSet.of();
|
||||
protected Map<String, Object> metadata = ImmutableMap.of();
|
||||
public final class LocationBuilder {
|
||||
private LocationScope scope;
|
||||
private String id;
|
||||
private String description;
|
||||
private Location parent;
|
||||
private Set<String> iso3166Codes = ImmutableSet.of();
|
||||
private Map<String, Object> metadata = ImmutableMap.of();
|
||||
|
||||
public LocationBuilder scope(LocationScope scope) {
|
||||
this.scope = scope;
|
||||
|
|
|
@ -36,7 +36,6 @@ public enum LocationScope {
|
|||
* E.g. the DMZ segment, secure segment.
|
||||
*/
|
||||
NETWORK,
|
||||
RACK,
|
||||
HOST;
|
||||
|
||||
}
|
||||
|
|
|
@ -18,7 +18,9 @@
|
|||
*/
|
||||
package org.jclouds.domain;
|
||||
|
||||
import org.jclouds.crypto.Pems;
|
||||
import static org.jclouds.crypto.Pems.PRIVATE_PKCS1_MARKER;
|
||||
import static org.jclouds.crypto.Pems.PRIVATE_PKCS8_MARKER;
|
||||
|
||||
import org.jclouds.javax.annotation.Nullable;
|
||||
|
||||
import com.google.common.base.Optional;
|
||||
|
@ -28,9 +30,9 @@ import com.google.common.base.Optional;
|
|||
*/
|
||||
public class LoginCredentials extends Credentials {
|
||||
|
||||
public static boolean isPrivateKeyCredential(String credential) {
|
||||
private static boolean isPrivateKeyCredential(String credential) {
|
||||
return credential != null
|
||||
&& (credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credential.startsWith(Pems.PRIVATE_PKCS8_MARKER));
|
||||
&& (credential.startsWith(PRIVATE_PKCS1_MARKER) || credential.startsWith(PRIVATE_PKCS8_MARKER));
|
||||
}
|
||||
|
||||
public static LoginCredentials fromCredentials(Credentials creds) {
|
||||
|
@ -115,15 +117,7 @@ public class LoginCredentials extends Credentials {
|
|||
private final Optional<String> password;
|
||||
private final Optional<String> privateKey;
|
||||
|
||||
public LoginCredentials(String username, 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) {
|
||||
private LoginCredentials(String username, @Nullable Optional<String> password, @Nullable Optional<String> privateKey, boolean authenticateSudo) {
|
||||
super(username, privateKey != null && privateKey.isPresent() && isPrivateKeyCredential(privateKey.get())
|
||||
? privateKey.get()
|
||||
: (password != null && password.isPresent() ? password.get() : null));
|
||||
|
@ -139,26 +133,12 @@ public class LoginCredentials extends Credentials {
|
|||
return identity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a password is available
|
||||
*/
|
||||
public boolean hasPassword() {
|
||||
return password != null && password.isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a password was set
|
||||
*/
|
||||
public boolean hasPasswordOption() {
|
||||
return password != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the password of the login user or null
|
||||
*/
|
||||
@Nullable
|
||||
public String getPassword() {
|
||||
return hasPassword() ? password.get() : null;
|
||||
return (password != null) ? password.orNull() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -169,26 +149,12 @@ public class LoginCredentials extends Credentials {
|
|||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a private key is available
|
||||
*/
|
||||
public boolean hasPrivateKey() {
|
||||
return privateKey != null && privateKey.isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if a password was set
|
||||
*/
|
||||
public boolean hasPrivateKeyOption() {
|
||||
return privateKey != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the private ssh key of the user or null
|
||||
*/
|
||||
@Nullable
|
||||
public String getPrivateKey() {
|
||||
return hasPrivateKey() ? privateKey.get() : null;
|
||||
return (privateKey != null) ? privateKey.orNull() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -233,7 +199,7 @@ public class LoginCredentials extends Credentials {
|
|||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[user=" + getUser() + ", passwordPresent=" + hasPassword() + ", privateKeyPresent="
|
||||
+ hasPrivateKey() + ", shouldAuthenticateSudo=" + authenticateSudo + "]";
|
||||
return "[user=" + getUser() + ", passwordPresent=" + password.isPresent() + ", privateKeyPresent="
|
||||
+ privateKey.isPresent() + ", shouldAuthenticateSudo=" + authenticateSudo + "]";
|
||||
}
|
||||
}
|
||||
|
|
|
@ -63,22 +63,15 @@ public class LocationImpl implements Location {
|
|||
|
||||
@Override
|
||||
public String toString() {
|
||||
return string().toString();
|
||||
}
|
||||
|
||||
|
||||
protected ToStringHelper string() {
|
||||
ToStringHelper helper = Objects.toStringHelper("").omitNullValues().add("scope", scope).add("id", id)
|
||||
.add("description", description);
|
||||
|
||||
.add("description", description);
|
||||
if (parent != null)
|
||||
helper.add("parent", parent.getId());
|
||||
|
||||
if (iso3166Codes.size() > 0)
|
||||
helper.add("iso3166Codes", iso3166Codes);
|
||||
if (metadata.size() > 0)
|
||||
helper.add("metadata", metadata);
|
||||
return helper;
|
||||
return helper.toString();
|
||||
}
|
||||
|
||||
public LocationImpl(LocationScope scope, String id, String description, @Nullable Location parent,
|
||||
|
|
|
@ -87,8 +87,8 @@ public class JCECrypto implements Crypto {
|
|||
return provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider);
|
||||
}
|
||||
|
||||
public static final String HmacSHA256 = "HmacSHA256";
|
||||
public static final String HmacSHA1 = "HmacSHA1";
|
||||
private static final String HmacSHA256 = "HmacSHA256";
|
||||
private static final String HmacSHA1 = "HmacSHA1";
|
||||
|
||||
@Override
|
||||
public Mac hmacSHA1(byte[] key) throws InvalidKeyException {
|
||||
|
|
|
@ -19,12 +19,15 @@
|
|||
|
||||
package org.jclouds.events.config;
|
||||
|
||||
import static com.google.inject.Scopes.SINGLETON;
|
||||
import static org.jclouds.Constants.PROPERTY_USER_THREADS;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.Constants;
|
||||
import org.jclouds.concurrent.config.ExecutorServiceModule;
|
||||
import org.jclouds.events.config.annotations.AsyncBus;
|
||||
import org.jclouds.events.handlers.DeadEventLoggingHandler;
|
||||
|
||||
|
@ -32,13 +35,12 @@ import com.google.common.eventbus.AsyncEventBus;
|
|||
import com.google.common.eventbus.EventBus;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Provides;
|
||||
import com.google.inject.Scopes;
|
||||
|
||||
/**
|
||||
* Configures the {@link EventBus} to be used in the platform.
|
||||
* <p>
|
||||
* This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for
|
||||
* asynchronous operations.
|
||||
* This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for asynchronous
|
||||
* operations.
|
||||
*
|
||||
* @author Ignasi Barrera
|
||||
*
|
||||
|
@ -49,37 +51,34 @@ import com.google.inject.Scopes;
|
|||
*/
|
||||
@ConfiguresEventBus
|
||||
public class EventBusModule extends AbstractModule {
|
||||
/**
|
||||
* Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch
|
||||
* events to subscribers.
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
AsyncEventBus provideAsyncEventBus(
|
||||
@Named(Constants.PROPERTY_USER_THREADS) final ExecutorService executor,
|
||||
final DeadEventLoggingHandler deadEventsHandler) {
|
||||
AsyncEventBus asyncBus = new AsyncEventBus("jclouds-async-event-bus", executor);
|
||||
asyncBus.register(deadEventsHandler);
|
||||
return asyncBus;
|
||||
}
|
||||
/**
|
||||
* Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch events to subscribers.
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
AsyncEventBus provideAsyncEventBus(@Named(PROPERTY_USER_THREADS) ExecutorService executor,
|
||||
DeadEventLoggingHandler deadEventsHandler) {// NO_UCD
|
||||
AsyncEventBus asyncBus = new AsyncEventBus("jclouds-async-event-bus", executor);
|
||||
asyncBus.register(deadEventsHandler);
|
||||
return asyncBus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides asynchronous {@link EventBus}.
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
EventBus provideSyncEventBus(final DeadEventLoggingHandler deadEventsHandler) {
|
||||
EventBus syncBus = new EventBus("jclouds-sync-event-bus");
|
||||
syncBus.register(deadEventsHandler);
|
||||
return syncBus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the {@link EventBus} to be singleton and enables the {@link AsyncBus} annotation.
|
||||
*/
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(EventBus.class).annotatedWith(AsyncBus.class).to(AsyncEventBus.class).in(Scopes.SINGLETON);
|
||||
}
|
||||
/**
|
||||
* Provides asynchronous {@link EventBus}.
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
EventBus provideSyncEventBus(DeadEventLoggingHandler deadEventsHandler) { // NO_UCD
|
||||
EventBus syncBus = new EventBus("jclouds-sync-event-bus");
|
||||
syncBus.register(deadEventsHandler);
|
||||
return syncBus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the {@link EventBus} to be singleton and enables the {@link AsyncBus} annotation.
|
||||
*/
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(EventBus.class).annotatedWith(AsyncBus.class).to(AsyncEventBus.class).in(SINGLETON);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -35,18 +35,12 @@ import com.google.common.eventbus.Subscribe;
|
|||
* @author Ignasi Barrera
|
||||
*/
|
||||
@Singleton
|
||||
public class DeadEventLoggingHandler
|
||||
{
|
||||
@Resource
|
||||
private Logger logger = Logger.NULL;
|
||||
public class DeadEventLoggingHandler {
|
||||
@Resource
|
||||
private Logger logger = Logger.NULL;
|
||||
|
||||
/**
|
||||
* Due to <a href="http://code.google.com/p/guava-libraries/issues/detail?id=783">Guava Issue
|
||||
* 786</a> {@link #handleDeadEvent(DeadEvent)} is marked <code>final</code>to avoid having
|
||||
* duplicate events.
|
||||
*/
|
||||
@Subscribe
|
||||
public final void handleDeadEvent(DeadEvent deadEvent) {
|
||||
logger.trace("detected dead event %s", deadEvent.getEvent());
|
||||
}
|
||||
@Subscribe
|
||||
public void handleDeadEvent(DeadEvent deadEvent) { // NO_UCD
|
||||
logger.trace("detected dead event %s", deadEvent.getEvent());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -36,19 +36,18 @@ import com.google.common.util.concurrent.ListenableFuture;
|
|||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class MapHttp4xxCodesToExceptions implements FutureFallback<Object> {
|
||||
public final class MapHttp4xxCodesToExceptions implements FutureFallback<Object> {
|
||||
|
||||
private final PropagateIfRetryAfter propagateIfRetryAfter;
|
||||
|
||||
@Inject
|
||||
protected MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) {
|
||||
MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) { // NO_UCD
|
||||
this.propagateIfRetryAfter = checkNotNull(propagateIfRetryAfter, "propagateIfRetryAfter");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Object> create(Throwable t) {
|
||||
// if we pass here, we aren't a retry-after exception
|
||||
propagateIfRetryAfter.create(t);
|
||||
public ListenableFuture<Object> create(Throwable t) { // NO_UCD
|
||||
propagateIfRetryAfter.create(t); // if we pass here, we aren't a retry-after exception
|
||||
if (t instanceof HttpResponseException) {
|
||||
HttpResponseException responseException = HttpResponseException.class.cast(t);
|
||||
if (responseException.getResponse() != null)
|
||||
|
|
|
@ -139,11 +139,6 @@ public final class Uris {
|
|||
return this;
|
||||
}
|
||||
|
||||
public UriBuilder clearPath() {
|
||||
path = null;
|
||||
return this;
|
||||
}
|
||||
|
||||
public UriBuilder path(@Nullable String path) {
|
||||
path = emptyToNull(path);
|
||||
if (path == null)
|
||||
|
@ -163,10 +158,6 @@ public final class Uris {
|
|||
return this;
|
||||
}
|
||||
|
||||
public UriBuilder query(Map<String, ?> parameters) {
|
||||
return query(forMap(parameters));
|
||||
}
|
||||
|
||||
public UriBuilder query(@Nullable String queryLine) {
|
||||
if (query == null)
|
||||
return clearQuery();
|
||||
|
@ -194,10 +185,6 @@ public final class Uris {
|
|||
return addQuery(name, Arrays.asList(checkNotNull(values, "values of %s", name)));
|
||||
}
|
||||
|
||||
public UriBuilder addQuery(Map<String, ?> parameters) {
|
||||
return addQuery(forMap(parameters));
|
||||
}
|
||||
|
||||
public UriBuilder addQuery(Multimap<String, ?> parameters) {
|
||||
query.putAll(checkNotNull(parameters, "parameters"));
|
||||
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();
|
||||
if (scheme != null)
|
||||
b.append(scheme).append("://");
|
||||
|
|
|
@ -205,10 +205,6 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
|
|||
}
|
||||
|
||||
public abstract static class HandlerForGeneratedRequestWithResult<T> extends HandlerWithResult<T> {
|
||||
@Override
|
||||
protected GeneratedHttpRequest getRequest() {
|
||||
return (GeneratedHttpRequest) super.getRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerForGeneratedRequestWithResult<T> setContext(HttpRequest request) {
|
||||
|
@ -216,6 +212,11 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
|
|||
super.setContext(request);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected GeneratedHttpRequest<?> getRequest() {
|
||||
return (GeneratedHttpRequest<?>) super.getRequest();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -53,11 +53,6 @@ public abstract class BaseView extends ForwardingObject implements View {
|
|||
return (C) backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <C extends Context> C unwrap(Class<C> clazz) {
|
||||
return unwrap (TypeToken.of(checkNotNull(clazz, "clazz")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeToken<? extends Context> getBackendType() {
|
||||
return backendType;
|
||||
|
|
|
@ -123,7 +123,6 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
|
|||
this.delegateFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, checkNotNull(serializationFieldNamingPolicy, "fieldNamingPolicy"), checkNotNull(excluder, "excluder"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
|
||||
Class<? super T> raw = type.getRawType();
|
||||
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 Constructor<? super T> parameterizedCtor;
|
||||
private final Map<String, ParameterReader> parameterReaders;
|
||||
private final Map<String, ParameterReader<?>> parameterReaders;
|
||||
private final 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.parameterizedCtor = parameterizedCtor;
|
||||
this.parameterReaders = parameterReaders;
|
||||
|
@ -174,7 +173,7 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
|
|||
while (in.hasNext()) {
|
||||
empty = false;
|
||||
String name = in.nextName();
|
||||
ParameterReader parameter = parameterReaders.get(name);
|
||||
ParameterReader<?> parameter = parameterReaders.get(name);
|
||||
if (parameter == null) {
|
||||
in.skipValue();
|
||||
} else {
|
||||
|
@ -246,20 +245,19 @@ public final class DeserializationConstructorAndReflectiveTypeAdapterFactory imp
|
|||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, ParameterReader> getParameterReaders(Gson context, TypeToken<?> declaring, Constructor<?> constructor) {
|
||||
Map<String, ParameterReader> result = Maps.newLinkedHashMap();
|
||||
private Map<String, ParameterReader<?>> getParameterReaders(Gson context, TypeToken<?> declaring, Constructor<?> constructor) {
|
||||
Map<String, ParameterReader<?>> result = Maps.newLinkedHashMap();
|
||||
|
||||
for (int index = 0; index < constructor.getGenericParameterTypes().length; index++) {
|
||||
Type parameterType = getTypeOfConstructorParameter(declaring, constructor, index);
|
||||
TypeAdapter<?> adapter = context.getAdapter(TypeToken.get(parameterType));
|
||||
String parameterName = constructorFieldNamingPolicy.translateName(constructor, index);
|
||||
checkArgument(parameterName != null, constructor + " parameter " + 0 + " failed to be named by " + constructorFieldNamingPolicy);
|
||||
ParameterReader parameterReader = new ParameterReader(parameterName, index, adapter);
|
||||
ParameterReader previous = result.put(parameterReader.name, parameterReader);
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
ParameterReader<?> parameterReader = new ParameterReader(parameterName, index, adapter);
|
||||
ParameterReader<?> previous = result.put(parameterReader.name, parameterReader);
|
||||
checkArgument(previous == null, constructor + " declares multiple JSON parameters named " + parameterReader.name);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ public class BindMapToStringPayload implements MapBinder {
|
|||
@Override
|
||||
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
|
||||
checkNotNull(postParams, "postParams");
|
||||
GeneratedHttpRequest r = GeneratedHttpRequest.class.cast(checkNotNull(request, "request"));
|
||||
GeneratedHttpRequest<?> r = GeneratedHttpRequest.class.cast(checkNotNull(request, "request"));
|
||||
Invokable<?, ?> invoked = r.getInvocation().getInvokable();
|
||||
checkArgument(invoked.isAnnotationPresent(Payload.class),
|
||||
"method %s must have @Payload annotation to use this binder", invoked);
|
||||
|
|
|
@ -18,6 +18,8 @@
|
|||
*/
|
||||
package org.jclouds;
|
||||
|
||||
import static java.util.concurrent.Executors.defaultThreadFactory;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletionService;
|
||||
|
@ -44,7 +46,7 @@ public abstract class PerformanceTest {
|
|||
|
||||
@BeforeTest
|
||||
public void setupExecutorService() {
|
||||
exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000);
|
||||
exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000, defaultThreadFactory());
|
||||
}
|
||||
|
||||
@AfterTest
|
||||
|
|
|
@ -36,32 +36,30 @@ public class ValueOfConfigurationKeyOrNullTest {
|
|||
|
||||
@Test
|
||||
public void testNotThere() {
|
||||
assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector()).apply("foo"), null);
|
||||
assertEquals(Guice.createInjector().getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testThere() {
|
||||
assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() {
|
||||
assertEquals(Guice.createInjector(new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to("bar");
|
||||
}
|
||||
|
||||
})).apply("foo"), "bar");
|
||||
|
||||
}).getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), "bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyIsThere() {
|
||||
assertEquals(new ValueOfConfigurationKeyOrNull(Guice.createInjector(new AbstractModule() {
|
||||
assertEquals(Guice.createInjector(new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindConstant().annotatedWith(Names.named("foo")).to("");
|
||||
}
|
||||
|
||||
})).apply("foo"), "");
|
||||
|
||||
}).getInstance(ValueOfConfigurationKeyOrNull.class).apply("foo"), "");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -42,6 +42,8 @@ import org.testng.annotations.BeforeClass;
|
|||
import org.testng.annotations.Test;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Guice;
|
||||
|
||||
/**
|
||||
* @author Adrian Cole
|
||||
|
@ -66,9 +68,9 @@ public class RsaSshKeyPairGeneratorTest {
|
|||
|
||||
@Test
|
||||
public void testApply() {
|
||||
Crypto crypto = createMock(Crypto.class);
|
||||
final Crypto crypto = createMock(Crypto.class);
|
||||
KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class);
|
||||
SecureRandom secureRandom = createMock(SecureRandom.class);
|
||||
final SecureRandom secureRandom = createMock(SecureRandom.class);
|
||||
|
||||
expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator);
|
||||
rsaKeyPairGenerator.initialize(2048, secureRandom);
|
||||
|
@ -76,7 +78,12 @@ public class RsaSshKeyPairGeneratorTest {
|
|||
|
||||
replay(crypto, rsaKeyPairGenerator, secureRandom);
|
||||
|
||||
RsaSshKeyPairGenerator supplier = new RsaSshKeyPairGenerator(crypto, secureRandom);
|
||||
RsaSshKeyPairGenerator supplier = Guice.createInjector(new AbstractModule(){
|
||||
protected void configure() {
|
||||
bind(Crypto.class).toInstance(crypto);
|
||||
bind(SecureRandom.class).toInstance(secureRandom);
|
||||
}
|
||||
}).getInstance(RsaSshKeyPairGenerator.class);
|
||||
|
||||
assertEquals(supplier.get(),
|
||||
ImmutableMap.of("public", openSshKey, "private", PRIVATE_KEY.replaceAll("\n", lineSeparator)));
|
||||
|
|
|
@ -174,13 +174,6 @@ public class DateServiceTest extends PerformanceTest {
|
|||
dateService.iso8601DateFormat();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFromSeconds() {
|
||||
long seconds = 1254008225;
|
||||
Date date = dateService.fromSeconds(seconds);
|
||||
assertEquals(dateService.iso8601SecondsDateFormat(date), "2009-09-26T23:37:05Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUTCIsGMT() {
|
||||
assertEquals(dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime(), dateService.iso8601SecondsDateParse("2012-11-26T17:32:31UTC+0000").getTime());
|
||||
|
|
|
@ -20,8 +20,6 @@ package org.jclouds.domain;
|
|||
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
/**
|
||||
|
@ -30,69 +28,9 @@ import org.testng.annotations.Test;
|
|||
@Test(groups = "unit")
|
||||
public class CredentialsTest {
|
||||
|
||||
public void testAzure() {
|
||||
Credentials creds = Credentials
|
||||
.parse(URI.create("compute://identity:Base64==@azureblob/container-hyphen/prefix"));
|
||||
assertEquals(creds.identity, "identity");
|
||||
assertEquals(creds.credential, "Base64==");
|
||||
}
|
||||
|
||||
public void testAtmos() {
|
||||
Credentials creds = Credentials.parse(URI
|
||||
.create("compute://domain%2Fuser:Base64%3D%3D@azureblob/container-hyphen/prefix"));
|
||||
assertEquals(creds.identity, "domain/user");
|
||||
assertEquals(creds.credential, "Base64==");
|
||||
}
|
||||
|
||||
public void testDollar() {
|
||||
Credentials creds = Credentials.parse(URI.create("compute://user%40domain:pa%24sword@hostingdotcom"));
|
||||
assertEquals(creds.identity, "user@domain");
|
||||
assertEquals(creds.credential, "pa$sword");
|
||||
}
|
||||
|
||||
public void testTerremark() {
|
||||
Credentials creds = Credentials.parse(URI.create("compute://user%40domain:password@terremark"));
|
||||
assertEquals(creds.identity, "user@domain");
|
||||
assertEquals(creds.credential, "password");
|
||||
}
|
||||
|
||||
public void testTerremark2() {
|
||||
Credentials creds = Credentials.parse(URI.create("compute://user%40domain:passw%40rd@terremark"));
|
||||
assertEquals(creds.identity, "user@domain");
|
||||
assertEquals(creds.credential, "passw@rd");
|
||||
}
|
||||
|
||||
public void testTerremark3() {
|
||||
Credentials creds = Credentials.parse(URI.create("compute://user%40domain:AbC%21%40943%21@terremark"));
|
||||
assertEquals(creds.identity, "user@domain");
|
||||
assertEquals(creds.credential, "AbC!@943!");
|
||||
}
|
||||
|
||||
public void testCloudFiles() {
|
||||
Credentials creds = Credentials.parse(URI.create("compute://identity:h3c@cloudfiles/container-hyphen/prefix"));
|
||||
assertEquals(creds.identity, "identity");
|
||||
assertEquals(creds.credential, "h3c");
|
||||
|
||||
}
|
||||
|
||||
public void testS3() {
|
||||
|
||||
Credentials creds = Credentials.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/prefix"));
|
||||
assertEquals(creds.identity, "0AB");
|
||||
assertEquals(creds.credential, "aA+/0");
|
||||
}
|
||||
|
||||
public void testS3Space() {
|
||||
|
||||
Credentials creds = Credentials.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/pre%20fix"));
|
||||
assertEquals(creds.identity, "0AB");
|
||||
assertEquals(creds.credential, "aA+/0");
|
||||
}
|
||||
|
||||
public void testSubClassEquals() {
|
||||
Credentials creds = new Credentials("user", "pass");
|
||||
assertEquals(creds, new Credentials("user", "pass") {
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -23,7 +23,6 @@ import static org.jclouds.util.Strings2.urlEncode;
|
|||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Test;
|
||||
|
@ -74,18 +73,17 @@ public class UrisTest {
|
|||
|
||||
@Test(dataProvider = "strings")
|
||||
public void testQuery(String val) {
|
||||
Map<String, String> query = ImmutableMap.of("moo", val);
|
||||
assertEquals(uriBuilder("https://foo.com:8080").query(query).toString(), "https://foo.com:8080?moo=" + val);
|
||||
assertEquals(uriBuilder("https://foo.com:8080").query(query).build().toString(), "https://foo.com:8080?moo="
|
||||
assertEquals(uriBuilder("https://foo.com:8080").addQuery("moo", val).toString(), "https://foo.com:8080?moo=" + val);
|
||||
assertEquals(uriBuilder("https://foo.com:8080").addQuery("moo", val).build().toString(), "https://foo.com:8080?moo="
|
||||
+ urlEncode(val, '/', ','));
|
||||
assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").query(query).toString(),
|
||||
"https://api.github.com/repos/user?moo=" + val);
|
||||
assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").query(query).build().toString(),
|
||||
"https://api.github.com/repos/user?moo=" + urlEncode(val, '/', ','));
|
||||
assertEquals(uriBuilder("https://api.github.com/repos/{user}").query(query).toString(),
|
||||
assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").addQuery("moo", val).toString(),
|
||||
"https://api.github.com/repos/user?foo=bar&kung=fu&moo=" + val);
|
||||
assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").addQuery("moo", val).build().toString(),
|
||||
"https://api.github.com/repos/user?foo=bar&kung=fu&moo=" + urlEncode(val, '/', ','));
|
||||
assertEquals(uriBuilder("https://api.github.com/repos/{user}").addQuery("moo", val).toString(),
|
||||
"https://api.github.com/repos/{user}?moo=" + val);
|
||||
assertEquals(
|
||||
uriBuilder("https://api.github.com/repos/{user}").query(query).build(templateParams).toASCIIString(),
|
||||
uriBuilder("https://api.github.com/repos/{user}").addQuery("moo", val).build(templateParams).toASCIIString(),
|
||||
"https://api.github.com/repos/bob?moo=" + urlEncode(val, '/', ','));
|
||||
}
|
||||
|
||||
|
|
|
@ -70,7 +70,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("Ubuntu Server 10.04 (64-bit)")
|
||||
.name("Ubuntu Server 10.04.3")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-4e5b842f")
|
||||
.providerId("qmi-4e5b842f")
|
||||
.location(defaultLocation)
|
||||
|
@ -89,7 +89,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("Ubuntu Server 11.10 (64-bit)")
|
||||
.name("Ubuntu Server 11.10")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-9ac92558")
|
||||
.providerId("qmi-9ac92558")
|
||||
.location(defaultLocation)
|
||||
|
@ -108,7 +108,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("CentOS 5.5 Server 64-bit")
|
||||
.name("CentOS 5.5 Server")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-33a467aa")
|
||||
.providerId("qmi-33a467aa")
|
||||
.location(defaultLocation)
|
||||
|
@ -127,7 +127,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("Debian 6.0 (64-bit)")
|
||||
.name("Debian 6.0")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-f2a9d2ba")
|
||||
.providerId("qmi-f2a9d2ba")
|
||||
.location(defaultLocation)
|
||||
|
@ -146,7 +146,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("CentOS 6.0 (64-bit)")
|
||||
.name("CentOS 6.0")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-96f82145")
|
||||
.providerId("qmi-96f82145")
|
||||
.location(defaultLocation)
|
||||
|
@ -165,7 +165,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("CentOS 6.0 GUI (64-bit)")
|
||||
.name("CentOS 6.0 GUI")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-42e877f6")
|
||||
.providerId("qmi-42e877f6")
|
||||
.location(defaultLocation)
|
||||
|
@ -184,7 +184,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("Ubuntu Server 11.04 (64-bit)")
|
||||
.name("Ubuntu Server 11.04")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-eed8cea7")
|
||||
.providerId("qmi-eed8cea7")
|
||||
.location(defaultLocation)
|
||||
|
@ -204,7 +204,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("Fedora 16 Server")
|
||||
.name("Fedora 16 Server")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-fa4bdae0")
|
||||
.providerId("qmi-fa4bdae0")
|
||||
.location(defaultLocation)
|
||||
|
@ -223,7 +223,7 @@ public class GreenQloudComputeReviseParsedImageTest {
|
|||
.arch("paravirtual").build())
|
||||
.description("CentOS 5.6 Server GUI 64-bit")
|
||||
.name("CentOS 5.6 GUI")
|
||||
.defaultCredentials(new LoginCredentials("root", false))
|
||||
.defaultCredentials(LoginCredentials.builder().user("root").build())
|
||||
.id("us-east-1/qmi-93271d32")
|
||||
.providerId("qmi-93271d32")
|
||||
.location(defaultLocation)
|
||||
|
|
|
@ -129,9 +129,11 @@ public class JsonNodeMetadataStore implements NodeMetadataStore {
|
|||
.tags(jsonMetadata.tags)
|
||||
.group(jsonMetadata.group)
|
||||
.userMetadata(jsonMetadata.userMetadata)
|
||||
.credentials(
|
||||
new LoginCredentials(jsonMetadata.user, jsonMetadata.password, jsonMetadata.privateKey,
|
||||
jsonMetadata.authenticateSudo)).build();
|
||||
.credentials(LoginCredentials.builder()
|
||||
.user(jsonMetadata.user)
|
||||
.privateKey(jsonMetadata.privateKey)
|
||||
.password(jsonMetadata.password)
|
||||
.authenticateSudo(jsonMetadata.authenticateSudo).build()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -146,7 +146,10 @@ public class YamlImage {
|
|||
|
||||
return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description)
|
||||
.operatingSystem(operatingSystem).status(Image.Status.AVAILABLE)
|
||||
.defaultCredentials(new LoginCredentials(arg0.username, arg0.credential, null, true))
|
||||
.defaultCredentials(LoginCredentials.builder()
|
||||
.user(arg0.username)
|
||||
.password(arg0.credential)
|
||||
.authenticateSudo(true).build())
|
||||
.build();
|
||||
}
|
||||
};
|
||||
|
|
|
@ -120,9 +120,10 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
|||
|
||||
String guestOsUser = vm.getExtraData(GUEST_OS_USER);
|
||||
String guestOsPassword = vm.getExtraData(GUEST_OS_PASSWORD);
|
||||
LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true);
|
||||
nodeMetadataBuilder.credentials(loginCredentials);
|
||||
|
||||
nodeMetadataBuilder.credentials(LoginCredentials.builder()
|
||||
.user(guestOsUser)
|
||||
.password(guestOsPassword)
|
||||
.authenticateSudo(true).build());
|
||||
return nodeMetadataBuilder.build();
|
||||
}
|
||||
|
||||
|
|
|
@ -241,7 +241,10 @@ public class MastersLoadingCache extends AbstractLoadingCache<Image, Master> {
|
|||
.iso(IsoSpec.builder().sourcePath(localIsoUrl)
|
||||
.installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())).build())
|
||||
.network(networkSpec)
|
||||
.credentials(new LoginCredentials(currentImage.username, currentImage.credential, null, true)).build();
|
||||
.credentials(LoginCredentials.builder()
|
||||
.user(currentImage.username)
|
||||
.password(currentImage.credential)
|
||||
.authenticateSudo(true).build()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -181,9 +181,11 @@ public class NodeCreator implements Function<NodeSpec, NodeAndInitialCredentials
|
|||
nodeMetadataBuilder.publicAddresses(ImmutableSet.of(networkUtils.getIpAddressFromNicSlot(clone.getName(), slot)));
|
||||
String guestOsUser = clone.getExtraData(GUEST_OS_USER);
|
||||
String guestOsPassword = clone.getExtraData(GUEST_OS_PASSWORD);
|
||||
LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true);
|
||||
nodeMetadataBuilder.credentials(loginCredentials);
|
||||
return nodeMetadataBuilder.build();
|
||||
nodeMetadataBuilder.credentials(LoginCredentials.builder()
|
||||
.user(guestOsUser)
|
||||
.password(guestOsPassword)
|
||||
.authenticateSudo(true).build());
|
||||
return nodeMetadataBuilder.build();
|
||||
}
|
||||
|
||||
private long findSlotForNetworkAttachment(IMachine clone, NetworkAttachmentType networkAttachmentType) {
|
||||
|
|
|
@ -67,7 +67,7 @@ public class AWSEC2ImageParserTest {
|
|||
.description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml")
|
||||
.is64Bit(false).build())
|
||||
.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")
|
||||
.userMetadata(ImmutableMap.of(
|
||||
"owner", "099720109477",
|
||||
|
@ -86,7 +86,7 @@ public class AWSEC2ImageParserTest {
|
|||
new OperatingSystem.Builder().family(OsFamily.UBUNTU).arch("paravirtual").version("8.04")
|
||||
.description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml").is64Bit(false)
|
||||
.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")
|
||||
.userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store"))
|
||||
.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")
|
||||
.is64Bit(false).build())
|
||||
.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")
|
||||
.userMetadata(ImmutableMap.of(
|
||||
"owner", "099720109477",
|
||||
|
@ -125,7 +125,7 @@ public class AWSEC2ImageParserTest {
|
|||
.description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml")
|
||||
.is64Bit(false).build())
|
||||
.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")
|
||||
.userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store"))
|
||||
.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")
|
||||
.description("amazon/EC2 CentOS 5.4 HVM AMI").is64Bit(true).build())
|
||||
.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)
|
||||
.userMetadata(ImmutableMap.of(
|
||||
"owner", "206029621532",
|
||||
|
@ -167,7 +167,7 @@ public class AWSEC2ImageParserTest {
|
|||
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)
|
||||
.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")
|
||||
.userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store"))
|
||||
.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")
|
||||
.version("0.9.7-beta").description("137112412989/amzn-ami-0.9.7-beta.i386-ebs")
|
||||
.is64Bit(false).build()).description("Amazon")
|
||||
.defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-82e4b5c7")
|
||||
.defaultCredentials(LoginCredentials.builder().user("ec2-user").build()).id("us-east-1/ami-82e4b5c7")
|
||||
.providerId("ami-82e4b5c7").location(defaultLocation).version("0.9.7-beta")
|
||||
.userMetadata(ImmutableMap.of(
|
||||
"owner", "137112412989",
|
||||
|
@ -213,7 +213,7 @@ public class AWSEC2ImageParserTest {
|
|||
.version("0.9.7-beta")
|
||||
.description("amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml").is64Bit(true)
|
||||
.build()).description("Amazon Linux AMI x86_64 S3")
|
||||
.defaultCredentials(new LoginCredentials("ec2-user", false)).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")
|
||||
.userMetadata(ImmutableMap.of(
|
||||
"owner", "137112412989",
|
||||
|
|
Loading…
Reference in New Issue