major overhaul to ibm smartcloud

This commit is contained in:
Adrian Cole 2011-05-14 00:44:54 -07:00
parent 20e3389a2d
commit 5b8ee87a4d
140 changed files with 3558 additions and 4056 deletions

View File

@ -42,7 +42,7 @@ public class OsFamilyVersion64Bit {
@Override @Override
public String toString() { public String toString() {
return "OsFamilyVersion64Bit [family=" + family + ", version=" + version + ", is64Bit=" + is64Bit + "]"; return "[family=" + family + ", version=" + version + ", is64Bit=" + is64Bit + "]";
} }
@Override @Override

View File

@ -557,10 +557,10 @@ public class TemplateBuilderImpl implements TemplateBuilder {
} }
protected Hardware resolveSize(Ordering<Hardware> hardwareOrdering, final Iterable<? extends Image> images) { protected Hardware resolveSize(Ordering<Hardware> hardwareOrdering, final Iterable<? extends Image> images) {
Set<? extends Hardware> hardwaresl = hardwares.get(); Set<? extends Hardware> hardwarel = hardwares.get();
Hardware hardware; Hardware hardware;
try { try {
Iterable<? extends Hardware> hardwaresThatAreCompatibleWithOurImages = filter(hardwaresl, Iterable<? extends Hardware> hardwaresThatAreCompatibleWithOurImages = filter(hardwarel,
new Predicate<Hardware>() { new Predicate<Hardware>() {
@Override @Override
public boolean apply(final Hardware hardware) { public boolean apply(final Hardware hardware) {
@ -582,7 +582,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
}); });
hardware = hardwareOrdering.max(filter(hardwaresThatAreCompatibleWithOurImages, hardwarePredicate)); hardware = hardwareOrdering.max(filter(hardwaresThatAreCompatibleWithOurImages, hardwarePredicate));
} catch (NoSuchElementException exception) { } catch (NoSuchElementException exception) {
throw new NoSuchElementException("hardwares don't support any images: " + toString() + "\n" + hardwaresl throw new NoSuchElementException("hardware don't support any images: " + toString() + "\n" + hardwarel
+ "\n" + images); + "\n" + images);
} }
logger.debug("<< matched hardware(%s)", hardware); logger.debug("<< matched hardware(%s)", hardware);

View File

@ -57,7 +57,7 @@ public interface ComputeServiceConstants {
public static class ReferenceData { public static class ReferenceData {
@Inject(optional = true) @Inject(optional = true)
@Named(PROPERTY_OS_VERSION_MAP_JSON) @Named(PROPERTY_OS_VERSION_MAP_JSON)
public String osVersionMapJson = "{\"centos\":{\"\":\"\",\"5\":\"5.0\",\"5.2\":\"5.2\",\"5.3\":\"5.3\",\"5.4\":\"5.4\",\"5.5\":\"5.5\"},\"rhel\":{\"\":\"\",\"5\":\"5.0\",\"5.2\":\"5.2\",\"5.3\":\"5.3\",\"5.4\":\"5.4\",\"5.5\":\"5.5\"},\"solaris\":{\"\":\"\",\"10\":\"10\"},\"ubuntu\":{\"\":\"\",\"hardy\":\"8.04\",\"karmic\":\"9.10\",\"lucid\":\"10.04\",\"maverick\":\"10.10\",\"natty\":\"11.04\"},\"windows\":{\"\":\"\",\"2003\":\"2003\",\"2003 Standard\":\"2003\",\"2003 R2\":\"2003 R2\",\"2008\":\"2008\",\"2008 Web\":\"2008\",\"2008 Server\":\"2008\",\"Server 2008\":\"2008\",\"2008 R2\":\"2008 R2\",\"Server 2008 R2\":\"2008 R2\",\"2008 Server R2\":\"2008 R2\",\"2008 SP2\":\"2008 SP2\",\"Server 2008 SP2\":\"2008 SP2\"}}"; public String osVersionMapJson = "{\"suse\":{\"\":\"\",\"11\":\"11\",\"11 SP1\":\"11 SP1\"},\"centos\":{\"\":\"\",\"5\":\"5.0\",\"5.2\":\"5.2\",\"5.3\":\"5.3\",\"5.4\":\"5.4\",\"5.5\":\"5.5\"},\"rhel\":{\"\":\"\",\"5\":\"5.0\",\"5.2\":\"5.2\",\"5.3\":\"5.3\",\"5.4\":\"5.4\",\"5.5\":\"5.5\"},\"solaris\":{\"\":\"\",\"10\":\"10\"},\"ubuntu\":{\"\":\"\",\"hardy\":\"8.04\",\"karmic\":\"9.10\",\"lucid\":\"10.04\",\"maverick\":\"10.10\",\"natty\":\"11.04\"},\"windows\":{\"\":\"\",\"2003\":\"2003\",\"2003 Standard\":\"2003\",\"2003 R2\":\"2003 R2\",\"2008\":\"2008\",\"2008 Web\":\"2008\",\"2008 Server\":\"2008\",\"Server 2008\":\"2008\",\"2008 R1\":\"2008 R1\",\"2008 R2\":\"2008 R2\",\"Server 2008 R2\":\"2008 R2\",\"2008 Server R2\":\"2008 R2\",\"2008 SP2\":\"2008 SP2\",\"Server 2008 SP2\":\"2008 SP2\"}}";
} }
@Singleton @Singleton

View File

@ -105,6 +105,8 @@ public class ComputeServiceUtils {
* @return null if group cannot be parsed * @return null if group cannot be parsed
*/ */
public static String parseGroupFromName(String from) { public static String parseGroupFromName(String from) {
if (from == null)
return null;
Matcher matcher = DELIMETED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX.matcher(from); Matcher matcher = DELIMETED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX.matcher(from);
return matcher.find() ? matcher.group(1) : null; return matcher.find() ? matcher.group(1) : null;
} }

View File

@ -160,8 +160,8 @@ public abstract class BaseComputeServiceLiveTest {
if (context != null) if (context != null)
context.close(); context.close();
Properties props = setupProperties(); Properties props = setupProperties();
context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of(
ImmutableSet.of(new Log4JLoggingModule(), getSshModule()), props); new Log4JLoggingModule(), getSshModule()), props);
client = context.getComputeService(); client = context.getComputeService();
} }
@ -182,7 +182,7 @@ public abstract class BaseComputeServiceLiveTest {
ComputeServiceContext context = null; ComputeServiceContext context = null;
try { try {
context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA",
ImmutableSet.<Module> of(new Log4JLoggingModule())); ImmutableSet.<Module> of(new Log4JLoggingModule()));
context.getComputeService().listNodes(); context.getComputeService().listNodes();
} catch (AuthorizationException e) { } catch (AuthorizationException e) {
throw e; throw e;
@ -207,7 +207,7 @@ public abstract class BaseComputeServiceLiveTest {
@Test(enabled = true, expectedExceptions = NoSuchElementException.class) @Test(enabled = true, expectedExceptions = NoSuchElementException.class)
public void testCorrectExceptionRunningNodesNotFound() throws Exception { public void testCorrectExceptionRunningNodesNotFound() throws Exception {
client.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() client.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder()
.family(OsFamily.UBUNTU).description("ffoo").build())); .family(OsFamily.UBUNTU).description("ffoo").build()));
} }
// since surefire and eclipse don't otherwise guarantee the order, we are // since surefire and eclipse don't otherwise guarantee the order, we are
@ -231,17 +231,17 @@ public abstract class BaseComputeServiceLiveTest {
OperatingSystem os = get(nodes, 0).getOperatingSystem(); OperatingSystem os = get(nodes, 0).getOperatingSystem();
try { try {
Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(group, os, new Credentials( Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(group, os, new Credentials(
good.identity, "romeo")); good.identity, "romeo"));
assert false : "shouldn't pass with a bad password\n" + responses; assert false : "shouldn't pass with a bad password\n" + responses;
} catch (RunScriptOnNodesException e) { } catch (RunScriptOnNodesException e) {
assert getRootCause(e).getMessage().contains("Auth fail") : e; assert getRootCause(e).getMessage().contains("Auth fail") : e;
} }
for (Entry<? extends NodeMetadata, ExecResponse> response : client.runScriptOnNodesMatching( for (Entry<? extends NodeMetadata, ExecResponse> response : client.runScriptOnNodesMatching(
runningInGroup(group), Statements.exec("echo hello"), runningInGroup(group), Statements.exec("echo hello"),
overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet()) overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet())
assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": "
+ response.getValue(); + response.getValue();
runScriptWithCreds(group, os, good); runScriptWithCreds(group, os, good);
@ -298,7 +298,8 @@ public abstract class BaseComputeServiceLiveTest {
// template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) // template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public"))
// .runScript(buildScript(template.getImage().getOperatingSystem())); // .runScript(buildScript(template.getImage().getOperatingSystem()));
template.getOptions().runScript( template.getOptions().runScript(
Statements.newStatementList(AdminAccess.standard(), buildScript(template.getImage().getOperatingSystem()))); Statements.newStatementList(AdminAccess.standard(),
buildScript(template.getImage().getOperatingSystem())));
} }
protected void checkImageIdMatchesTemplate(NodeMetadata node) { protected void checkImageIdMatchesTemplate(NodeMetadata node) {
@ -309,8 +310,8 @@ public abstract class BaseComputeServiceLiveTest {
protected void checkOsMatchesTemplate(NodeMetadata node) { protected void checkOsMatchesTemplate(NodeMetadata node) {
if (node.getOperatingSystem() != null) if (node.getOperatingSystem() != null)
assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String
.format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), .format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), node
node.getOperatingSystem()); .getOperatingSystem());
} }
void assertLocationSameOrChild(Location test, Location expected) { void assertLocationSameOrChild(Location test, Location expected) {
@ -342,10 +343,10 @@ public abstract class BaseComputeServiceLiveTest {
} }
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String group, OperatingSystem os, protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String group, OperatingSystem os,
Credentials creds) throws RunScriptOnNodesException { Credentials creds) throws RunScriptOnNodesException {
try { try {
return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds)
.nameTask("runScriptWithCreds")); .nameTask("runScriptWithCreds"));
} catch (SshException e) { } catch (SshException e) {
throw e; throw e;
} }
@ -375,16 +376,16 @@ public abstract class BaseComputeServiceLiveTest {
@Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
public void testGet() throws Exception { public void testGet() throws Exception {
Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex( Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex(filter(client
filter(client.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))),
new Function<NodeMetadata, String>() { new Function<NodeMetadata, String>() {
@Override @Override
public String apply(NodeMetadata from) { public String apply(NodeMetadata from) {
return from.getId(); return from.getId();
} }
})); }));
for (NodeMetadata node : nodes) { for (NodeMetadata node : nodes) {
metadataMap.remove(node.getId()); metadataMap.remove(node.getId());
NodeMetadata metadata = client.getNodeMetadata(node.getId()); NodeMetadata metadata = client.getNodeMetadata(node.getId());
@ -403,7 +404,7 @@ public abstract class BaseComputeServiceLiveTest {
protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet) { protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet) {
assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]",
metadataSet, nodes); metadataSet, nodes);
} }
@Test(enabled = true, dependsOnMethods = "testGet") @Test(enabled = true, dependsOnMethods = "testGet")
@ -491,12 +492,12 @@ public abstract class BaseComputeServiceLiveTest {
} }
template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080))
.build(); .build();
// note this is a dependency on the template resolution // note this is a dependency on the template resolution
template.getOptions().runScript( template.getOptions().runScript(
RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage()
.getOperatingSystem())); .getOperatingSystem()));
try { try {
NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template)); NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template));
@ -530,26 +531,26 @@ public abstract class BaseComputeServiceLiveTest {
assert location != location.getParent() : location; assert location != location.getParent() : location;
assert location.getScope() != null : location; assert location.getScope() != null : location;
switch (location.getScope()) { switch (location.getScope()) {
case PROVIDER: case PROVIDER:
assertProvider(location); assertProvider(location);
break; break;
case REGION: case REGION:
assertProvider(location.getParent()); assertProvider(location.getParent());
break; break;
case ZONE: case ZONE:
Location provider = location.getParent().getParent(); Location provider = location.getParent().getParent();
// zone can be a direct descendant of provider // zone can be a direct descendant of provider
if (provider == null) if (provider == null)
provider = location.getParent(); provider = location.getParent();
assertProvider(provider); assertProvider(provider);
break; break;
case HOST: case HOST:
Location provider2 = location.getParent().getParent().getParent(); Location provider2 = location.getParent().getParent().getParent();
// zone can be a direct descendant of provider // zone can be a direct descendant of provider
if (provider2 == null) if (provider2 == null)
provider2 = location.getParent().getParent(); provider2 = location.getParent().getParent();
assertProvider(provider2); assertProvider(provider2);
break; break;
} }
} }
} }
@ -582,10 +583,10 @@ public abstract class BaseComputeServiceLiveTest {
public void testListSizes() throws Exception { public void testListSizes() throws Exception {
for (Hardware hardware : client.listHardwareProfiles()) { for (Hardware hardware : client.listHardwareProfiles()) {
assert hardware.getProviderId() != null; assert hardware.getProviderId() != null : hardware;
assert getCores(hardware) > 0; assert getCores(hardware) > 0 : hardware;
assert hardware.getVolumes().size() >= 0; assert hardware.getVolumes().size() >= 0 : hardware;
assert hardware.getRam() > 0; assert hardware.getRam() > 0 : hardware;
assertEquals(hardware.getType(), ComputeType.HARDWARE); assertEquals(hardware.getType(), ComputeType.HARDWARE);
} }
} }
@ -637,7 +638,7 @@ public abstract class BaseComputeServiceLiveTest {
assertEquals(hello.getOutput().trim(), "hello"); assertEquals(hello.getOutput().trim(), "hello");
ExecResponse exec = ssh.exec("java -version"); ExecResponse exec = ssh.exec("java -version");
assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n" assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n"
+ ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log"); + ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log");
} finally { } finally {
if (ssh != null) if (ssh != null)
ssh.disconnect(); ssh.disconnect();

View File

@ -167,7 +167,7 @@ public abstract class BaseTemplateBuilderLiveTest {
Template defaultTemplate = context.getComputeService().templateBuilder().build(); Template defaultTemplate = context.getComputeService().templateBuilder().build();
Template template = context.getComputeService().templateBuilder().imageId(defaultTemplate.getImage().getId()) Template template = context.getComputeService().templateBuilder().imageId(defaultTemplate.getImage().getId())
.build(); .locationId(defaultTemplate.getLocation().getId()).build();
assertEquals(template.getImage(), defaultTemplate.getImage()); assertEquals(template.getImage(), defaultTemplate.getImage());
} }

View File

@ -743,34 +743,7 @@ public class RestAnnotationProcessor<T> {
|| TypeLiteral.get(method.getGenericReturnType()).equals(futureHttpResponseLiteral)) { || TypeLiteral.get(method.getGenericReturnType()).equals(futureHttpResponseLiteral)) {
return Key.get((Class) IdentityFunction.class); return Key.get((Class) IdentityFunction.class);
} else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) { } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) {
Type returnVal; return getJsonParserKeyForMethod(method);
if (method.getReturnType().getTypeParameters().length == 0) {
returnVal = method.getReturnType();
} else if (method.getReturnType().equals(ListenableFuture.class)) {
ParameterizedType futureType = ((ParameterizedType) method.getGenericReturnType());
returnVal = futureType.getActualTypeArguments()[0];
if (returnVal instanceof WildcardType)
returnVal = WildcardType.class.cast(returnVal).getUpperBounds()[0];
} else {
returnVal = method.getGenericReturnType();
}
ParameterizedType parserType;
if (method.isAnnotationPresent(Unwrap.class)) {
int depth = method.getAnnotation(Unwrap.class).depth();
Class edgeCollection = method.getAnnotation(Unwrap.class).edgeCollection();
if (depth == 1 && edgeCollection == Map.class)
parserType = Types.newParameterizedType(UnwrapOnlyJsonValue.class, returnVal);
else if (depth == 2 && edgeCollection == Map.class)
parserType = Types.newParameterizedType(UnwrapOnlyNestedJsonValue.class, returnVal);
else if (depth == 3 && edgeCollection == Set.class)
parserType = Types.newParameterizedType(UnwrapOnlyNestedJsonValueInSet.class, returnVal);
else
throw new IllegalStateException(String.format(
"depth(%d) edgeCollection(%s) not yet supported for @Unwrap", depth, edgeCollection));
} else {
parserType = Types.newParameterizedType(ParseJson.class, returnVal);
}
return (Key<? extends Function<HttpResponse, ?>>) Key.get(parserType);
} else if (method.getReturnType().equals(String.class) } else if (method.getReturnType().equals(String.class)
|| TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) { || TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) {
return Key.get(ReturnStringIf2xx.class); return Key.get(ReturnStringIf2xx.class);
@ -784,6 +757,47 @@ public class RestAnnotationProcessor<T> {
return Key.get(annotation.value()); return Key.get(annotation.value());
} }
public static Key<? extends Function<HttpResponse, ?>> getJsonParserKeyForMethod(Method method) {
Type returnVal = getReturnTypeForMethod(method);
return getJsonParserKeyForMethodAnType(method, returnVal);
}
public static Type getReturnTypeForMethod(Method method) {
Type returnVal;
if (method.getReturnType().getTypeParameters().length == 0) {
returnVal = method.getReturnType();
} else if (method.getReturnType().equals(ListenableFuture.class)) {
ParameterizedType futureType = ((ParameterizedType) method.getGenericReturnType());
returnVal = futureType.getActualTypeArguments()[0];
if (returnVal instanceof WildcardType)
returnVal = WildcardType.class.cast(returnVal).getUpperBounds()[0];
} else {
returnVal = method.getGenericReturnType();
}
return returnVal;
}
@SuppressWarnings( { "unchecked", "rawtypes" })
public static Key<? extends Function<HttpResponse, ?>> getJsonParserKeyForMethodAnType(Method method, Type returnVal) {
ParameterizedType parserType;
if (method.isAnnotationPresent(Unwrap.class)) {
int depth = method.getAnnotation(Unwrap.class).depth();
Class edgeCollection = method.getAnnotation(Unwrap.class).edgeCollection();
if (depth == 1 && edgeCollection == Map.class)
parserType = Types.newParameterizedType(UnwrapOnlyJsonValue.class, returnVal);
else if (depth == 2 && edgeCollection == Map.class)
parserType = Types.newParameterizedType(UnwrapOnlyNestedJsonValue.class, returnVal);
else if (depth == 3 && edgeCollection == Set.class)
parserType = Types.newParameterizedType(UnwrapOnlyNestedJsonValueInSet.class, returnVal);
else
throw new IllegalStateException(String.format("depth(%d) edgeCollection(%s) not yet supported for @Unwrap",
depth, edgeCollection));
} else {
parserType = Types.newParameterizedType(ParseJson.class, returnVal);
}
return (Key<? extends Function<HttpResponse, ?>>) Key.get(parserType);
}
public static Class<? extends HandlerWithResult<?>> getSaxResponseParserClassOrNull(Method method) { public static Class<? extends HandlerWithResult<?>> getSaxResponseParserClassOrNull(Method method) {
XMLResponseParser annotation = method.getAnnotation(XMLResponseParser.class); XMLResponseParser annotation = method.getAnnotation(XMLResponseParser.class);
if (annotation != null) { if (annotation != null) {

View File

@ -126,8 +126,8 @@ openhosting-east1.contextbuilder=org.jclouds.openhosting.OpenHostingEast1Context
cloudsigma-zrh.propertiesbuilder=org.jclouds.cloudsigma.CloudSigmaZurichPropertiesBuilder cloudsigma-zrh.propertiesbuilder=org.jclouds.cloudsigma.CloudSigmaZurichPropertiesBuilder
cloudsigma-zrh.contextbuilder=org.jclouds.cloudsigma.CloudSigmaContextBuilder cloudsigma-zrh.contextbuilder=org.jclouds.cloudsigma.CloudSigmaContextBuilder
ibmdev.propertiesbuilder=org.jclouds.ibmdev.IBMDeveloperCloudPropertiesBuilder ibm-smartcloud.propertiesbuilder=org.jclouds.ibm.smartcloud.IBMSmartCloudPropertiesBuilder
ibmdev.contextbuilder=org.jclouds.ibmdev.IBMDeveloperCloudContextBuilder ibm-smartcloud.contextbuilder=org.jclouds.ibm.smartcloud.IBMSmartCloudContextBuilder
stub.contextbuilder=org.jclouds.compute.stub.StubComputeServiceContextBuilder stub.contextbuilder=org.jclouds.compute.stub.StubComputeServiceContextBuilder
# example of where to change your endpoint # example of where to change your endpoint

View File

@ -20,18 +20,24 @@ package org.jclouds.json;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyNestedJsonValue; import org.jclouds.io.Payload;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
/** /**
* *
@ -39,22 +45,41 @@ import com.google.inject.util.Types;
*/ */
public abstract class BaseParserTest<T, G> { public abstract class BaseParserTest<T, G> {
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Qualifier
public @interface Nested {
}
@SuppressWarnings("unchecked")
protected Function<HttpResponse, T> parser(Injector i) {
try {
return (Function<HttpResponse, T>) i.getInstance(RestAnnotationProcessor.getJsonParserKeyForMethod(getClass()
.getMethod("expected")));
} catch (Exception e) {
Throwables.propagate(e);
return null;
}
}
@Test @Test
public void test() { public void test() {
T expects = expected(); T expects = expected();
Function<HttpResponse, T> parser = parser(injector());
Function<HttpResponse, T> parser = getParser(getInjector()); T response = parser.apply(new HttpResponse(200, "ok", payload()));
T response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(getClass()
.getResourceAsStream(resource()))));
compare(expects, response); compare(expects, response);
} }
protected Payload payload() {
return Payloads.newInputStreamPayload(getClass().getResourceAsStream(resource()));
}
public void compare(T expects, T response) { public void compare(T expects, T response) {
assertEquals(response.toString(), expects.toString()); assertEquals(response.toString(), expects.toString());
} }
protected Injector getInjector() { protected Injector injector() {
return Guice.createInjector(new GsonModule() { return Guice.createInjector(new GsonModule() {
@Override @Override
@ -67,15 +92,9 @@ public abstract class BaseParserTest<T, G> {
} }
@SuppressWarnings("unchecked") protected String resource() {
protected Function<HttpResponse, T> getParser(Injector i) { throw new IllegalStateException("please define resource such as \"/testaddresses.json\"");
return (Function<HttpResponse, T>) i.getInstance(Key.get(TypeLiteral.get(
Types.newParameterizedType(UnwrapOnlyNestedJsonValue.class, type())).getType()));
} }
public abstract Class<G> type();
public abstract String resource();
public abstract T expected(); public abstract T expected();
} }

View File

@ -22,15 +22,7 @@ import static org.testng.Assert.assertEquals;
import java.util.Set; import java.util.Set;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyNestedJsonValue;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
/** /**
* *
@ -38,15 +30,6 @@ import com.google.inject.util.Types;
*/ */
public abstract class BaseSetParserTest<T> extends BaseParserTest<Set<T>, T> { public abstract class BaseSetParserTest<T> extends BaseParserTest<Set<T>, T> {
@SuppressWarnings("unchecked")
// crazy stuff due to type erasure
@Override
protected Function<HttpResponse, Set<T>> getParser(Injector i) {
return (Function<HttpResponse, Set<T>>) i.getInstance(Key.get(TypeLiteral.get(
Types.newParameterizedType(UnwrapOnlyNestedJsonValue.class, Types
.newParameterizedType(Set.class, type()))).getType()));
}
public void compare(Set<T> expects, Set<T> response) { public void compare(Set<T> expects, Set<T> response) {
assertEquals(ImmutableSortedSet.copyOf(response).toString(), ImmutableSortedSet.copyOf(expects).toString()); assertEquals(ImmutableSortedSet.copyOf(response).toString(), ImmutableSortedSet.copyOf(expects).toString());
} }

View File

@ -39,11 +39,6 @@ import com.google.inject.Injector;
@Test(groups = "unit") @Test(groups = "unit")
public class UnwrapLoadBalancerTest extends BaseItemParserTest<LoadBalancer> { public class UnwrapLoadBalancerTest extends BaseItemParserTest<LoadBalancer> {
@Override
public Class<LoadBalancer> type() {
return LoadBalancer.class;
}
@Override @Override
public String resource() { public String resource() {
return "/getloadbalancer.json"; return "/getloadbalancer.json";
@ -73,7 +68,7 @@ public class UnwrapLoadBalancerTest extends BaseItemParserTest<LoadBalancer> {
} }
@Override @Override
protected Function<HttpResponse, LoadBalancer> getParser(Injector i) { protected Function<HttpResponse, LoadBalancer> parser(Injector i) {
return i.getInstance(UnwrapLoadBalancer.class).setRegion("DFW"); return i.getInstance(UnwrapLoadBalancer.class).setRegion("DFW");
} }
} }

View File

@ -39,11 +39,6 @@ import com.google.inject.Injector;
@Test(groups = "unit") @Test(groups = "unit")
public class UnwrapLoadBalancersTest extends BaseSetParserTest<LoadBalancer> { public class UnwrapLoadBalancersTest extends BaseSetParserTest<LoadBalancer> {
@Override
public Class<LoadBalancer> type() {
return LoadBalancer.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listloadbalancers.json"; return "/listloadbalancers.json";
@ -70,7 +65,7 @@ public class UnwrapLoadBalancersTest extends BaseSetParserTest<LoadBalancer> {
} }
@Override @Override
protected Function<HttpResponse, Set<LoadBalancer>> getParser(Injector i) { protected Function<HttpResponse, Set<LoadBalancer>> parser(Injector i) {
return i.getInstance(UnwrapLoadBalancers.class).setRegion("DFW"); return i.getInstance(UnwrapLoadBalancers.class).setRegion("DFW");
} }
} }

View File

@ -28,6 +28,7 @@ import org.jclouds.cloudstack.domain.Account.Type;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -40,8 +41,9 @@ import com.google.inject.Injector;
*/ */
@Test(groups = "unit") @Test(groups = "unit")
public class ListAccountsResponseTest extends BaseSetParserTest<Account> { public class ListAccountsResponseTest extends BaseSetParserTest<Account> {
@Override @Override
protected Injector getInjector() { protected Injector injector() {
return Guice.createInjector(new CloudStackParserModule(), new GsonModule() { return Guice.createInjector(new CloudStackParserModule(), new GsonModule() {
@Override @Override
@ -54,17 +56,13 @@ public class ListAccountsResponseTest extends BaseSetParserTest<Account> {
} }
@Override
public Class<Account> type() {
return Account.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listaccountsresponse.json"; return "/listaccountsresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<Account> expected() { public Set<Account> expected() {
return ImmutableSet.<Account> of(Account return ImmutableSet.<Account> of(Account
.builder() .builder()

View File

@ -20,6 +20,7 @@ package org.jclouds.cloudstack.parse;
import org.jclouds.cloudstack.domain.Capabilities; import org.jclouds.cloudstack.domain.Capabilities;
import org.jclouds.json.BaseItemParserTest; import org.jclouds.json.BaseItemParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
@ -29,17 +30,13 @@ import org.testng.annotations.Test;
@Test(groups = "unit") @Test(groups = "unit")
public class ListCapabilitiesResponseTest extends BaseItemParserTest<Capabilities> { public class ListCapabilitiesResponseTest extends BaseItemParserTest<Capabilities> {
@Override
public Class<Capabilities> type() {
return Capabilities.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listcapabilitiesresponse.json"; return "/listcapabilitiesresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Capabilities expected() { public Capabilities expected() {
return Capabilities.builder().securityGroupsEnabled(true).sharedTemplatesEnabled(true).cloudStackVersion("2.2") return Capabilities.builder().securityGroupsEnabled(true).sharedTemplatesEnabled(true).cloudStackVersion("2.2")
.build(); .build();

View File

@ -23,6 +23,7 @@ import java.util.Set;
import org.jclouds.cloudstack.domain.DiskOffering; import org.jclouds.cloudstack.domain.DiskOffering;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -34,17 +35,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListDiskOfferingsResponseTest extends BaseSetParserTest<DiskOffering> { public class ListDiskOfferingsResponseTest extends BaseSetParserTest<DiskOffering> {
@Override
public Class<DiskOffering> type() {
return DiskOffering.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listdiskofferingsresponse.json"; return "/listdiskofferingsresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<DiskOffering> expected() { public Set<DiskOffering> expected() {
return ImmutableSet.<DiskOffering> of( return ImmutableSet.<DiskOffering> of(
DiskOffering.builder().id(3).domainId(1).domain("ROOT").name("Small").displayText("Small Disk, 5 GB") DiskOffering.builder().id(3).domainId(1).domain("ROOT").name("Small").displayText("Small Disk, 5 GB")

View File

@ -36,11 +36,6 @@ import com.google.inject.Injector;
@Test(groups = "unit") @Test(groups = "unit")
public class ListHypervisorsResponseTest extends BaseSetParserTest<String> { public class ListHypervisorsResponseTest extends BaseSetParserTest<String> {
@Override
public Class<String> type() {
return String.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listhypervisorsresponse.json"; return "/listhypervisorsresponse.json";
@ -52,7 +47,7 @@ public class ListHypervisorsResponseTest extends BaseSetParserTest<String> {
} }
@Override @Override
protected Function<HttpResponse, Set<String>> getParser(Injector injector) { protected Function<HttpResponse, Set<String>> parser(Injector injector) {
return injector.getInstance(ParseNamesFromHttpResponse.class); return injector.getInstance(ParseNamesFromHttpResponse.class);
} }
} }

View File

@ -23,6 +23,7 @@ import java.util.Set;
import org.jclouds.cloudstack.domain.NetworkOffering; import org.jclouds.cloudstack.domain.NetworkOffering;
import org.jclouds.cloudstack.domain.TrafficType; import org.jclouds.cloudstack.domain.TrafficType;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -34,17 +35,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListNetworkOfferingsResponseTest extends BaseSetParserTest<NetworkOffering> { public class ListNetworkOfferingsResponseTest extends BaseSetParserTest<NetworkOffering> {
@Override
public Class<NetworkOffering> type() {
return NetworkOffering.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listnetworkofferingsresponse.json"; return "/listnetworkofferingsresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<NetworkOffering> expected() { public Set<NetworkOffering> expected() {
return ImmutableSet.<NetworkOffering> of( return ImmutableSet.<NetworkOffering> of(
NetworkOffering.builder().id(7).name("DefaultDirectNetworkOffering").displayText("Direct") NetworkOffering.builder().id(7).name("DefaultDirectNetworkOffering").displayText("Direct")

View File

@ -26,6 +26,7 @@ import org.jclouds.cloudstack.domain.Network;
import org.jclouds.cloudstack.domain.NetworkService; import org.jclouds.cloudstack.domain.NetworkService;
import org.jclouds.cloudstack.domain.TrafficType; import org.jclouds.cloudstack.domain.TrafficType;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -41,17 +42,13 @@ import com.google.common.collect.ImmutableSortedSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListNetworksResponseTest extends BaseSetParserTest<Network> { public class ListNetworksResponseTest extends BaseSetParserTest<Network> {
@Override
public Class<Network> type() {
return Network.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listnetworksresponse.json"; return "/listnetworksresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<Network> expected() { public Set<Network> expected() {
return ImmutableSet return ImmutableSet
.<Network> of(Network .<Network> of(Network

View File

@ -49,13 +49,7 @@ public class ListOSCategoriesResponseTest extends BaseItemParserTest<Map<Long, S
} }
@Override @Override
protected Function<HttpResponse, Map<Long, String>> getParser(Injector injector) { protected Function<HttpResponse, Map<Long, String>> parser(Injector injector) {
return injector.getInstance(ParseIdToNameFromHttpResponse.class); return injector.getInstance(ParseIdToNameFromHttpResponse.class);
} }
@SuppressWarnings( { "unchecked", "rawtypes" })
@Override
public Class<Map<Long, String>> type() {
return (Class) Map.class;
}
} }

View File

@ -19,9 +19,12 @@
package org.jclouds.cloudstack.parse; package org.jclouds.cloudstack.parse;
import java.util.Set; import java.util.Set;
import org.jclouds.cloudstack.domain.OSType; import org.jclouds.cloudstack.domain.OSType;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
/** /**
@ -30,10 +33,6 @@ import com.google.common.collect.ImmutableSet;
*/ */
@Test(groups = "unit") @Test(groups = "unit")
public class ListOSTypesResponseTest extends BaseSetParserTest<OSType> { public class ListOSTypesResponseTest extends BaseSetParserTest<OSType> {
@Override
public Class<OSType> type() {
return OSType.class;
}
@Override @Override
public String resource() { public String resource() {
@ -41,6 +40,7 @@ public class ListOSTypesResponseTest extends BaseSetParserTest<OSType> {
} }
@Override @Override
@Unwrap(depth = 2)
public Set<OSType> expected() { public Set<OSType> expected() {
return ImmutableSet.<OSType> builder().add( return ImmutableSet.<OSType> builder().add(
OSType.builder().id(69).OSCategoryId(7).description("Asianux 3(32-bit)").build()).add( OSType.builder().id(69).OSCategoryId(7).description("Asianux 3(32-bit)").build()).add(

View File

@ -22,6 +22,7 @@ import java.util.Set;
import org.jclouds.cloudstack.domain.PortForwardingRule; import org.jclouds.cloudstack.domain.PortForwardingRule;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -33,17 +34,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListPortForwardingRulesResponseTest extends BaseSetParserTest<PortForwardingRule> { public class ListPortForwardingRulesResponseTest extends BaseSetParserTest<PortForwardingRule> {
@Override
public Class<PortForwardingRule> type() {
return PortForwardingRule.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listportforwardingrulesresponse.json"; return "/listportforwardingrulesresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<PortForwardingRule> expected() { public Set<PortForwardingRule> expected() {
return ImmutableSet.<PortForwardingRule> of( return ImmutableSet.<PortForwardingRule> of(
PortForwardingRule.builder().id(15).privatePort(22).protocol("tcp").publicPort(2022).virtualMachineId(3) PortForwardingRule.builder().id(15).privatePort(22).protocol("tcp").publicPort(2022).virtualMachineId(3)

View File

@ -23,6 +23,7 @@ import java.util.Set;
import org.jclouds.cloudstack.domain.PublicIPAddress; import org.jclouds.cloudstack.domain.PublicIPAddress;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -34,10 +35,6 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListPublicIPAddressesResponseTest extends BaseSetParserTest<PublicIPAddress> { public class ListPublicIPAddressesResponseTest extends BaseSetParserTest<PublicIPAddress> {
@Override
public Class<PublicIPAddress> type() {
return PublicIPAddress.class;
}
@Override @Override
public String resource() { public String resource() {
@ -45,6 +42,7 @@ public class ListPublicIPAddressesResponseTest extends BaseSetParserTest<PublicI
} }
@Override @Override
@Unwrap(depth = 2)
public Set<PublicIPAddress> expected() { public Set<PublicIPAddress> expected() {
return ImmutableSet.of(PublicIPAddress.builder().id(30).IPAddress("72.52.126.59") return ImmutableSet.of(PublicIPAddress.builder().id(30).IPAddress("72.52.126.59")
.allocated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2011-02-19T21:15:01-0800")).zoneId(1) .allocated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2011-02-19T21:15:01-0800")).zoneId(1)

View File

@ -23,6 +23,7 @@ import java.util.Set;
import org.jclouds.cloudstack.domain.IngressRule; import org.jclouds.cloudstack.domain.IngressRule;
import org.jclouds.cloudstack.domain.SecurityGroup; import org.jclouds.cloudstack.domain.SecurityGroup;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -34,17 +35,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListSecurityGroupsResponseTest extends BaseSetParserTest<SecurityGroup> { public class ListSecurityGroupsResponseTest extends BaseSetParserTest<SecurityGroup> {
@Override
public Class<SecurityGroup> type() {
return SecurityGroup.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listsecuritygroupsresponse.json"; return "/listsecuritygroupsresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<SecurityGroup> expected() { public Set<SecurityGroup> expected() {
return ImmutableSet return ImmutableSet
.<SecurityGroup> builder() .<SecurityGroup> builder()

View File

@ -24,6 +24,7 @@ import org.jclouds.cloudstack.domain.ServiceOffering;
import org.jclouds.cloudstack.domain.StorageType; import org.jclouds.cloudstack.domain.StorageType;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -35,17 +36,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListServiceOfferingsResponseTest extends BaseSetParserTest<ServiceOffering> { public class ListServiceOfferingsResponseTest extends BaseSetParserTest<ServiceOffering> {
@Override
public Class<ServiceOffering> type() {
return ServiceOffering.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listserviceofferingsresponse.json"; return "/listserviceofferingsresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<ServiceOffering> expected() { public Set<ServiceOffering> expected() {
return ImmutableSet.<ServiceOffering> of( return ImmutableSet.<ServiceOffering> of(
ServiceOffering.builder().id(1).name("Small Instance") ServiceOffering.builder().id(1).name("Small Instance")

View File

@ -25,6 +25,7 @@ import org.jclouds.cloudstack.domain.Template.Format;
import org.jclouds.cloudstack.domain.Template.Type; import org.jclouds.cloudstack.domain.Template.Type;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -36,11 +37,6 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListTemplatesResponseTest extends BaseSetParserTest<Template> { public class ListTemplatesResponseTest extends BaseSetParserTest<Template> {
@Override
public Class<Template> type() {
return Template.class;
}
@Override @Override
public String resource() { public String resource() {
// grep listtemplatesresponse ./target/test-data/jclouds-wire.log|tail // grep listtemplatesresponse ./target/test-data/jclouds-wire.log|tail
@ -49,6 +45,7 @@ public class ListTemplatesResponseTest extends BaseSetParserTest<Template> {
} }
@Override @Override
@Unwrap(depth = 2)
public Set<Template> expected() { public Set<Template> expected() {
return ImmutableSet.of( return ImmutableSet.of(
Template.builder().id(2).name("CentOS 5.3(64-bit) no GUI (XenServer)") Template.builder().id(2).name("CentOS 5.3(64-bit) no GUI (XenServer)")

View File

@ -26,6 +26,7 @@ import org.jclouds.cloudstack.domain.TrafficType;
import org.jclouds.cloudstack.domain.VirtualMachine; import org.jclouds.cloudstack.domain.VirtualMachine;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -37,17 +38,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListVirtualMachinesResponseTest extends BaseSetParserTest<VirtualMachine> { public class ListVirtualMachinesResponseTest extends BaseSetParserTest<VirtualMachine> {
@Override
public Class<VirtualMachine> type() {
return VirtualMachine.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listvirtualmachinesresponse.json"; return "/listvirtualmachinesresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<VirtualMachine> expected() { public Set<VirtualMachine> expected() {
return ImmutableSet.of(VirtualMachine return ImmutableSet.of(VirtualMachine
.builder() .builder()

View File

@ -23,6 +23,7 @@ import java.util.Set;
import org.jclouds.cloudstack.domain.NetworkType; import org.jclouds.cloudstack.domain.NetworkType;
import org.jclouds.cloudstack.domain.Zone; import org.jclouds.cloudstack.domain.Zone;
import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -34,17 +35,13 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit") @Test(groups = "unit")
public class ListZonesResponseTest extends BaseSetParserTest<Zone> { public class ListZonesResponseTest extends BaseSetParserTest<Zone> {
@Override
public Class<Zone> type() {
return Zone.class;
}
@Override @Override
public String resource() { public String resource() {
return "/listzonesresponse.json"; return "/listzonesresponse.json";
} }
@Override @Override
@Unwrap(depth = 2)
public Set<Zone> expected() { public Set<Zone> expected() {
return ImmutableSet.of(Zone.builder().id(1).name("San Jose 1").networkType(NetworkType.ADVANCED) return ImmutableSet.of(Zone.builder().id(1).name("San Jose 1").networkType(NetworkType.ADVANCED)
.securityGroupsEnabled(false).build(), .securityGroupsEnabled(false).build(),

View File

@ -34,9 +34,9 @@
<relativePath>../../project/pom.xml</relativePath> <relativePath>../../project/pom.xml</relativePath>
</parent> </parent>
<groupId>org.jclouds.provider</groupId> <groupId>org.jclouds.provider</groupId>
<artifactId>ibmdev</artifactId> <artifactId>ibm-smartcloud</artifactId>
<name>jclouds IBMDeveloperCloud core</name> <name>jclouds IBM SmartCloud core</name>
<description>jclouds components to access IBMDeveloperCloud</description> <description>jclouds components to access IBM SmartCloud</description>
<!-- bootstrapping: need to fetch the project POM --> <!-- bootstrapping: need to fetch the project POM -->
<repositories> <repositories>
<repository> <repository>
@ -52,10 +52,10 @@
</repositories> </repositories>
<properties> <properties>
<test.ibmdev.endpoint>https://www-147.ibm.com/computecloud/enterprise/api/rest</test.ibmdev.endpoint> <test.ibm-smartcloud.endpoint>https://www-147.ibm.com/computecloud/enterprise/api/rest</test.ibm-smartcloud.endpoint>
<test.ibmdev.apiversion>20100331</test.ibmdev.apiversion> <test.ibm-smartcloud.apiversion>20100331</test.ibm-smartcloud.apiversion>
<test.ibmdev.identity>FIXME</test.ibmdev.identity> <test.ibm-smartcloud.identity>FIXME</test.ibm-smartcloud.identity>
<test.ibmdev.credential>FIXME</test.ibmdev.credential> <test.ibm-smartcloud.credential>FIXME</test.ibm-smartcloud.credential>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -82,12 +82,6 @@
<type>test-jar</type> <type>test-jar</type>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.jclouds.driver</groupId> <groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId> <artifactId>jclouds-log4j</artifactId>
@ -100,11 +94,6 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<profiles> <profiles>
<profile> <profile>
@ -124,20 +113,20 @@
<configuration> <configuration>
<systemProperties> <systemProperties>
<property> <property>
<name>test.ibmdev.endpoint</name> <name>test.ibm-smartcloud.endpoint</name>
<value>${test.ibmdev.endpoint}</value> <value>${test.ibm-smartcloud.endpoint}</value>
</property> </property>
<property> <property>
<name>test.ibmdev.apiversion</name> <name>test.ibm-smartcloud.apiversion</name>
<value>${test.ibmdev.apiversion}</value> <value>${test.ibm-smartcloud.apiversion}</value>
</property> </property>
<property> <property>
<name>test.ibmdev.identity</name> <name>test.ibm-smartcloud.identity</name>
<value>${test.ibmdev.identity}</value> <value>${test.ibm-smartcloud.identity}</value>
</property> </property>
<property> <property>
<name>test.ibmdev.credential</name> <name>test.ibm-smartcloud.credential</name>
<value>${test.ibmdev.credential}</value> <value>${test.ibm-smartcloud.credential}</value>
</property> </property>
</systemProperties> </systemProperties>
</configuration> </configuration>

View File

@ -16,9 +16,8 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import java.net.URI;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
@ -33,36 +32,23 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibm.smartcloud.domain.Location;
import org.jclouds.ibmdev.domain.Offering; import org.jclouds.ibm.smartcloud.domain.Offering;
import org.jclouds.ibmdev.domain.StorageOffering; import org.jclouds.ibm.smartcloud.domain.StorageOffering;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibm.smartcloud.domain.Volume;
import org.jclouds.ibmdev.functions.GetFirstInstanceInList; import org.jclouds.ibm.smartcloud.functions.ParseLongFromDate;
import org.jclouds.ibmdev.functions.ParseAddressFromJson; import org.jclouds.ibm.smartcloud.options.CreateInstanceOptions;
import org.jclouds.ibmdev.functions.ParseAddressesFromJson; import org.jclouds.ibm.smartcloud.options.RestartInstanceOptions;
import org.jclouds.ibmdev.functions.ParseExpirationTimeFromJson; import org.jclouds.ibm.smartcloud.xml.LocationHandler;
import org.jclouds.ibmdev.functions.ParseImageFromJson; import org.jclouds.ibm.smartcloud.xml.LocationsHandler;
import org.jclouds.ibmdev.functions.ParseImagesFromJson;
import org.jclouds.ibmdev.functions.ParseInstanceFromJson;
import org.jclouds.ibmdev.functions.ParseInstancesFromJson;
import org.jclouds.ibmdev.functions.ParseKeysFromJson;
import org.jclouds.ibmdev.functions.ParseLongFromDate;
import org.jclouds.ibmdev.functions.ParseVolumeFromJson;
import org.jclouds.ibmdev.functions.ParseVolumesFromJson;
import org.jclouds.ibmdev.options.CreateInstanceOptions;
import org.jclouds.ibmdev.options.RestartInstanceOptions;
import org.jclouds.ibmdev.xml.LocationHandler;
import org.jclouds.ibmdev.xml.LocationsHandler;
import org.jclouds.rest.annotations.EndpointParam;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.FormParams;
import org.jclouds.rest.annotations.ParamParser; import org.jclouds.rest.annotations.ParamParser;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.Unwrap; import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.annotations.XMLResponseParser;
@ -73,305 +59,299 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
/** /**
* Provides asynchronous access to IBMDeveloperCloud via their REST API. * Provides asynchronous access to IBMSmartCloud via their REST API.
* <p/> * <p/>
* *
* @see IBMDeveloperCloudClient * @see IBMSmartCloudClient
* @see <a href="http://www-180.ibm.com/cloud/enterprise/beta/support" /> * @see <a href="http://www-180.ibm.com/cloud/enterprise/beta/support" />
* @author Adrian Cole * @author Adrian Cole
*/ */
@RequestFilters(BasicAuthentication.class) @RequestFilters(BasicAuthentication.class)
@SkipEncoding( { '{', '}' }) @SkipEncoding( { '{', '}' })
public interface IBMDeveloperCloudAsyncClient { public interface IBMSmartCloudAsyncClient {
public static final String VERSION = "20100331"; public static final String VERSION = "20100331";
/** /**
* @see IBMDeveloperCloudClient#listImages() * @see IBMSmartCloudClient#listImages()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image") @Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/image")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImagesFromJson.class) @Unwrap
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Image>> listImages(); ListenableFuture<Set<? extends Image>> listImages();
/** /**
* @see IBMDeveloperCloudClient#getImage(long) * @see IBMSmartCloudClient#getImage(long)
*/ */
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image/{imageId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/image/{imageId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> getImage(@PathParam("imageId") String id); ListenableFuture<Image> getImage(@PathParam("imageId") String id);
/** /**
* @see IBMDeveloperCloudClient#deleteImage * @see IBMSmartCloudClient#getManifestOfImage
*/
@GET
@Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/image/{imageId}/manifest")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Consumes(MediaType.TEXT_XML)
ListenableFuture<String> getManifestOfImage(@PathParam("imageId") String id);
/**
* @see IBMSmartCloudClient#deleteImage
*/ */
@DELETE @DELETE
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image/{imageId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/image/{imageId}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteImage(@PathParam("imageId") String id); ListenableFuture<Void> deleteImage(@PathParam("imageId") String id);
/** /**
* @see IBMDeveloperCloudClient#setImageVisibility(long, Image.Visibility) * @see IBMSmartCloudClient#setImageVisibility(long, Image.Visibility)
*/ */
@PUT @PUT
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image/{imageId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/image/{imageId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id, ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id,
@FormParam("visibility") Image.Visibility visibility); @FormParam("visibility") Image.Visibility visibility);
/** /**
* @see IBMDeveloperCloudClient#listInstancesFromRequest(long) * @see IBMSmartCloudClient#listInstancesFromRequest(long)
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/requests/{requestId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/requests/{requestId}")
@Unwrap
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstancesFromJson.class)
ListenableFuture<Set<? extends Instance>> listInstancesFromRequest(@PathParam("requestId") String requestId); ListenableFuture<Set<? extends Instance>> listInstancesFromRequest(@PathParam("requestId") String requestId);
/** /**
* @see IBMDeveloperCloudClient#listInstances() * @see IBMSmartCloudClient#listInstances()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstancesFromJson.class) @Unwrap
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Instance>> listInstances(); ListenableFuture<Set<? extends Instance>> listInstances();
/** /**
* @see IBMDeveloperCloudClient#getInstance(long) * @see IBMSmartCloudClient#getInstance(long)
*/ */
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances/{instanceId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstanceFromJson.class)
ListenableFuture<Instance> getInstance(@PathParam("instanceId") String id); ListenableFuture<Instance> getInstance(@PathParam("instanceId") String id);
/** /**
* *
* @see IBMDeveloperCloudClient#extendReservationForInstance(long,Date) * @see IBMSmartCloudClient#extendReservationForInstance(long,Date)
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances/{instanceId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseExpirationTimeFromJson.class) @Unwrap
ListenableFuture<Date> extendReservationForInstance(@PathParam("instanceId") String id, ListenableFuture<Date> extendReservationForInstance(@PathParam("instanceId") String id,
@FormParam("expirationTime") @ParamParser(ParseLongFromDate.class) Date expirationTime); @FormParam("expirationTime") @ParamParser(ParseLongFromDate.class) Date expirationTime);
/** /**
* @see IBMDeveloperCloudClient#restartInstance * @see IBMSmartCloudClient#restartInstance
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances/{instanceId}")
@FormParams(keys = "state", values = "restart") @FormParams(keys = "state", values = "restart")
ListenableFuture<Void> restartInstance(@PathParam("instanceId") String id, RestartInstanceOptions... options); ListenableFuture<Void> restartInstance(@PathParam("instanceId") String id, RestartInstanceOptions... options);
/** /**
* @see IBMDeveloperCloudClient#saveInstanceToImage * @see IBMSmartCloudClient#saveInstanceToImage
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances/{instanceId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@FormParams(keys = "state", values = "save") @FormParams(keys = "state", values = "save")
@ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> saveInstanceToImage(@PathParam("instanceId") String id, ListenableFuture<Image> saveInstanceToImage(@PathParam("instanceId") String id,
@FormParam("name") String toImageName, @FormParam("description") String toImageDescription); @FormParam("name") String toImageName, @FormParam("description") String toImageDescription);
/** /**
* @see IBMDeveloperCloudClient#createInstanceInLocation * @see IBMSmartCloudClient#createInstanceInLocation
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(GetFirstInstanceInList.class)
ListenableFuture<Instance> createInstanceInLocation(@FormParam("location") String location, ListenableFuture<Instance> createInstanceInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("imageID") String imageID, @FormParam("name") String name, @FormParam("imageID") String imageID,
@FormParam("instanceType") String instanceType, CreateInstanceOptions... options); @FormParam("instanceType") String instanceType, CreateInstanceOptions... options);
/** /**
* @see IBMDeveloperCloudClient#deleteInstance * @see IBMSmartCloudClient#deleteInstance
*/ */
@DELETE @DELETE
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/instances/{instanceId}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteInstance(@PathParam("instanceId") String id); ListenableFuture<Void> deleteInstance(@PathParam("instanceId") String id);
/** /**
* @see IBMDeveloperCloudClient#listKeys() * @see IBMSmartCloudClient#listKeys()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseKeysFromJson.class) @Unwrap
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Key>> listKeys(); ListenableFuture<Set<? extends Key>> listKeys();
/** /**
* @see IBMDeveloperCloudClient#generateKeyPair(String) * @see IBMSmartCloudClient#generateKeyPair(String)
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Key> generateKeyPair(@FormParam("name") String name); ListenableFuture<Key> generateKeyPair(@FormParam("name") String name);
/** /**
* @see IBMDeveloperCloudClient#addPublicKey(String, String) * @see IBMSmartCloudClient#addPublicKey(String, String)
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys")
ListenableFuture<Void> addPublicKey(@FormParam("name") String name, @FormParam("publicKey") String publicKey); ListenableFuture<Void> addPublicKey(@FormParam("name") String name, @FormParam("publicKey") String publicKey);
/** /**
* @see IBMDeveloperCloudClient#updatePublicKey(String, String) * @see IBMSmartCloudClient#updatePublicKey(String, String)
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys/{keyName}")
ListenableFuture<Void> updatePublicKey(@PathParam("keyName") String name, @FormParam("publicKey") String publicKey); ListenableFuture<Void> updatePublicKey(@PathParam("keyName") String name, @FormParam("publicKey") String publicKey);
/** /**
* @see IBMDeveloperCloudClient#setDefaultStatusOfKey(String, boolean) * @see IBMSmartCloudClient#setDefaultStatusOfKey(String, boolean)
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys/{keyName}")
ListenableFuture<Void> setDefaultStatusOfKey(@PathParam("keyName") String name, ListenableFuture<Void> setDefaultStatusOfKey(@PathParam("keyName") String name,
@FormParam("default") boolean isDefault); @FormParam("default") boolean isDefault);
/** /**
* @see IBMDeveloperCloudClient#getKey(String) * @see IBMSmartCloudClient#getKey(String)
*/ */
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys/{keyName}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Key> getKey(@PathParam("keyName") String name); ListenableFuture<Key> getKey(@PathParam("keyName") String name);
/** /**
* @see IBMDeveloperCloudClient#deleteKey * @see IBMSmartCloudClient#deleteKey
*/ */
@DELETE @DELETE
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}") @Path(IBMSmartCloudAsyncClient.VERSION + "/keys/{keyName}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteKey(@PathParam("keyName") String name); ListenableFuture<Void> deleteKey(@PathParam("keyName") String name);
/** /**
* @see IBMDeveloperCloudClient#listStorageOfferings() * @see IBMSmartCloudClient#listStorageOfferings()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/storage") @Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/storage")
@Unwrap @Unwrap
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends StorageOffering>> listStorageOfferings(); ListenableFuture<Set<? extends StorageOffering>> listStorageOfferings();
/** /**
* @see IBMDeveloperCloudClient#listVolumes() * @see IBMSmartCloudClient#listVolumes()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage") @Path(IBMSmartCloudAsyncClient.VERSION + "/storage")
@ResponseParser(ParseVolumesFromJson.class) @Unwrap
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Volume>> listVolumes(); ListenableFuture<Set<? extends Volume>> listVolumes();
/** /**
* @see IBMDeveloperCloudClient#createVolumeInLocation * @see IBMSmartCloudClient#createVolumeInLocation
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage") @Path(IBMSmartCloudAsyncClient.VERSION + "/storage")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseVolumeFromJson.class)
ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location, ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size, @FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size,
@FormParam("offeringID") String offeringID); @FormParam("offeringID") String offeringID);
/** /**
* @see IBMDeveloperCloudClient#getVolume(long) * @see IBMSmartCloudClient#getVolume(long)
*/ */
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage/{volumeId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/storage/{volumeId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseVolumeFromJson.class)
ListenableFuture<Volume> getVolume(@PathParam("volumeId") String id); ListenableFuture<Volume> getVolume(@PathParam("volumeId") String id);
/** /**
* @see IBMDeveloperCloudClient#deleteVolume * @see IBMSmartCloudClient#deleteVolume
*/ */
@DELETE @DELETE
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage/{volumeId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/storage/{volumeId}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteVolume(@PathParam("volumeId") String id); ListenableFuture<Void> deleteVolume(@PathParam("volumeId") String id);
/** /**
* @see IBMDeveloperCloudClient#listLocations() * @see IBMSmartCloudClient#listLocations()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/locations") @Path(IBMSmartCloudAsyncClient.VERSION + "/locations")
@Consumes(MediaType.TEXT_XML) @Consumes(MediaType.TEXT_XML)
@XMLResponseParser(LocationsHandler.class) @XMLResponseParser(LocationsHandler.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Location>> listLocations(); ListenableFuture<Set<? extends Location>> listLocations();
/** /**
* @see IBMDeveloperCloudClient#getLocation * @see IBMSmartCloudClient#getLocation
*/ */
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/locations/{locationId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/locations/{locationId}")
@Consumes(MediaType.TEXT_XML) @Consumes(MediaType.TEXT_XML)
@XMLResponseParser(LocationHandler.class) @XMLResponseParser(LocationHandler.class)
ListenableFuture<Location> getLocation(@PathParam("locationId") String id); ListenableFuture<Location> getLocation(@PathParam("locationId") String id);
/** /**
* @see IBMDeveloperCloudClient#listAddressOfferings() * @see IBMSmartCloudClient#listAddressOfferings()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/address") @Path(IBMSmartCloudAsyncClient.VERSION + "/offerings/address")
@Unwrap @Unwrap
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Offering>> listAddressOfferings(); ListenableFuture<Set<? extends Offering>> listAddressOfferings();
/** /**
* @see IBMDeveloperCloudClient#listAddresses() * @see IBMSmartCloudClient#listAddresses()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses") @Path(IBMSmartCloudAsyncClient.VERSION + "/addresses")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseAddressesFromJson.class) @Unwrap
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Address>> listAddresses(); ListenableFuture<Set<? extends Address>> listAddresses();
/** /**
* @see IBMDeveloperCloudClient#allocateAddressInLocation * @see IBMSmartCloudClient#allocateAddressInLocation
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses") @Path(IBMSmartCloudAsyncClient.VERSION + "/addresses")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseAddressFromJson.class)
ListenableFuture<Address> allocateAddressInLocation(@FormParam("location") String locationId, ListenableFuture<Address> allocateAddressInLocation(@FormParam("location") String locationId,
@FormParam("offeringID") String offeringID); @FormParam("offeringID") String offeringID);
/** /**
* @see IBMDeveloperCloudClient#releaseAddress * @see IBMSmartCloudClient#releaseAddress
*/ */
@DELETE @DELETE
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses/{addressId}") @Path(IBMSmartCloudAsyncClient.VERSION + "/addresses/{addressId}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> releaseAddress(@PathParam("addressId") String id); ListenableFuture<Void> releaseAddress(@PathParam("addressId") String id);
/**
* @see IBMDeveloperCloudClient#getManifest
*/
@GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Consumes(MediaType.TEXT_XML)
ListenableFuture<String> getManifest(@EndpointParam URI manifest);
} }

View File

@ -16,37 +16,36 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import java.net.URI;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibm.smartcloud.domain.Location;
import org.jclouds.ibmdev.domain.Offering; import org.jclouds.ibm.smartcloud.domain.Offering;
import org.jclouds.ibmdev.domain.StorageOffering; import org.jclouds.ibm.smartcloud.domain.StorageOffering;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibm.smartcloud.domain.Volume;
import org.jclouds.ibmdev.options.CreateInstanceOptions; import org.jclouds.ibm.smartcloud.options.CreateInstanceOptions;
import org.jclouds.ibmdev.options.RestartInstanceOptions; import org.jclouds.ibm.smartcloud.options.RestartInstanceOptions;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
/** /**
* Provides synchronous access to IBMDeveloperCloud. * Provides synchronous access to IBMSmartCloud.
* <p/> * <p/>
* *
* @see IBMDeveloperCloudAsyncClient * @see IBMSmartCloudAsyncClient
* @see <a href="http://www-180.ibm.com/cloud/enterprise/beta/support" /> * @see <a href="http://www-180.ibm.com/cloud/enterprise/beta/support" />
* @author Adrian Cole * @author Adrian Cole
*/ */
@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS)
public interface IBMDeveloperCloudClient { public interface IBMSmartCloudClient {
/** /**
* *
* @return the list of Images available to be provisioned on the IBM * @return the list of Images available to be provisioned on the IBM
@ -75,6 +74,8 @@ public interface IBMDeveloperCloudClient {
*/ */
void deleteImage(String id); void deleteImage(String id);
String getManifestOfImage(String id);
/** /**
* If set to {@code Image.Visibility#PUBLIC}, makes the Image identified by * If set to {@code Image.Visibility#PUBLIC}, makes the Image identified by
* the supplied Image ID publicly available for all users to create Instances * the supplied Image ID publicly available for all users to create Instances
@ -463,6 +464,5 @@ public interface IBMDeveloperCloudClient {
*/ */
void releaseAddress(String id); void releaseAddress(String id);
String getManifest(URI manifest);
} }

View File

@ -16,34 +16,34 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import org.jclouds.compute.ComputeServiceContextBuilder; import org.jclouds.compute.ComputeServiceContextBuilder;
import org.jclouds.ibmdev.compute.config.IBMDeveloperCloudComputeServiceContextModule; import org.jclouds.ibm.smartcloud.compute.config.IBMSmartCloudComputeServiceContextModule;
import org.jclouds.ibmdev.config.IBMDeveloperCloudRestClientModule; import org.jclouds.ibm.smartcloud.config.IBMSmartCloudRestClientModule;
import com.google.inject.Module; import com.google.inject.Module;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudContextBuilder extends public class IBMSmartCloudContextBuilder extends
ComputeServiceContextBuilder<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> { ComputeServiceContextBuilder<IBMSmartCloudClient, IBMSmartCloudAsyncClient> {
public IBMDeveloperCloudContextBuilder(Properties props) { public IBMSmartCloudContextBuilder(Properties props) {
super(IBMDeveloperCloudClient.class, IBMDeveloperCloudAsyncClient.class, props); super(IBMSmartCloudClient.class, IBMSmartCloudAsyncClient.class, props);
} }
protected void addClientModule(List<Module> modules) { protected void addClientModule(List<Module> modules) {
modules.add(new IBMDeveloperCloudRestClientModule()); modules.add(new IBMSmartCloudRestClientModule());
} }
@Override @Override
protected void addContextModule(List<Module> modules) { protected void addContextModule(List<Module> modules) {
modules.add(new IBMDeveloperCloudComputeServiceContextModule()); modules.add(new IBMSmartCloudComputeServiceContextModule());
} }
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.Constants.PROPERTY_ENDPOINT; import static org.jclouds.Constants.PROPERTY_ENDPOINT;
@ -31,27 +31,29 @@ import java.util.Properties;
import org.jclouds.PropertiesBuilder; import org.jclouds.PropertiesBuilder;
/** /**
* Builds properties used in IBMDeveloperCloud Clients * Builds properties used in IBMSmartCloud Clients
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudPropertiesBuilder extends PropertiesBuilder { public class IBMSmartCloudPropertiesBuilder extends PropertiesBuilder {
@Override @Override
protected Properties defaultProperties() { protected Properties defaultProperties() {
Properties properties = super.defaultProperties(); Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_ZONES, "41,61,82,101"); properties.setProperty(PROPERTY_ZONES, "41,61,82,101,121,141");
properties.setProperty(PROPERTY_ISO3166_CODES, "US-NC,DE-BW,US-CO,CA-ON"); properties.setProperty(PROPERTY_ISO3166_CODES, "US-NC,DE-BW,US-CO,CA-ON,JP-12,SG");
properties.setProperty(PROPERTY_ZONE + ".41." + ISO3166_CODES, "US-NC"); properties.setProperty(PROPERTY_ZONE + ".41." + ISO3166_CODES, "US-NC");
properties.setProperty(PROPERTY_ZONE + ".61." + ISO3166_CODES, "DE-BW"); properties.setProperty(PROPERTY_ZONE + ".61." + ISO3166_CODES, "DE-BW");
properties.setProperty(PROPERTY_ZONE + ".82." + ISO3166_CODES, "US-CO"); properties.setProperty(PROPERTY_ZONE + ".82." + ISO3166_CODES, "US-CO");
properties.setProperty(PROPERTY_ZONE + ".101." + ISO3166_CODES, "CA-ON"); properties.setProperty(PROPERTY_ZONE + ".101." + ISO3166_CODES, "CA-ON");
properties.setProperty(PROPERTY_API_VERSION, IBMDeveloperCloudAsyncClient.VERSION); properties.setProperty(PROPERTY_ZONE + ".121." + ISO3166_CODES, "JP-12");
properties.setProperty(PROPERTY_ZONE + ".141." + ISO3166_CODES, "SG");
properties.setProperty(PROPERTY_API_VERSION, IBMSmartCloudAsyncClient.VERSION);
properties.setProperty(PROPERTY_ENDPOINT, "https://www-147.ibm.com/computecloud/enterprise/api/rest"); properties.setProperty(PROPERTY_ENDPOINT, "https://www-147.ibm.com/computecloud/enterprise/api/rest");
properties.setProperty(PROPERTY_TIMEOUT_NODE_RUNNING, (15 * 60 * 1000) + ""); properties.setProperty(PROPERTY_TIMEOUT_NODE_RUNNING, (15 * 60 * 1000) + "");
return properties; return properties;
} }
public IBMDeveloperCloudPropertiesBuilder(Properties properties) { public IBMSmartCloudPropertiesBuilder(Properties properties) {
super(properties); super(properties);
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.config; package org.jclouds.ibm.smartcloud.compute.config;
import org.jclouds.compute.config.BindComputeStrategiesByClass; import org.jclouds.compute.config.BindComputeStrategiesByClass;
import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;
@ -26,50 +26,50 @@ import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy; import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudCreateNodeWithGroupEncodedIntoName; import org.jclouds.ibm.smartcloud.compute.strategy.IBMSmartCloudCreateNodeWithGroupEncodedIntoName;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudDestroyNodeStrategy; import org.jclouds.ibm.smartcloud.compute.strategy.IBMSmartCloudDestroyNodeStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudGetNodeMetadataStrategy; import org.jclouds.ibm.smartcloud.compute.strategy.IBMSmartCloudGetNodeMetadataStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudLifeCycleStrategy; import org.jclouds.ibm.smartcloud.compute.strategy.IBMSmartCloudLifeCycleStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudListNodesStrategy; import org.jclouds.ibm.smartcloud.compute.strategy.IBMSmartCloudListNodesStrategy;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudBindComputeStrategiesByClass extends BindComputeStrategiesByClass { public class IBMSmartCloudBindComputeStrategiesByClass extends BindComputeStrategiesByClass {
@Override @Override
protected Class<? extends CreateNodeWithGroupEncodedIntoName> defineAddNodeWithTagStrategy() { protected Class<? extends CreateNodeWithGroupEncodedIntoName> defineAddNodeWithTagStrategy() {
return IBMDeveloperCloudCreateNodeWithGroupEncodedIntoName.class; return IBMSmartCloudCreateNodeWithGroupEncodedIntoName.class;
} }
@Override @Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() { protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return IBMDeveloperCloudDestroyNodeStrategy.class; return IBMSmartCloudDestroyNodeStrategy.class;
} }
@Override @Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() { protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return IBMDeveloperCloudGetNodeMetadataStrategy.class; return IBMSmartCloudGetNodeMetadataStrategy.class;
} }
@Override @Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() { protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return IBMDeveloperCloudListNodesStrategy.class; return IBMSmartCloudListNodesStrategy.class;
} }
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return IBMDeveloperCloudLifeCycleStrategy.class; return IBMSmartCloudLifeCycleStrategy.class;
} }
@Override @Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() { protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return IBMDeveloperCloudLifeCycleStrategy.class; return IBMSmartCloudLifeCycleStrategy.class;
} }
@Override @Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() { protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return IBMDeveloperCloudLifeCycleStrategy.class; return IBMSmartCloudLifeCycleStrategy.class;
} }
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.config; package org.jclouds.ibm.smartcloud.compute.config;
import java.util.Set; import java.util.Set;
@ -24,27 +24,27 @@ import org.jclouds.compute.config.BindComputeSuppliersByClass;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.ibmdev.compute.suppliers.IBMDeveloperCloudHardwareSupplier; import org.jclouds.ibm.smartcloud.compute.suppliers.IBMSmartCloudHardwareSupplier;
import org.jclouds.ibmdev.compute.suppliers.IBMDeveloperCloudImageSupplier; import org.jclouds.ibm.smartcloud.compute.suppliers.IBMSmartCloudImageSupplier;
import org.jclouds.ibmdev.compute.suppliers.IBMDeveloperCloudLocationSupplier; import org.jclouds.ibm.smartcloud.compute.suppliers.IBMSmartCloudLocationSupplier;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudBindComputeSuppliersByClass extends BindComputeSuppliersByClass { public class IBMSmartCloudBindComputeSuppliersByClass extends BindComputeSuppliersByClass {
@Override @Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() { protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return IBMDeveloperCloudHardwareSupplier.class; return IBMSmartCloudHardwareSupplier.class;
} }
@Override @Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() { protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return IBMDeveloperCloudImageSupplier.class; return IBMSmartCloudImageSupplier.class;
} }
@Override @Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() { protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return IBMDeveloperCloudLocationSupplier.class; return IBMSmartCloudLocationSupplier.class;
} }
} }

View File

@ -16,9 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.config; package org.jclouds.ibm.smartcloud.compute.config;
import static org.jclouds.compute.domain.OsFamily.SUSE;
import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
@ -27,26 +25,26 @@ import org.jclouds.compute.internal.BaseComputeService;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Configures the {@link IBMDeveloperCloudComputeServiceContext}; requires * Configures the {@link IBMSmartCloudComputeServiceContext}; requires
* {@link BaseComputeService} bound. * {@link BaseComputeService} bound.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudComputeServiceContextModule extends BaseComputeServiceContextModule { public class IBMSmartCloudComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
install(new IBMDeveloperCloudComputeServiceDependenciesModule()); install(new IBMSmartCloudComputeServiceDependenciesModule());
install(new IBMDeveloperCloudBindComputeStrategiesByClass()); install(new IBMSmartCloudBindComputeStrategiesByClass());
install(new IBMDeveloperCloudBindComputeSuppliersByClass()); install(new IBMSmartCloudBindComputeSuppliersByClass());
super.configure(); super.configure();
} }
/** /**
* tested known configuration * cheapest image in most available datacenter
*/ */
@Override @Override
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(SUSE); return template.imageNameMatches("^SUSE Linux Enterprise Server 11 SP1 for x86.*").locationId("101");
} }
} }

View File

@ -16,8 +16,9 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.config; package org.jclouds.ibm.smartcloud.compute.config;
import java.security.SecureRandom;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -28,15 +29,20 @@ import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.ibmdev.IBMDeveloperCloudAsyncClient; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;
import org.jclouds.ibmdev.compute.functions.InstanceToNodeMetadata; import org.jclouds.ibm.smartcloud.IBMSmartCloudAsyncClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibm.smartcloud.compute.functions.InstanceToNodeMetadata;
import org.jclouds.ibm.smartcloud.compute.options.IBMSmartCloudTemplateOptions;
import org.jclouds.ibm.smartcloud.compute.strategy.CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -46,18 +52,35 @@ import com.google.inject.TypeLiteral;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudComputeServiceDependenciesModule extends AbstractModule { public class IBMSmartCloudComputeServiceDependenciesModule extends AbstractModule {
@Override @Override
protected void configure() { protected void configure() {
bind(TemplateOptions.class).to(IBMSmartCloudTemplateOptions.class);
bind(new TypeLiteral<Function<Instance, NodeMetadata>>() { bind(new TypeLiteral<Function<Instance, NodeMetadata>>() {
}).to(InstanceToNodeMetadata.class); }).to(InstanceToNodeMetadata.class);
bind(new TypeLiteral<ComputeServiceContext>() { bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient>>() { }).to(new TypeLiteral<ComputeServiceContextImpl<IBMSmartCloudClient, IBMSmartCloudAsyncClient>>() {
}).in(Scopes.SINGLETON); }).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient>>() { bind(new TypeLiteral<RestContext<IBMSmartCloudClient, IBMSmartCloudAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient>>() { }).to(new TypeLiteral<RestContextImpl<IBMSmartCloudClient, IBMSmartCloudAsyncClient>>() {
}).in(Scopes.SINGLETON); }).in(Scopes.SINGLETON);
bind(CreateNodesWithGroupEncodedIntoNameThenAddToSet.class).to(
CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet.class);
}
@Provides
@Singleton
Supplier<String> provideSuffix() {
return new Supplier<String>() {
final SecureRandom random = new SecureRandom();
@Override
public String get() {
return random.nextInt(100) + "";
}
};
} }
@Provides @Provides

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.functions; package org.jclouds.ibm.smartcloud.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
@ -35,14 +35,17 @@ import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.IP;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -52,19 +55,19 @@ public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata>
@VisibleForTesting @VisibleForTesting
public static final Map<Instance.Status, NodeState> instanceStatusToNodeState = ImmutableMap public static final Map<Instance.Status, NodeState> instanceStatusToNodeState = ImmutableMap
.<Instance.Status, NodeState> builder().put(Instance.Status.ACTIVE, NodeState.RUNNING)// .<Instance.Status, NodeState> builder().put(Instance.Status.ACTIVE, NodeState.RUNNING)//
.put(Instance.Status.STOPPED, NodeState.SUSPENDED)// .put(Instance.Status.STOPPED, NodeState.SUSPENDED)//
.put(Instance.Status.REMOVED, NodeState.TERMINATED)// .put(Instance.Status.REMOVED, NodeState.TERMINATED)//
.put(Instance.Status.DEPROVISIONING, NodeState.PENDING)// .put(Instance.Status.DEPROVISIONING, NodeState.PENDING)//
.put(Instance.Status.FAILED, NodeState.ERROR)// .put(Instance.Status.FAILED, NodeState.ERROR)//
.put(Instance.Status.NEW, NodeState.PENDING)// .put(Instance.Status.NEW, NodeState.PENDING)//
.put(Instance.Status.PROVISIONING, NodeState.PENDING)// .put(Instance.Status.PROVISIONING, NodeState.PENDING)//
.put(Instance.Status.REJECTED, NodeState.ERROR)// .put(Instance.Status.REJECTED, NodeState.ERROR)//
.put(Instance.Status.RESTARTING, NodeState.PENDING)// .put(Instance.Status.RESTARTING, NodeState.PENDING)//
.put(Instance.Status.STARTING, NodeState.PENDING)// .put(Instance.Status.STARTING, NodeState.PENDING)//
.put(Instance.Status.STOPPING, NodeState.PENDING)// .put(Instance.Status.STOPPING, NodeState.PENDING)//
.put(Instance.Status.DEPROVISION_PENDING, NodeState.PENDING)// .put(Instance.Status.DEPROVISION_PENDING, NodeState.PENDING)//
.put(Instance.Status.UNKNOWN, NodeState.UNRECOGNIZED).build(); .put(Instance.Status.UNKNOWN, NodeState.UNRECOGNIZED).build();
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final Map<Instance.Status, NodeState> instanceStateToNodeState; private final Map<Instance.Status, NodeState> instanceStateToNodeState;
@ -74,25 +77,36 @@ public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata>
@Inject @Inject
InstanceToNodeMetadata(Map<Instance.Status, NodeState> instanceStateToNodeState, InstanceToNodeMetadata(Map<Instance.Status, NodeState> instanceStateToNodeState,
Supplier<Map<String, ? extends Image>> images, @Named("CREDENTIALS") Map<String, String> credentialsMap, Supplier<Map<String, ? extends Image>> images, @Named("CREDENTIALS") Map<String, String> credentialsMap,
Supplier<Map<String, ? extends Location>> locations) { Supplier<Map<String, ? extends Location>> locations) {
this.instanceStateToNodeState = checkNotNull(instanceStateToNodeState, "instanceStateToNodeState"); this.instanceStateToNodeState = checkNotNull(instanceStateToNodeState, "instanceStateToNodeState");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
this.locations = checkNotNull(locations, "locations"); this.locations = checkNotNull(locations, "locations");
} }
private static Function<IP, String> ipFromIP = new Function<IP, String>() {
@Override
public String apply(IP arg0) {
return arg0 != null ? arg0.getIP() : null;
}
};
@Override @Override
public NodeMetadata apply(Instance from) { public NodeMetadata apply(Instance from) {
//TODO hardware // TODO hardware
String group = parseGroupFromName(from.getName()); String group = parseGroupFromName(from.getName());
Set<String> ipSet = from.getIp() != null ? ImmutableSet.of(from.getIp()) : ImmutableSet.<String> of(); String ip = ipFromIP.apply(from.getPrimaryIP());
Set<String> ipSet = ip != null ? ImmutableSet.of(ip) : ImmutableSet.<String> of();
Image image = images.get().get(from.getImageId()); Image image = images.get().get(from.getImageId());
String key = group != null ? credentialsMap.get(group) : null; String key = credentialsMap.get(from.getKeyName());
return new NodeMetadataBuilder().ids(from.getId() + "").name(from.getName()) return new NodeMetadataBuilder().ids(from.getId() + "").name(from.getName()).location(
.location(locations.get().get(image.getLocation())).group(group).imageId(from.getImageId()) locations.get().get(image.getLocation())).group(group).imageId(from.getImageId()).state(
.state(instanceStateToNodeState.get(from.getStatus())) instanceStateToNodeState.get(from.getStatus())).operatingSystem(
.operatingSystem(image != null ? image.getOperatingSystem() : null).publicAddresses(ipSet) image != null ? image.getOperatingSystem() : null).publicAddresses(ipSet).privateAddresses(
.credentials(new Credentials(image.getDefaultCredentials().identity, key)).build(); Iterables.filter(Iterables.transform(from.getSecondaryIPs(), ipFromIP), Predicates.notNull()))
.credentials(new Credentials(image.getDefaultCredentials().identity, key)).build();
} }
} }

View File

@ -0,0 +1,366 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.compute.options;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.Arrays;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.ibm.smartcloud.options.CreateInstanceOptions;
import org.jclouds.io.Payload;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.util.Preconditions2;
/**
* Contains options supported in the {@code ComputeService#runNode} operation on the
* "ibm.smartcloud" provider. <h2>
* Usage</h2> The recommended way to instantiate a IBMSmartCloudTemplateOptions object is to
* statically import IBMSmartCloudTemplateOptions.* and invoke a static creation method followed by
* an instance mutator (if needed):
* <p/>
* <code>
* import static org.jclouds.ibm.smartcloud.compute.options.IBMSmartCloudTemplateOptions.Builder.*;
* <p/>
* ComputeService client = // get connection
* templateBuilder.options(inboundPorts(22, 80, 8080, 443));
* Set<? extends NodeMetadata> set = client.runNodesWithTag(tag, 2, templateBuilder.build());
* <code>
*
* @author Adrian Cole
*/
public class IBMSmartCloudTemplateOptions extends TemplateOptions implements Cloneable {
@Override
public IBMSmartCloudTemplateOptions clone() {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
copyTo(options);
return options;
}
@Override
public void copyTo(TemplateOptions to) {
super.copyTo(to);
if (to instanceof IBMSmartCloudTemplateOptions) {
IBMSmartCloudTemplateOptions eTo = IBMSmartCloudTemplateOptions.class.cast(to);
if (getKeyPair() != null)
eTo.keyPair(getKeyPair());
if (!shouldAutomaticallyCreateKeyPair())
eTo.noKeyPair();
if (!isMiniEphemeral)
eTo.isMiniEphemeral(false);
}
}
private String keyPair = null;
private boolean noKeyPair;
private boolean isMiniEphemeral = true;
public static final IBMSmartCloudTemplateOptions NONE = new IBMSmartCloudTemplateOptions();
/**
* @see CreateInstanceOptions#isMiniEphemeral
*/
public IBMSmartCloudTemplateOptions isMiniEphemeral(boolean isMiniEphemeral) {
this.isMiniEphemeral = isMiniEphemeral;
return this;
}
/**
* Specifies the keypair used to run instances with
*/
public IBMSmartCloudTemplateOptions keyPair(String keyPair) {
checkNotNull(keyPair, "use noKeyPair option to request boot without a keypair");
checkState(!noKeyPair, "you cannot specify both options keyPair and noKeyPair");
Preconditions2.checkNotEmpty(keyPair, "keypair must be non-empty");
this.keyPair = keyPair;
return this;
}
/**
* Do not use a keypair on instances
*/
public IBMSmartCloudTemplateOptions noKeyPair() {
checkState(keyPair == null, "you cannot specify both options keyPair and noKeyPair");
this.noKeyPair = true;
return this;
}
public static class Builder {
/**
* @see IBMSmartCloudTemplateOptions#isMiniEphemeral
*/
public static IBMSmartCloudTemplateOptions isMiniEphemeral(boolean isMiniEphemeral) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return options.isMiniEphemeral(isMiniEphemeral);
}
/**
* @see IBMSmartCloudTemplateOptions#keyPair
*/
public static IBMSmartCloudTemplateOptions keyPair(String keyPair) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.keyPair(keyPair));
}
/**
* @see IBMSmartCloudTemplateOptions#noKeyPair
*/
public static IBMSmartCloudTemplateOptions noKeyPair() {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.noKeyPair());
}
// methods that only facilitate returning the correct object type
/**
* @see TemplateOptions#inboundPorts
*/
public static IBMSmartCloudTemplateOptions inboundPorts(int... ports) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.inboundPorts(ports));
}
/**
* @see TemplateOptions#port
*/
public static IBMSmartCloudTemplateOptions blockOnPort(int port, int seconds) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.blockOnPort(port, seconds));
}
/**
* @see TemplateOptions#runScript
*/
public static IBMSmartCloudTemplateOptions runScript(byte[] script) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.runScript(script));
}
/**
* @see TemplateOptions#installPrivateKey
*/
public static IBMSmartCloudTemplateOptions installPrivateKey(String rsaKey) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.installPrivateKey(rsaKey));
}
/**
* @see TemplateOptions#authorizePublicKey
*/
public static IBMSmartCloudTemplateOptions authorizePublicKey(String rsaKey) {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.authorizePublicKey(rsaKey));
}
/**
* @see TemplateOptions#withDetails
*/
public static IBMSmartCloudTemplateOptions withDetails() {
IBMSmartCloudTemplateOptions options = new IBMSmartCloudTemplateOptions();
return IBMSmartCloudTemplateOptions.class.cast(options.withMetadata());
}
}
// methods that only facilitate returning the correct object type
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions blockOnPort(int port, int seconds) {
return IBMSmartCloudTemplateOptions.class.cast(super.blockOnPort(port, seconds));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions inboundPorts(int... ports) {
return IBMSmartCloudTemplateOptions.class.cast(super.inboundPorts(ports));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions authorizePublicKey(String publicKey) {
return IBMSmartCloudTemplateOptions.class.cast(super.authorizePublicKey(publicKey));
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public IBMSmartCloudTemplateOptions authorizePublicKey(Payload publicKey) {
return IBMSmartCloudTemplateOptions.class.cast(super.authorizePublicKey(publicKey));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions installPrivateKey(String privateKey) {
return IBMSmartCloudTemplateOptions.class.cast(super.installPrivateKey(privateKey));
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public IBMSmartCloudTemplateOptions installPrivateKey(Payload privateKey) {
return IBMSmartCloudTemplateOptions.class.cast(super.installPrivateKey(privateKey));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions runScript(Payload script) {
return IBMSmartCloudTemplateOptions.class.cast(super.runScript(script));
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public IBMSmartCloudTemplateOptions runScript(byte[] script) {
return IBMSmartCloudTemplateOptions.class.cast(super.runScript(script));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions withMetadata() {
return IBMSmartCloudTemplateOptions.class.cast(super.withMetadata());
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions blockUntilRunning(boolean blockUntilRunning) {
return IBMSmartCloudTemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions dontAuthorizePublicKey() {
return IBMSmartCloudTemplateOptions.class.cast(super.dontAuthorizePublicKey());
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions nameTask(String name) {
return IBMSmartCloudTemplateOptions.class.cast(super.nameTask(name));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions runAsRoot(boolean runAsRoot) {
return IBMSmartCloudTemplateOptions.class.cast(super.runAsRoot(runAsRoot));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions runScript(Statement script) {
return IBMSmartCloudTemplateOptions.class.cast(super.runScript(script));
}
/**
* {@inheritDoc}
*/
@Override
public IBMSmartCloudTemplateOptions overrideCredentialsWith(Credentials overridingCredentials) {
return IBMSmartCloudTemplateOptions.class.cast(super.overrideCredentialsWith(overridingCredentials));
}
/**
* @return keyPair to use when running the instance or null, to generate a keypair.
*/
public String getKeyPair() {
return keyPair;
}
/**
* @return true (default) if we are supposed to use a keypair
*/
public boolean shouldAutomaticallyCreateKeyPair() {
return !noKeyPair;
}
/**
* @see CreateInstanceOptions#isMiniEphemeral
*/
public boolean isMiniEphemeral() {
return isMiniEphemeral;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((keyPair == null) ? 0 : keyPair.hashCode());
result = prime * result + (noKeyPair ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
IBMSmartCloudTemplateOptions other = (IBMSmartCloudTemplateOptions) obj;
if (keyPair == null) {
if (other.keyPair != null)
return false;
} else if (!keyPair.equals(other.keyPair))
return false;
if (noKeyPair != other.noKeyPair)
return false;
return true;
}
@Override
public String toString() {
return "[keyPair=" + keyPair + ", noKeyPair=" + noKeyPair + ", isMiniEphemeral=" + isMiniEphemeral
+ ", inboundPorts=" + Arrays.toString(inboundPorts) + ", privateKey=" + (privateKey != null)
+ ", publicKey=" + (publicKey != null) + ", runScript=" + (script != null) + ", port:seconds=" + port
+ ":" + seconds + ", metadata/details: " + includeMetadata + "]";
}
}

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.strategy; package org.jclouds.ibm.smartcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -25,6 +25,7 @@ import java.util.Set;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -33,21 +34,34 @@ import org.jclouds.Constants;
import org.jclouds.compute.config.CustomizationResponse; import org.jclouds.compute.config.CustomizationResponse;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;
import org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap; import org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet; import org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibm.smartcloud.compute.options.IBMSmartCloudTemplateOptions;
import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet extends CreateNodesWithGroupEncodedIntoNameThenAddToSet { public class CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet extends
private final IBMDeveloperCloudClient client; CreateNodesWithGroupEncodedIntoNameThenAddToSet {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final IBMSmartCloudClient client;
private final Map<String, String> credentialsMap; private final Map<String, String> credentialsMap;
private final Supplier<String> randomSuffix;
@Inject @Inject
protected CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet( protected CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet(
@ -56,29 +70,45 @@ public class CreateKeyCreateNodesWithGroupEncodedIntoNameThenAddToSet extends Cr
@Named("NAMING_CONVENTION") String nodeNamingConvention, @Named("NAMING_CONVENTION") String nodeNamingConvention,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor,
CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory, CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,
IBMDeveloperCloudClient client, @Named("CREDENTIALS") Map<String, String> credentialsMap) { IBMSmartCloudClient client, @Named("CREDENTIALS") Map<String, String> credentialsMap,
Supplier<String> randomSuffix) {
super(addNodeWithTagStrategy, listNodesStrategy, nodeNamingConvention, executor, super(addNodeWithTagStrategy, listNodesStrategy, nodeNamingConvention, executor,
customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory); customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
this.randomSuffix = checkNotNull(randomSuffix, "randomSuffix");
} }
@Override @Override
public Map<?, Future<Void>> execute(String group, int count, Template template, Set<NodeMetadata> goodNodes, public Map<?, Future<Void>> execute(String group, int count, Template template, Set<NodeMetadata> goodNodes,
Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses) { Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {
String keyAsText = template.getOptions().getPublicKey(); IBMSmartCloudTemplateOptions options = template.getOptions().as(IBMSmartCloudTemplateOptions.class);
if (keyAsText != null) { if (options.shouldAutomaticallyCreateKeyPair() && options.getKeyPair() == null) {
template.getOptions().dontAuthorizePublicKey(); Key key = createNewKey(group);
try { options.keyPair(key.getName());
client.addPublicKey(group, keyAsText); credentialsMap.put(key.getName(), key.getKeyMaterial());
} catch (IllegalStateException e) {
// must not have been found
client.updatePublicKey(group, keyAsText);
}
} else {
credentialsMap.put(group, client.generateKeyPair(group).getKeyMaterial());
} }
return super.execute(group, count, template, goodNodes, badNodes, customizationResponses); return super.execute(group, count, template, goodNodes, badNodes, customizationResponses);
} }
@VisibleForTesting
Key createNewKey(String group) {
checkNotNull(group, "group");
logger.debug(">> creating key group(%s)", group);
Key key = null;
while (key == null) {
try {
key = client.generateKeyPair(getNextName(group));
logger.debug("<< created key(%s)", key.getName());
} catch (IllegalStateException e) {
}
}
return key;
}
private String getNextName(String group) {
return String.format("jclouds#%s#%s", group, randomSuffix.get());
}
} }

View File

@ -16,10 +16,10 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.strategy; package org.jclouds.ibm.smartcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.authorizePublicKey; import static org.jclouds.ibm.smartcloud.options.CreateInstanceOptions.Builder.authorizePublicKey;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -27,8 +27,10 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.compute.options.IBMSmartCloudTemplateOptions;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibm.smartcloud.options.CreateInstanceOptions;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -36,22 +38,25 @@ import com.google.common.base.Function;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGroupEncodedIntoName { public class IBMSmartCloudCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGroupEncodedIntoName {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata; private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject @Inject
protected IBMDeveloperCloudCreateNodeWithGroupEncodedIntoName(IBMDeveloperCloudClient client, protected IBMSmartCloudCreateNodeWithGroupEncodedIntoName(IBMSmartCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) { Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.instanceToNodeMetadata = checkNotNull(instanceToNodeMetadata, "instanceToNodeMetadata"); this.instanceToNodeMetadata = checkNotNull(instanceToNodeMetadata, "instanceToNodeMetadata");
} }
@Override @Override
public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) { public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
IBMSmartCloudTemplateOptions templateOptions = template.getOptions().as(IBMSmartCloudTemplateOptions.class);
CreateInstanceOptions options = authorizePublicKey(templateOptions.getKeyPair()).isMiniEphemeral(
IBMSmartCloudTemplateOptions.class.cast(template.getOptions()).isMiniEphemeral());
Instance instance = client.createInstanceInLocation(template.getLocation().getId(), name, template.getImage() Instance instance = client.createInstanceInLocation(template.getLocation().getId(), name, template.getImage()
.getProviderId(), template.getHardware().getProviderId(), authorizePublicKey(group)); .getProviderId(), template.getHardware().getProviderId(), options);
return instanceToNodeMetadata.apply(client.getInstance(instance.getId())); return instanceToNodeMetadata.apply(instance);
} }
} }

View File

@ -0,0 +1,74 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibm.smartcloud.predicates.InstanceActiveOrFailed;
import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMSmartCloudDestroyNodeStrategy implements DestroyNodeStrategy {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final IBMSmartCloudClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected IBMSmartCloudDestroyNodeStrategy(IBMSmartCloudClient client, GetNodeMetadataStrategy getNode) {
this.client = checkNotNull(client, "client");
this.getNode = checkNotNull(getNode, "getNode");
}
@Override
public NodeMetadata destroyNode(String id) {
Instance instance = client.getInstance(id);
if (instance != null && instance.getStatus() != Instance.Status.DEPROVISIONING
&& instance.getStatus() != Instance.Status.DEPROVISION_PENDING) {
// often it takes 8 minutes to finish provisioning a suse host
int timeout = (instance.getStatus() == Instance.Status.NEW || instance.getStatus() == Instance.Status.PROVISIONING) ? 600
: 30;
logger.debug(">> awaiting up to %s seconds for instance %s to be ready for delete", timeout, id);
boolean ready = new RetryablePredicate<Instance>(new InstanceActiveOrFailed(client), timeout, 2,
TimeUnit.SECONDS).apply(instance);
logger.debug(">> instance state is %sready, deleting", ready ? "" : "not ", id);
client.deleteInstance(instance.getId());
}
return instance != null ? getNode.getNode(id) : null;
}
}

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.strategy; package org.jclouds.ibm.smartcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -25,8 +25,8 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -34,12 +34,12 @@ import com.google.common.base.Function;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudGetNodeMetadataStrategy implements GetNodeMetadataStrategy { public class IBMSmartCloudGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata; private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject @Inject
protected IBMDeveloperCloudGetNodeMetadataStrategy(IBMDeveloperCloudClient client, protected IBMSmartCloudGetNodeMetadataStrategy(IBMSmartCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) { Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = client; this.client = client;
this.instanceToNodeMetadata = instanceToNodeMetadata; this.instanceToNodeMetadata = instanceToNodeMetadata;

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.strategy; package org.jclouds.ibm.smartcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -28,19 +28,19 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy; import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStrategy, ResumeNodeStrategy { public class IBMSmartCloudLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStrategy, ResumeNodeStrategy {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
private final GetNodeMetadataStrategy getNode; private final GetNodeMetadataStrategy getNode;
@Inject @Inject
protected IBMDeveloperCloudLifeCycleStrategy(IBMDeveloperCloudClient client, GetNodeMetadataStrategy getNode) { protected IBMSmartCloudLifeCycleStrategy(IBMSmartCloudClient client, GetNodeMetadataStrategy getNode) {
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.getNode = checkNotNull(getNode, "getNode"); this.getNode = checkNotNull(getNode, "getNode");
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.strategy; package org.jclouds.ibm.smartcloud.compute.strategy;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -25,8 +25,8 @@ import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -36,12 +36,12 @@ import com.google.common.collect.Iterables;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudListNodesStrategy implements ListNodesStrategy { public class IBMSmartCloudListNodesStrategy implements ListNodesStrategy {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata; private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject @Inject
protected IBMDeveloperCloudListNodesStrategy(IBMDeveloperCloudClient client, protected IBMSmartCloudListNodesStrategy(IBMSmartCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) { Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = client; this.client = client;
this.instanceToNodeMetadata = instanceToNodeMetadata; this.instanceToNodeMetadata = instanceToNodeMetadata;

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.suppliers; package org.jclouds.ibm.smartcloud.compute.suppliers;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -31,10 +31,11 @@ import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.InstanceType; import org.jclouds.ibm.smartcloud.domain.InstanceType;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
@ -45,16 +46,16 @@ import com.google.common.collect.Sets;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudHardwareSupplier implements Supplier<Set<? extends Hardware>> { public class IBMSmartCloudHardwareSupplier implements Supplier<Set<? extends Hardware>> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final IBMDeveloperCloudClient sync; private final IBMSmartCloudClient sync;
private final Supplier<Map<String, ? extends Location>> locations; private final Supplier<Map<String, ? extends Location>> locations;
@Inject @Inject
IBMDeveloperCloudHardwareSupplier(IBMDeveloperCloudClient sync, Supplier<Map<String, ? extends Location>> locations) { IBMSmartCloudHardwareSupplier(IBMSmartCloudClient sync, Supplier<Map<String, ? extends Location>> locations) {
this.sync = sync; this.sync = sync;
this.locations = locations; this.locations = locations;
} }
@ -63,16 +64,17 @@ public class IBMDeveloperCloudHardwareSupplier implements Supplier<Set<? extends
public Set<? extends Hardware> get() { public Set<? extends Hardware> get() {
final Set<Hardware> hardware = Sets.newHashSet(); final Set<Hardware> hardware = Sets.newHashSet();
logger.debug(">> providing hardware"); logger.debug(">> providing hardware");
for (org.jclouds.ibmdev.domain.Image image : sync.listImages()) { for (org.jclouds.ibm.smartcloud.domain.Image image : sync.listImages()) {
for (InstanceType instanceType : image.getSupportedInstanceTypes()) { for (InstanceType instanceType : image.getSupportedInstanceTypes()) {
hardware.add(new HardwareBuilder() hardware.add(new HardwareBuilder()
.id(image.getId() + "/" + instanceType.getId()) .id(image.getId() + "/" + instanceType.getId())
.providerId(image.getId()) .providerId(instanceType.getId())
.name(instanceType.getLabel()) .name(instanceType.getLabel())
.location(locations.get().get(image.getLocation())) .location(locations.get().get(image.getLocation()))
.uri(image.getManifest()) .uri(image.getManifest())
.processors(ImmutableList.of(new Processor((instanceType.getPrice().getRate() * 100), 1.0))) .processors(ImmutableList.of(new Processor((instanceType.getPrice().getRate() * 100), 1.0)))
.ram((int) instanceType.getPrice().getRate() * 1024) .ram((int) instanceType.getPrice().getRate() * 1024)
.supportsImage(ImagePredicates.idEquals(image.getId()))
.volumes( .volumes(
ImmutableList.<Volume> of(new VolumeImpl((float) (instanceType.getPrice().getRate() * 100d), ImmutableList.<Volume> of(new VolumeImpl((float) (instanceType.getPrice().getRate() * 100d),
true, true))).build()); true, true))).build());

View File

@ -16,7 +16,9 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.suppliers; package org.jclouds.ibm.smartcloud.compute.suppliers;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -28,32 +30,34 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystemBuilder; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibm.smartcloud.domain.Image.Architecture;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudImageSupplier implements Supplier<Set<? extends Image>> { public class IBMSmartCloudImageSupplier implements Supplier<Set<? extends Image>> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final IBMDeveloperCloudClient sync; private final IBMSmartCloudClient sync;
private final Supplier<Map<String, ? extends Location>> locations; private final Supplier<Map<String, ? extends Location>> locations;
@Inject @Inject
IBMDeveloperCloudImageSupplier(final IBMDeveloperCloudClient sync, IBMSmartCloudImageSupplier(final IBMSmartCloudClient sync, Supplier<Map<String, ? extends Location>> locations) {
Supplier<Map<String, ? extends Location>> locations) {
this.sync = sync; this.sync = sync;
this.locations = locations; this.locations = locations;
} }
@ -63,21 +67,31 @@ public class IBMDeveloperCloudImageSupplier implements Supplier<Set<? extends Im
final Set<Image> images = Sets.newHashSet(); final Set<Image> images = Sets.newHashSet();
logger.debug(">> providing images"); logger.debug(">> providing images");
for (org.jclouds.ibmdev.domain.Image image : sync.listImages()) { for (org.jclouds.ibm.smartcloud.domain.Image image : sync.listImages()) {
// TODO parse correct OS
OperatingSystem.Builder osBuilder = OperatingSystem.builder();
Iterable<String> osVersion = Splitter.on('/').split(checkNotNull(image.getPlatform(), "platform"));
osBuilder.version(Iterables.get(osVersion, 1));
osBuilder.name(image.getPlatform());
osBuilder.description(image.getPlatform());
if ("Red Hat Enterprise Linux".equals(Iterables.get(osVersion, 0)))
osBuilder.family(OsFamily.RHEL);
else if ("SUSE Linux Enterprise Server".equals(Iterables.get(osVersion, 0)))
osBuilder.family(OsFamily.SUSE);
else if ("Windows".equals(Iterables.get(osVersion, 0)))
osBuilder.family(OsFamily.WINDOWS);
else
osBuilder.family(OsFamily.UNRECOGNIZED);
osBuilder.arch(image.getArchitecture().toString());
osBuilder.is64Bit(image.getArchitecture() == Architecture.X86_64);
// TODO manifest fails to parse due to encoding issues in the path // TODO manifest fails to parse due to encoding issues in the path
// TODO get correct default credentials // TODO get correct default credentials
// http://www-180.ibm.com/cloud/enterprise/beta/ram/community/_rlvid.jsp.faces?_rap=pc_DiscussionForum.doDiscussionTopic&_rvip=/community/discussionForum.jsp&guid={DA689AEE-783C-6FE7-6F9F-DFEE9763F806}&v=1&submission=false&fid=1068&tid=1527 // http://www-180.ibm.com/cloud/enterprise/beta/ram/community/_rlvid.jsp.faces?_rap=pc_DiscussionForum.doDiscussionTopic&_rvip=/community/discussionForum.jsp&guid={DA689AEE-783C-6FE7-6F9F-DFEE9763F806}&v=1&submission=false&fid=1068&tid=1527
images.add(new ImageBuilder() images.add(new ImageBuilder().ids(image.getId()).name(image.getName()).location(
.ids(image.getId()) locations.get().get(image.getLocation())).operatingSystem(osBuilder.build()).description(
.name(image.getName()) image.getName()).version(image.getCreatedTime().getTime() + "").defaultCredentials(
.location(locations.get().get(image.getLocation())) new Credentials("idcuser", null)).build());
.operatingSystem(
new OperatingSystemBuilder()
.family((image.getPlatform().indexOf("Red Hat") != -1) ? OsFamily.RHEL : OsFamily.SUSE)
.arch(image.getPlatform()).is64Bit(image.getPlatform().indexOf("32") == -1).build())
.description(image.getName()).version(image.getCreatedTime().getTime() + "")
.defaultCredentials(new Credentials("idcuser", null)).build());
} }
logger.debug("<< images(%d)", images.size()); logger.debug("<< images(%d)", images.size());

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.suppliers; package org.jclouds.ibm.smartcloud.compute.suppliers;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -30,7 +30,8 @@ import javax.inject.Singleton;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibm.smartcloud.domain.Location.State;
import org.jclouds.location.Iso3166; import org.jclouds.location.Iso3166;
import org.jclouds.location.Provider; import org.jclouds.location.Provider;
import org.jclouds.location.suppliers.JustProvider; import org.jclouds.location.suppliers.JustProvider;
@ -44,14 +45,14 @@ import com.google.common.collect.ImmutableSet.Builder;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudLocationSupplier extends JustProvider { public class IBMSmartCloudLocationSupplier extends JustProvider {
private final IBMDeveloperCloudClient sync; private final IBMSmartCloudClient sync;
private final Map<String, Set<String>> isoCodesById; private final Map<String, Set<String>> isoCodesById;
@Inject @Inject
IBMDeveloperCloudLocationSupplier(@Iso3166 Set<String> isoCodes, @Provider String providerName, IBMSmartCloudLocationSupplier(@Iso3166 Set<String> isoCodes, @Provider String providerName, @Provider URI endpoint,
@Provider URI endpoint, IBMDeveloperCloudClient sync, @Iso3166 Map<String, Set<String>> isoCodesById) { IBMSmartCloudClient sync, @Iso3166 Map<String, Set<String>> isoCodesById) {
super(isoCodes, providerName, endpoint); super(isoCodes, providerName, endpoint);
this.sync = checkNotNull(sync, "sync"); this.sync = checkNotNull(sync, "sync");
this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById"); this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById");
@ -60,17 +61,19 @@ public class IBMDeveloperCloudLocationSupplier extends JustProvider {
@Override @Override
public Set<? extends Location> get() { public Set<? extends Location> get() {
Builder<Location> locations = ImmutableSet.builder(); Builder<Location> locations = ImmutableSet.builder();
Set<? extends org.jclouds.ibmdev.domain.Location> list = sync.listLocations(); Set<? extends org.jclouds.ibm.smartcloud.domain.Location> list = sync.listLocations();
Location provider = Iterables.getOnlyElement(super.get()); Location provider = Iterables.getOnlyElement(super.get());
if (list.size() == 0) if (list.size() == 0)
locations.add(provider); locations.add(provider);
else else
for (org.jclouds.ibmdev.domain.Location from : list) { for (org.jclouds.ibm.smartcloud.domain.Location from : list) {
LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(from.getId() + "") if (from.getState() != State.OFFLINE) {
.description(from.getName()).parent(provider); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(from.getId() + "")
if (isoCodesById.containsKey(from.getId() + "")) .description(from.getName()).parent(provider);
builder.iso3166Codes(isoCodesById.get(from.getId() + "")); if (isoCodesById.containsKey(from.getId() + ""))
locations.add(builder.build()); builder.iso3166Codes(isoCodesById.get(from.getId() + ""));
locations.add(builder.build());
}
} }
return locations.build(); return locations.build();
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.config; package org.jclouds.ibm.smartcloud.config;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.URI; import java.net.URI;
@ -41,7 +41,7 @@ import com.google.inject.Provides;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudParserModule extends AbstractModule { public class IBMSmartCloudParserModule extends AbstractModule {
@Singleton @Singleton
public static class CurlyBraceCapableURIAdapter implements JsonDeserializer<URI> { public static class CurlyBraceCapableURIAdapter implements JsonDeserializer<URI> {
@Override @Override

View File

@ -16,46 +16,46 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.config; package org.jclouds.ibm.smartcloud.config;
import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.HttpErrorHandler;
import org.jclouds.http.RequiresHttp; import org.jclouds.http.RequiresHttp;
import org.jclouds.http.annotation.ClientError; import org.jclouds.http.annotation.ClientError;
import org.jclouds.http.annotation.Redirection; import org.jclouds.http.annotation.Redirection;
import org.jclouds.http.annotation.ServerError; import org.jclouds.http.annotation.ServerError;
import org.jclouds.ibmdev.IBMDeveloperCloudAsyncClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudAsyncClient;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.handlers.IBMDeveloperCloudErrorHandler; import org.jclouds.ibm.smartcloud.handlers.IBMSmartCloudErrorHandler;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.config.RestClientModule; import org.jclouds.rest.config.RestClientModule;
/** /**
* Configures the IBMDeveloperCloud connection. * Configures the IBMSmartCloud connection.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@RequiresHttp @RequiresHttp
@ConfiguresRestClient @ConfiguresRestClient
public class IBMDeveloperCloudRestClientModule extends public class IBMSmartCloudRestClientModule extends
RestClientModule<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> { RestClientModule<IBMSmartCloudClient, IBMSmartCloudAsyncClient> {
public IBMDeveloperCloudRestClientModule() { public IBMSmartCloudRestClientModule() {
super(IBMDeveloperCloudClient.class, IBMDeveloperCloudAsyncClient.class); super(IBMSmartCloudClient.class, IBMSmartCloudAsyncClient.class);
} }
@Override @Override
protected void bindErrorHandlers() { protected void bindErrorHandlers() {
bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to( bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(
IBMDeveloperCloudErrorHandler.class); IBMSmartCloudErrorHandler.class);
bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to( bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(
IBMDeveloperCloudErrorHandler.class); IBMSmartCloudErrorHandler.class);
bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to( bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(
IBMDeveloperCloudErrorHandler.class); IBMSmartCloudErrorHandler.class);
} }
@Override @Override
protected void configure() { protected void configure() {
install(new IBMDeveloperCloudParserModule()); install(new IBMSmartCloudParserModule());
super.configure(); super.configure();
} }
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -26,30 +26,30 @@ import javax.annotation.Nullable;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Address { public class Address implements Comparable<Address> {
public static enum State { public static enum State {
NEW, ALLOCATING, FREE, ATTACHED, RELEASING, RELEASED, FAILED, RELEASE_PENDING; NEW, ALLOCATING, FREE, ATTACHED, RELEASING, RELEASED, FAILED, RELEASE_PENDING;
public static State fromValue(int v) { public static State fromValue(int v) {
switch (v) { switch (v) {
case 0: case 0:
return NEW; return NEW;
case 1: case 1:
return ALLOCATING; return ALLOCATING;
case 2: case 2:
return FREE; return FREE;
case 3: case 3:
return ATTACHED; return ATTACHED;
case 4: case 4:
return RELEASING; return RELEASING;
case 5: case 5:
return RELEASED; return RELEASED;
case 6: case 6:
return FAILED; return FAILED;
case 7: case 7:
return RELEASE_PENDING; return RELEASE_PENDING;
default: default:
throw new IllegalArgumentException("invalid state:" + v); throw new IllegalArgumentException("invalid state:" + v);
} }
} }
} }
@ -69,7 +69,7 @@ public class Address {
this.instanceId = instanceId; this.instanceId = instanceId;
} }
public Address() { Address() {
} }
@ -77,42 +77,22 @@ public class Address {
return State.fromValue(state); return State.fromValue(state);
} }
public void setState(int state) {
this.state = state;
}
public String getLocation() { public String getLocation() {
return location; return location;
} }
public void setLocation(String location) { public String getIP() {
this.location = location; return "".equals(ip.trim()) ? null : ip;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
} }
public String getId() { public String getId() {
return id; return id;
} }
public void setId(String id) {
this.id = id;
}
public String getInstanceId() { public String getInstanceId() {
return instanceId; return instanceId;
} }
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
@ -159,7 +139,11 @@ public class Address {
@Override @Override
public String toString() { public String toString() {
return "[id=" + id + ", ip=" + ip + ", location=" + location + ", state=" + getState() + ", instanceId=" return "[id=" + id + ", ip=" + ip + ", location=" + location + ", state=" + getState() + ", instanceId="
+ instanceId + "]"; + instanceId + "]";
} }
@Override
public int compareTo(Address arg0) {
return id.compareTo(arg0.getId());
}
} }

View File

@ -0,0 +1,127 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
/**
*
*
* @author Adrian Cole
*/
public class IP {
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String ip;
private String hostname;
private int type;
public Builder ip(String ip) {
this.ip = ip;
return this;
}
public Builder hostname(String hostname) {
this.hostname = hostname;
return this;
}
public Builder type(int type) {
this.type = type;
return this;
}
public IP build() {
return new IP(ip, hostname, type);
}
}
private String ip;
private String hostname;
@Beta
private int type;
IP() {
}
public IP(String ip, String hostname, int type) {
this.ip = checkNotNull(ip, "ip");
this.hostname = checkNotNull(hostname, "hostname");
this.type = type;
}
// TODO custom parser to do this once
public String getHostname() {
return "".equals(hostname.trim()) ? null : hostname;
}
public String getIP() {
return "".equals(ip.trim()) ? null : ip;
}
public int getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((hostname == null) ? 0 : hostname.hashCode());
result = prime * result + ((ip == null) ? 0 : ip.hashCode());
result = prime * result + type;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IP other = (IP) obj;
if (hostname == null) {
if (other.hostname != null)
return false;
} else if (!hostname.equals(other.hostname))
return false;
if (ip == null) {
if (other.ip != null)
return false;
} else if (!ip.equals(other.ip))
return false;
if (type != other.type)
return false;
return true;
}
@Override
public String toString() {
return String.format("[hostname=%s, ip=%s, type=%s]", hostname, ip, type);
}
}

View File

@ -0,0 +1,221 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.domain;
import java.net.URI;
import java.util.Date;
import java.util.Set;
import java.util.SortedSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
/**
*
* The current state of the image.
*
* @author Adrian Cole
*/
public class Image implements Comparable<Image> {
public static enum State {
NEW, AVAILABLE, UNAVAILABLE, DELETED, CAPTURING, UNRECOGNIZED;
public static State fromValue(String v) {
switch (Integer.parseInt(v)) {
case 0:
return NEW;
case 1:
return AVAILABLE;
case 2:
return UNAVAILABLE;
case 3:
return DELETED;
case 4:
return CAPTURING;
default:
return UNRECOGNIZED;
}
}
}
public static enum Visibility {
PUBLIC,
SHARED,
PRIVATE;
}
public static enum Architecture {
I386, X86_64, UNRECOGNIZED;
public String value() {
return name().toLowerCase();
}
public static Architecture fromValue(String v) {
try {
return valueOf(v.toUpperCase());
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}
private String name;
private URI manifest;
private State state;
private Visibility visibility;
private String owner;
private String platform;
private Architecture architecture;
private Date createdTime;
private String location;
// for testing to be the same order each time
private SortedSet<InstanceType> supportedInstanceTypes = Sets.newTreeSet();
private SortedSet<String> productCodes = Sets.newTreeSet();
private URI documentation;
private String id;
private String description;
Image() {
}
public Image(String name, URI manifest, State state, Visibility visibility, String owner, String platform,
Architecture architecture, Date createdTime, String location, Set<InstanceType> supportedInstanceTypes,
Set<String> productCodes, URI documentation, String id, String description) {
this.name = name;
this.manifest = manifest;
this.state = state;
this.visibility = visibility;
this.owner = owner;
this.platform = platform;
this.architecture = architecture;
this.createdTime = createdTime;
this.location = location;
this.supportedInstanceTypes = ImmutableSortedSet.copyOf(supportedInstanceTypes);
this.productCodes = ImmutableSortedSet.copyOf(productCodes);
this.documentation = documentation;
this.id = id;
this.description = description;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((location == null) ? 0 : location.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Image other = (Image) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
return true;
}
@Override
public String toString() {
return String
.format(
"[id=%s, name=%s, architecture=%s, createdTime=%s, description=%s, documentation=%s, location=%s, manifest=%s, owner=%s, platform=%s, productCodes=%s, state=%s, supportedInstanceTypes=%s, visibility=%s]",
id, name, architecture, createdTime, description, documentation, location, manifest, owner,
platform, productCodes, state, supportedInstanceTypes, visibility);
}
public String getName() {
return name;
}
public URI getManifest() {
return manifest;
}
public State getState() {
return state;
}
public Visibility getVisibility() {
return visibility;
}
public String getOwner() {
return owner;
}
public String getPlatform() {
return platform;
}
public Architecture getArchitecture() {
return architecture;
}
public Date getCreatedTime() {
return createdTime;
}
public String getLocation() {
return location;
}
public Set<InstanceType> getSupportedInstanceTypes() {
return supportedInstanceTypes;
}
public Set<String> getProductCodes() {
return productCodes;
}
public URI getDocumentation() {
return documentation;
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
@Override
public int compareTo(Image arg0) {
return id.compareTo(arg0.getId());
}
}

View File

@ -0,0 +1,449 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Date;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.gson.annotations.SerializedName;
/**
*
* The current state of the instance.
*
* @author Adrian Cole
*/
public class Instance implements Comparable<Instance> {
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Date launchTime;
private Set<Software> software = Sets.newLinkedHashSet();
private IP primaryIP;
private Set<IP> secondaryIPs = Sets.newLinkedHashSet();
private String requestId;
private String keyName;
private String name;
private String instanceType;
private Status status;
private String owner;
private String location;
private String imageId;
private Set<String> productCodes = Sets.newLinkedHashSet();
private String requestName;
private String id;
private Date expirationTime;
private Vlan vlan;
private int diskSize;
private boolean rootOnly;
private String antiCollocationInstance;
public Builder launchTime(Date launchTime) {
this.launchTime = launchTime;
return this;
}
public Builder software(Iterable<Software> software) {
this.software = ImmutableSet.<Software> copyOf(checkNotNull(software, "software"));
return this;
}
public Builder primaryIP(IP primaryIP) {
this.primaryIP = primaryIP;
return this;
}
public Builder secondaryIPs(Iterable<IP> secondaryIPs) {
this.secondaryIPs = ImmutableSet.<IP> copyOf(checkNotNull(secondaryIPs, "secondaryIPs"));
return this;
}
public Builder requestId(String requestId) {
this.requestId = requestId;
return this;
}
public Builder keyName(String keyName) {
this.keyName = keyName;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder instanceType(String instanceType) {
this.instanceType = instanceType;
return this;
}
public Builder status(Status status) {
this.status = status;
return this;
}
public Builder owner(String owner) {
this.owner = owner;
return this;
}
public Builder location(String location) {
this.location = location;
return this;
}
public Builder imageId(String imageId) {
this.imageId = imageId;
return this;
}
public Builder productCodes(Iterable<String> productCodes) {
this.productCodes = ImmutableSet.<String> copyOf(checkNotNull(productCodes, "productCodes"));
return this;
}
public Builder requestName(String requestName) {
this.requestName = requestName;
return this;
}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder expirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
return this;
}
public Builder vlan(Vlan vlan) {
this.vlan = vlan;
return this;
}
public Builder diskSize(int diskSize) {
this.diskSize = diskSize;
return this;
}
public Builder rootOnly(boolean rootOnly) {
this.rootOnly = rootOnly;
return this;
}
public Builder antiCollocationInstance(String antiCollocationInstance) {
this.antiCollocationInstance = antiCollocationInstance;
return this;
}
public Instance build() {
return new Instance(launchTime, software, primaryIP, secondaryIPs, requestId, keyName, name, instanceType,
status, owner, location, imageId, productCodes, requestName, id, expirationTime, vlan, diskSize,
rootOnly, antiCollocationInstance);
}
}
public static enum Status {
NEW, PROVISIONING, FAILED, REMOVED, REJECTED, ACTIVE, UNKNOWN, DEPROVISIONING, RESTARTING, STARTING, STOPPING, STOPPED, DEPROVISION_PENDING, UNRECOGNIZED;
public static Status fromValue(String v) {
switch (Integer.parseInt(v)) {
case 0:
return NEW;
case 1:
return PROVISIONING;
case 2:
return FAILED;
case 3:
return REMOVED;
case 4:
return REJECTED;
case 5:
return ACTIVE;
case 6:
return UNKNOWN;
case 7:
return DEPROVISIONING;
case 8:
return RESTARTING;
case 9:
return STARTING;
case 10:
return STOPPING;
case 11:
return STOPPED;
case 12:
return DEPROVISION_PENDING;
default:
return UNRECOGNIZED;
}
}
}
public static class Software {
private String version;
private String type;
private String name;
public Software(String name, String type, String version) {
this.version = version;
this.type = type;
this.name = name;
}
public Software() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Software other = (Software) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
public String getVersion() {
return version;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "[name=" + name + ", type=" + type + ", version=" + version + "]";
}
}
private Date launchTime;
private Set<Software> software = Sets.newLinkedHashSet();
private IP primaryIP;
@SerializedName("secondaryIP")
private Set<IP> secondaryIPs = Sets.newLinkedHashSet();
private String requestId;
private String keyName;
private String name;
private String instanceType;
private Status status;
private String owner;
private String location;
private String imageId;
private Set<String> productCodes = Sets.newLinkedHashSet();
private String requestName;
private String id;
private Date expirationTime;
private Vlan vlan;
private int diskSize;
@SerializedName("root-only")
private boolean rootOnly;
private String antiCollocationInstance;
Instance() {
}
public Instance(Date launchTime, Iterable<Software> software, IP primaryIP, Iterable<IP> secondaryIPs,
String requestId, String keyName, String name, String instanceType, Status status, String owner,
String location, String imageId, Iterable<String> productCodes, String requestName, String id,
Date expirationTime, Vlan vlan, int diskSize, boolean rootOnly, String antiCollocationInstance) {
this.launchTime = launchTime;
this.software = ImmutableSet.copyOf(software);
this.primaryIP = primaryIP;
this.secondaryIPs = ImmutableSet.copyOf(secondaryIPs);
this.requestId = requestId;
this.keyName = keyName;
this.name = name;
this.instanceType = instanceType;
this.status = status;
this.owner = owner;
this.location = location;
this.imageId = imageId;
this.productCodes = ImmutableSet.copyOf(productCodes);
this.requestName = requestName;
this.id = id;
this.expirationTime = expirationTime;
this.vlan = vlan;
this.diskSize = diskSize;
this.rootOnly = rootOnly;
this.antiCollocationInstance = antiCollocationInstance;
}
public Date getLaunchTime() {
return launchTime;
}
public Set<Software> getSoftware() {
return software;
}
public IP getPrimaryIP() {
return primaryIP;
}
public Set<IP> getSecondaryIPs() {
return secondaryIPs;
}
public String getRequestId() {
return requestId;
}
public String getKeyName() {
return keyName;
}
public String getName() {
return name;
}
public String getInstanceType() {
return instanceType;
}
public Status getStatus() {
return status;
}
public String getOwner() {
return owner;
}
public String getLocation() {
return location;
}
public String getImageId() {
return imageId;
}
public Set<String> getProductCodes() {
return productCodes;
}
public String getRequestName() {
return requestName;
}
public String getId() {
return id;
}
public Date getExpirationTime() {
return expirationTime;
}
public Vlan getVlan() {
return vlan;
}
public int getDiskSize() {
return diskSize;
}
public boolean isRootOnly() {
return rootOnly;
}
public String getAntiCollocationInstance() {
return antiCollocationInstance;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Instance other = (Instance) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return String
.format(
"[id=%s, instanceType=%s, owner=%s, name=%s, location=%s, status=%s, imageId=%s, primaryIP=%s, secondaryIPs=%s, diskSize=%s, keyName=%s, launchTime=%s, rootOnly=%s, vlan=%s, software=%s, expirationTime=%s, antiCollocationInstance=%s, requestId=%s, requestName=%s, productCodes=%s]",
id, instanceType, owner, name, location, status, imageId, primaryIP, secondaryIPs, diskSize,
keyName, launchTime, rootOnly, vlan, software, expirationTime, antiCollocationInstance,
requestId, requestName, productCodes);
}
@Override
public int compareTo(Instance arg0) {
return id.compareTo(arg0.getId());
}
}

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import com.google.common.collect.ComparisonChain; import com.google.common.collect.ComparisonChain;

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
@ -31,7 +31,7 @@ import com.google.gson.annotations.SerializedName;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Key { public class Key implements Comparable<Key> {
@SerializedName("default") @SerializedName("default")
private boolean isDefault; private boolean isDefault;
private Set<String> instanceIds = Sets.newLinkedHashSet(); private Set<String> instanceIds = Sets.newLinkedHashSet();
@ -144,4 +144,8 @@ public class Key {
this.instanceIds = instanceIds; this.instanceIds = instanceIds;
} }
@Override
public int compareTo(Key arg0) {
return name.compareTo(arg0.name);
}
} }

View File

@ -16,21 +16,20 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
/** /**
* *
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Offering { public class Offering implements Comparable<Offering> {
protected String location; protected String location;
protected Price price; protected Price price;
protected String id; protected String id;
public Offering() { Offering() {
super();
} }
public String getLocation() { public String getLocation() {
@ -87,4 +86,8 @@ public class Offering {
return "[id=" + id + ", location=" + location + ", price=" + price + "]"; return "[id=" + id + ", location=" + location + ", price=" + price + "]";
} }
@Override
public int compareTo(Offering arg0) {
return id.compareTo(arg0.id);
}
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import java.util.Date; import java.util.Date;

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import java.util.Set; import java.util.Set;

View File

@ -16,61 +16,74 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import java.util.Map;
import com.google.common.collect.Maps;
/** /**
* *
* The current state of a location (datacenter)
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Location { public class Vlan {
public static Builder builder() {
return new Builder();
}
private final String id; public static class Builder {
private final String name; private String id;
private final String description; private String name;
private final String location; private String location;
private final Map<String, Map<String, String>> capabilities = Maps.newLinkedHashMap();
public Location(String id, String name, String description, String location, public Builder id(String id) {
Map<String, Map<String, String>> capabilities) { this.id = id;
this.id = id; return this;
this.name = name; }
this.description = description;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder location(String location) {
this.location = location;
return this;
}
public Vlan build() {
return new Vlan(location, name, id);
}
}
private String location;
private String name;
private String id;
Vlan() {
}
public Vlan(String location, String name, String id) {
this.location = location; this.location = location;
this.capabilities.putAll(capabilities); this.name = name;
} this.id = id;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
} }
public String getLocation() { public String getLocation() {
return location; return location;
} }
public Map<String, Map<String, String>> getCapabilities() { public String getName() {
return capabilities; return name;
}
public String getId() {
return id;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((location == null) ? 0 : location.hashCode()); result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode());
@ -85,17 +98,7 @@ public class Location {
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
Location other = (Location) obj; Vlan other = (Vlan) obj;
if (capabilities == null) {
if (other.capabilities != null)
return false;
} else if (!capabilities.equals(other.capabilities))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) { if (id == null) {
if (other.id != null) if (other.id != null)
return false; return false;
@ -116,8 +119,7 @@ public class Location {
@Override @Override
public String toString() { public String toString() {
return "Location [id=" + id + ", name=" + name + ", description=" + description return "[id=" + id + ", location=" + location + ", name=" + name + "]";
+ ", location=" + location + ", capabilities=" + capabilities + "]";
} }
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.domain; package org.jclouds.ibm.smartcloud.domain;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
@ -30,7 +30,7 @@ import com.google.common.collect.Sets;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Volume { public class Volume implements Comparable<Volume> {
public static enum State { public static enum State {
NEW, CREATING, DELETING, DELETED, UNMOUNTED, MOUNTED, FAILED; NEW, CREATING, DELETING, DELETED, UNMOUNTED, MOUNTED, FAILED;
@ -243,4 +243,8 @@ public class Volume {
+ productCodes + "]"; + productCodes + "]";
} }
@Override
public int compareTo(Volume arg0) {
return id.compareTo(arg0.getId());
}
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibm.smartcloud.functions;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.handlers; package org.jclouds.ibm.smartcloud.handlers;
import static org.jclouds.http.HttpUtils.releasePayload; import static org.jclouds.http.HttpUtils.releasePayload;
@ -41,7 +41,7 @@ import org.jclouds.util.Strings2;
* *
*/ */
@Singleton @Singleton
public class IBMDeveloperCloudErrorHandler implements HttpErrorHandler { public class IBMSmartCloudErrorHandler implements HttpErrorHandler {
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;

View File

@ -0,0 +1,207 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.options;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import java.util.Map.Entry;
import org.jclouds.http.options.BaseHttpRequestOptions;
import com.google.common.collect.ImmutableSet;
/**
*
*
* @author Adrian Cole
*
*/
public class CreateInstanceOptions extends BaseHttpRequestOptions {
public CreateInstanceOptions() {
super();
formParameters.put("publicKey", "DEFAULT");
}
/**
*
* @param id
* The ID of a storage volume to associate with this instance
* @param mountPoint
* The mount point in which to mount the attached storage volume
*/
public CreateInstanceOptions mountVolume(String id, String mountPoint) {
checkNotNull(id, "volume id");
checkNotNull(mountPoint, "mountPoint");
formParameters.replaceValues("volumeID", ImmutableSet.of(id));
String mountParam = String.format("oss.storage.id.0.mnt", id);
formParameters.replaceValues(mountParam, ImmutableSet.of(mountPoint));
return this;
}
/**
*
* @param publicKeyName
* The public key to use for accessing the created instancee
*/
public CreateInstanceOptions authorizePublicKey(String publicKeyName) {
checkNotNull(publicKeyName, "publicKeyName");
formParameters.replaceValues("publicKey", ImmutableSet.of(publicKeyName));
return this;
}
/**
*
* @param configurationData
* extra configuration to pass to the instance
*/
public CreateInstanceOptions configurationData(Map<String, String> configurationData) {
checkNotNull(configurationData, "configurationData");
for (Entry<String, String> entry : configurationData.entrySet()) {
formParameters.replaceValues(entry.getKey(), ImmutableSet.of(entry.getValue()));
}
return this;
}
/**
*
* @param ip
* The ID of a static IP address to associate with this instance
*/
public CreateInstanceOptions staticIP(String ip) {
checkNotNull(ip, "ip");
formParameters.replaceValues("ip", ImmutableSet.of(ip));
return this;
}
/**
*
* @param id
* The ID of a Vlan offering to associate with this instance.
*/
public CreateInstanceOptions vlanID(String id) {
checkNotNull(id, "id");
formParameters.replaceValues("vlanID", ImmutableSet.of(id));
return this;
}
/**
*
* @param ip
* The ID of a static IP address to associate with this instance as secondary IP.
*/
public CreateInstanceOptions secondaryIP(String ip) {
checkNotNull(ip, "ip");
formParameters.replaceValues("secondaryIP", ImmutableSet.of(ip));
return this;
}
/**
*
* @param id
* The ID of an existing anti-collocated instance.
*/
public CreateInstanceOptions antiCollocationInstance(String id) {
checkNotNull(id, "id");
formParameters.replaceValues("antiCollocationInstance", ImmutableSet.of(id));
return this;
}
/**
* Whether or not the instance should be provisioned with the root segment only. Compared to
* standard server size, this option will provide less storage but same memory and CPU, and thus
* provision the instance faster.
*
* @param isMiniEphemeral
* true if root only provision, False: normal provision
*/
public CreateInstanceOptions isMiniEphemeral(boolean isMiniEphemeral) {
formParameters.replaceValues("isMiniEphemeral", ImmutableSet.of(isMiniEphemeral + ""));
return this;
}
public static class Builder {
/**
* @see CreateInstanceOptions#configurationData
*/
public static CreateInstanceOptions configurationData(Map<String, String> configurationData) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.configurationData(configurationData);
}
/**
* @see CreateInstanceOptions#mountVolume
*/
public static CreateInstanceOptions mountVolume(String id, String mountPoint) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.mountVolume(id, mountPoint);
}
/**
* @see CreateInstanceOptions#staticIP
*/
public static CreateInstanceOptions staticIP(String ip) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.staticIP(ip);
}
/**
* @see CreateInstanceOptions#secondaryIP
*/
public static CreateInstanceOptions secondaryIP(String ip) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.secondaryIP(ip);
}
/**
* @see CreateInstanceOptions#vlanID
*/
public static CreateInstanceOptions vlanID(String id) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.vlanID(id);
}
/**
* @see CreateInstanceOptions#antiCollocationInstance
*/
public static CreateInstanceOptions antiCollocationInstance(String id) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.antiCollocationInstance(id);
}
/**
* @see CreateInstanceOptions#isMiniEphemeral
*/
public static CreateInstanceOptions isMiniEphemeral(boolean isMiniEphemeral) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.isMiniEphemeral(isMiniEphemeral);
}
/**
* @see CreateInstanceOptions#authorizePublicKey
*/
public static CreateInstanceOptions authorizePublicKey(String publicKeyName) {
CreateInstanceOptions options = new CreateInstanceOptions();
return options.authorizePublicKey(publicKeyName);
}
}
}

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.options; package org.jclouds.ibm.smartcloud.options;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;

View File

@ -16,15 +16,15 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.predicates; package org.jclouds.ibm.smartcloud.predicates;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -38,13 +38,13 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class AddressFree implements Predicate<Address> { public class AddressFree implements Predicate<Address> {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject @Inject
public AddressFree(IBMDeveloperCloudClient client) { public AddressFree(IBMSmartCloudClient client) {
this.client = client; this.client = client;
} }

View File

@ -16,13 +16,13 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.predicates; package org.jclouds.ibm.smartcloud.predicates;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -36,13 +36,13 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class InstanceActive implements Predicate<Instance> { public class InstanceActive implements Predicate<Instance> {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject @Inject
public InstanceActive(IBMDeveloperCloudClient client) { public InstanceActive(IBMSmartCloudClient client) {
this.client = client; this.client = client;
} }

View File

@ -16,13 +16,13 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.predicates; package org.jclouds.ibm.smartcloud.predicates;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -35,13 +35,13 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class InstanceActiveOrFailed implements Predicate<Instance> { public class InstanceActiveOrFailed implements Predicate<Instance> {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject @Inject
public InstanceActiveOrFailed(IBMDeveloperCloudClient client) { public InstanceActiveOrFailed(IBMSmartCloudClient client) {
this.client = client; this.client = client;
} }

View File

@ -16,13 +16,13 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.predicates; package org.jclouds.ibm.smartcloud.predicates;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -36,13 +36,13 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class InstanceRemovedOrNotFound implements Predicate<Instance> { public class InstanceRemovedOrNotFound implements Predicate<Instance> {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject @Inject
public InstanceRemovedOrNotFound(IBMDeveloperCloudClient client) { public InstanceRemovedOrNotFound(IBMSmartCloudClient client) {
this.client = client; this.client = client;
} }

View File

@ -16,13 +16,13 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.predicates; package org.jclouds.ibm.smartcloud.predicates;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibm.smartcloud.IBMSmartCloudClient;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibm.smartcloud.domain.Volume;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -35,13 +35,13 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class VolumeUnmounted implements Predicate<Volume> { public class VolumeUnmounted implements Predicate<Volume> {
private final IBMDeveloperCloudClient client; private final IBMSmartCloudClient client;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject @Inject
public VolumeUnmounted(IBMDeveloperCloudClient client) { public VolumeUnmounted(IBMSmartCloudClient client) {
this.client = client; this.client = client;
} }

View File

@ -16,17 +16,18 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.reference; package org.jclouds.ibm.smartcloud.reference;
/** /**
* Configuration properties and constants used in IBMDeveloperCloud connections. * Configuration properties and constants used in IBMSmartCloud connections.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public interface IBMDeveloperCloudConstants { public interface Capabilities {
public static final String CAPABILITY_CAPACITY = "oss.storage.capacity"; public static final String CAPABILITY_CAPACITY = "oss.storage.capacity";
public static final String CAPABILITY_FORMAT = "oss.storage.format"; public static final String CAPABILITY_FORMAT = "oss.storage.format";
public static final String CAPABILITY_I386 = "oss.instance.spec.i386"; public static final String CAPABILITY_I386 = "oss.instance.spec.i386";
public static final String CAPABILITY_x86_64 = "oss.instance.spec.x86_64"; public static final String CAPABILITY_x86_64 = "oss.instance.spec.x86_64";
public static final String CAPABILITY_AVAILABILITYAREA = "oss.storage.availabilityarea";
} }

View File

@ -16,15 +16,13 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.xml; package org.jclouds.ibm.smartcloud.xml;
import java.util.Map; import java.util.Map;
import javax.annotation.Resource;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibm.smartcloud.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.ibm.smartcloud.domain.Location.State;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
@ -44,18 +42,16 @@ public class LocationHandler extends ParseSax.HandlerWithResult<Location> {
private String capabilityName; private String capabilityName;
private String capabilityKey; private String capabilityKey;
@Resource
protected Logger logger = Logger.NULL;
private Location loc; private Location loc;
private State state;
public Location getResult() { public Location getResult() {
return loc; return loc;
} }
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attributes) public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
throws SAXException {
if (qName.equalsIgnoreCase("Capability")) { if (qName.equalsIgnoreCase("Capability")) {
capabilityName = attributes.getValue(attributes.getIndex("id")); capabilityName = attributes.getValue(attributes.getIndex("id"));
capabilities.put(capabilityName, Maps.<String, String> newLinkedHashMap()); capabilities.put(capabilityName, Maps.<String, String> newLinkedHashMap());
@ -74,15 +70,18 @@ public class LocationHandler extends ParseSax.HandlerWithResult<Location> {
description = currentText.toString().trim(); description = currentText.toString().trim();
if (description.equals("")) if (description.equals(""))
description = null; description = null;
} else if (qName.equalsIgnoreCase("State")) {
state = State.fromValue(Integer.parseInt(currentText.toString().trim()));
} else if (qName.equalsIgnoreCase("Value")) { } else if (qName.equalsIgnoreCase("Value")) {
capabilities.get(capabilityName).put(capabilityKey, currentText.toString().trim()); capabilities.get(capabilityName).put(capabilityKey, currentText.toString().trim());
} else if (qName.equalsIgnoreCase("Location")) { } else if (qName.equalsIgnoreCase("Location")) {
if (currentText.toString().trim().equals("")) { if (currentText.toString().trim().equals("")) {
this.loc = new Location(id, name, description, location, capabilities); this.loc = new Location(id, name, description, location, state, capabilities);
id = null; id = null;
name = null; name = null;
description = null; description = null;
location = null; location = null;
state = null;
capabilities = Maps.newLinkedHashMap(); capabilities = Maps.newLinkedHashMap();
capabilityKey = null; capabilityKey = null;
capabilityName = null; capabilityName = null;

View File

@ -16,14 +16,14 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.xml; package org.jclouds.ibm.smartcloud.xml;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibm.smartcloud.domain.Location;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
@ -35,7 +35,7 @@ import com.google.common.collect.Sets;
public class LocationsHandler extends ParseSax.HandlerWithResult<Set<? extends Location>> { public class LocationsHandler extends ParseSax.HandlerWithResult<Set<? extends Location>> {
private StringBuilder currentText = new StringBuilder(); private StringBuilder currentText = new StringBuilder();
private Set<Location> tasks = Sets.newLinkedHashSet(); private Set<Location> locations = Sets.newLinkedHashSet();
private final LocationHandler locationHandler; private final LocationHandler locationHandler;
@Inject @Inject
@ -44,7 +44,7 @@ public class LocationsHandler extends ParseSax.HandlerWithResult<Set<? extends L
} }
public Set<? extends Location> getResult() { public Set<? extends Location> getResult() {
return tasks; return locations;
} }
@Override @Override
@ -57,7 +57,7 @@ public class LocationsHandler extends ParseSax.HandlerWithResult<Set<? extends L
public void endElement(String uri, String localName, String qName) throws SAXException { public void endElement(String uri, String localName, String qName) throws SAXException {
locationHandler.endElement(uri, localName, qName); locationHandler.endElement(uri, localName, qName);
if (qName.equals("Location") && currentText.toString().trim().equals("")) { if (qName.equals("Location") && currentText.toString().trim().equals("")) {
this.tasks.add(locationHandler.getResult()); this.locations.add(locationHandler.getResult());
} }
currentText = new StringBuilder(); currentText = new StringBuilder();
} }

View File

@ -0,0 +1,91 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeTestUtils;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/**
*
* @author Adrian Cole
*/
@Test(groups = "live", singleThreaded = true, testName = "BaseIBMSmartCloudClientLiveTest")
public abstract class BaseIBMSmartCloudClientLiveTest {
protected RestContext<IBMSmartCloudClient, IBMSmartCloudAsyncClient> context;
protected String provider = "ibm-smartcloud";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
protected IBMSmartCloudClient connection;
protected Map<String, String> keyPair;
protected void setupCredentials() {
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider
+ ".identity must be set. ex. apiKey");
credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider
+ ".credential must be set. ex. secretKey");
endpoint = System.getProperty("test." + provider + ".endpoint");
apiversion = System.getProperty("test." + provider + ".apiversion");
}
protected Properties setupProperties() {
Properties overrides = new Properties();
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
overrides.setProperty(provider + ".identity", identity);
overrides.setProperty(provider + ".credential", credential);
if (endpoint != null)
overrides.setProperty(provider + ".endpoint", endpoint);
if (apiversion != null)
overrides.setProperty(provider + ".apiversion", apiversion);
return overrides;
}
@BeforeGroups(groups = "live")
public void setupClient() throws FileNotFoundException, IOException {
setupCredentials();
Properties overrides = setupProperties();
context = new RestContextFactory().createContext(provider, ImmutableSet.<Module> of(new Log4JLoggingModule(),
new JschSshClientModule()), overrides);
connection = context.getApi();
keyPair = ComputeTestUtils.setupKeyPair();
}
}

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -31,22 +31,11 @@ import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibmdev.functions.GetFirstInstanceInList; import org.jclouds.ibm.smartcloud.options.CreateInstanceOptions;
import org.jclouds.ibmdev.functions.ParseAddressFromJson; import org.jclouds.ibm.smartcloud.options.RestartInstanceOptions;
import org.jclouds.ibmdev.functions.ParseAddressesFromJson; import org.jclouds.ibm.smartcloud.xml.LocationHandler;
import org.jclouds.ibmdev.functions.ParseExpirationTimeFromJson; import org.jclouds.ibm.smartcloud.xml.LocationsHandler;
import org.jclouds.ibmdev.functions.ParseImageFromJson;
import org.jclouds.ibmdev.functions.ParseImagesFromJson;
import org.jclouds.ibmdev.functions.ParseInstanceFromJson;
import org.jclouds.ibmdev.functions.ParseInstancesFromJson;
import org.jclouds.ibmdev.functions.ParseKeysFromJson;
import org.jclouds.ibmdev.functions.ParseVolumeFromJson;
import org.jclouds.ibmdev.functions.ParseVolumesFromJson;
import org.jclouds.ibmdev.options.CreateInstanceOptions;
import org.jclouds.ibmdev.options.RestartInstanceOptions;
import org.jclouds.ibmdev.xml.LocationHandler;
import org.jclouds.ibmdev.xml.LocationsHandler;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.RestContextSpec;
@ -61,19 +50,19 @@ import com.google.common.collect.Iterables;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
/** /**
* Tests annotation parsing of {@code IBMDeveloperCloudAsyncClient} * Tests annotation parsing of {@code IBMSmartCloudAsyncClient}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "ibmdevelopercloud.IBMDeveloperCloudAsyncClientTest") @Test(groups = "unit", testName = "IBMSmartCloudAsyncClientTest")
public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDeveloperCloudAsyncClient> { public class IBMSmartCloudAsyncClientTest extends RestClientTest<IBMSmartCloudAsyncClient> {
public void testListImages() throws SecurityException, NoSuchMethodException, IOException { public void testListImages() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listImages"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listImages");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -82,14 +71,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1");
// for example, using basic authentication, we should get "only one" // for example, using basic authentication, we should get "only one"
// header // header
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest,
"Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); "Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseImagesFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
@ -98,15 +88,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testGetImage() throws SecurityException, NoSuchMethodException, IOException { public void testGetImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getImage", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("getImage", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
@ -115,11 +106,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testDeleteImage() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteImage", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("deleteImage", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -132,17 +123,17 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testSetImageVisibility() throws SecurityException, NoSuchMethodException, IOException { public void testSetImageVisibility() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("setImageVisibility", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("setImageVisibility", String.class,
Image.Visibility.class); Image.Visibility.class);
HttpRequest httpRequest = processor.createRequest(method, "1", HttpRequest httpRequest = processor.createRequest(method, "1", Image.Visibility.PUBLIC);
Image.Visibility.PUBLIC);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
@ -151,15 +142,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListInstances() throws SecurityException, NoSuchMethodException, IOException { public void testListInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listInstances"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listInstances");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseInstancesFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
@ -168,15 +160,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListInstancesFromRequest() throws SecurityException, NoSuchMethodException, IOException { public void testListInstancesFromRequest() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listInstancesFromRequest", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("listInstancesFromRequest", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/requests/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/requests/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseInstancesFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
@ -185,15 +178,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testGetInstance() throws SecurityException, NoSuchMethodException, IOException { public void testGetInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getInstance", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("getInstance", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseInstanceFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
@ -202,17 +196,17 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testExtendReservationForInstance() throws SecurityException, NoSuchMethodException, IOException { public void testExtendReservationForInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("extendReservationForInstance", String.class, Method method = IBMSmartCloudAsyncClient.class
Date.class); .getMethod("extendReservationForInstance", String.class, Date.class);
HttpRequest httpRequest = processor.createRequest(method, "1", new Date( HttpRequest httpRequest = processor.createRequest(method, "1", new Date(123215235l));
123215235l));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseExpirationTimeFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -220,12 +214,12 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testRestartInstance() throws SecurityException, NoSuchMethodException, IOException { public void testRestartInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("restartInstance", String.class,
RestartInstanceOptions[].class); RestartInstanceOptions[].class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false);
@ -237,13 +231,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testRestartInstanceNewKey() throws SecurityException, NoSuchMethodException, IOException { public void testRestartInstanceNewKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("restartInstance", String.class,
RestartInstanceOptions[].class); RestartInstanceOptions[].class);
HttpRequest httpRequest = processor.createRequest(method, "1", HttpRequest httpRequest = processor.createRequest(method, "1", new RestartInstanceOptions()
new RestartInstanceOptions().authorizePublicKey("keyName")); .authorizePublicKey("keyName"));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false);
@ -255,18 +249,18 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testSaveInstanceToImage() throws SecurityException, NoSuchMethodException, IOException { public void testSaveInstanceToImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("saveInstanceToImage", String.class, String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("saveInstanceToImage", String.class, String.class,
String.class); String.class);
HttpRequest httpRequest = processor.createRequest(method, "1", HttpRequest httpRequest = processor.createRequest(method, "1", "imageName", "imageDescription");
"imageName", "imageDescription");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "state=save&description=imageDescription&name=imageName", assertPayloadEquals(httpRequest, "state=save&description=imageDescription&name=imageName",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -274,11 +268,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testDeleteInstance() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteInstance", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("deleteInstance", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -291,15 +285,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListKeys() throws SecurityException, NoSuchMethodException, IOException { public void testListKeys() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listKeys"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listKeys");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeysFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
@ -308,11 +303,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testGetKey() throws SecurityException, NoSuchMethodException, IOException { public void testGetKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getKey", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("getKey", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -325,11 +320,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testGenerateKeyPair() throws SecurityException, NoSuchMethodException, IOException { public void testGenerateKeyPair() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("generateKeyPair", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("generateKeyPair", String.class);
HttpRequest httpRequest = processor.createRequest(method, "key"); HttpRequest httpRequest = processor.createRequest(method, "key");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false);
@ -342,12 +337,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testAddPublicKey() throws SecurityException, NoSuchMethodException, IOException { public void testAddPublicKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("addPublicKey", String.class, String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("addPublicKey", String.class, String.class);
HttpRequest httpRequest = processor.createRequest(method, "key", HttpRequest httpRequest = processor.createRequest(method, "key", "publicbits");
"publicbits");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false);
@ -360,12 +354,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testUpdatePublicKey() throws SecurityException, NoSuchMethodException, IOException { public void testUpdatePublicKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("updatePublicKey", String.class, String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("updatePublicKey", String.class, String.class);
HttpRequest httpRequest = processor.createRequest(method, "key", HttpRequest httpRequest = processor.createRequest(method, "key", "publicbits");
"publicbits");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false);
@ -378,12 +371,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testSetDefaultStatusOfKey() throws SecurityException, NoSuchMethodException, IOException { public void testSetDefaultStatusOfKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class Method method = IBMSmartCloudAsyncClient.class.getMethod("setDefaultStatusOfKey", String.class, boolean.class);
.getMethod("setDefaultStatusOfKey", String.class, boolean.class);
HttpRequest httpRequest = processor.createRequest(method, "key", true); HttpRequest httpRequest = processor.createRequest(method, "key", true);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false);
@ -396,11 +388,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testDeleteKey() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteKey", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("deleteKey", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -413,15 +405,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListVolumes() throws SecurityException, NoSuchMethodException, IOException { public void testListVolumes() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listVolumes"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listVolumes");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseVolumesFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
@ -430,15 +423,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testGetVolume() throws SecurityException, NoSuchMethodException, IOException { public void testGetVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getVolume", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("getVolume", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseVolumeFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
@ -447,18 +441,17 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, IOException { public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createVolumeInLocation", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("createVolumeInLocation", String.class, String.class,
String.class, String.class, String.class, String.class); String.class, String.class, String.class);
HttpRequest httpRequest = processor.createRequest(method, "location", HttpRequest httpRequest = processor.createRequest(method, "location", "name", "format", "size", "offering");
"name", "format", "size", "offering");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=location&format=format&name=name&size=size&offeringID=offering", assertPayloadEquals(httpRequest, "location=location&format=format&name=name&size=size&offeringID=offering",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseVolumeFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -467,17 +460,17 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testCreateInstanceInLocation() throws SecurityException, NoSuchMethodException, IOException { public void testCreateInstanceInLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class, String.class,
String.class, String.class, String.class, CreateInstanceOptions[].class); String.class, String.class, CreateInstanceOptions[].class);
HttpRequest httpRequest = processor.createRequest(method, "1", "name", HttpRequest httpRequest = processor.createRequest(method, "1", "name", "22", "instanceType");
"22", "instanceType");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=1&imageID=22&name=name&instanceType=instanceType", assertPayloadEquals(httpRequest, "location=1&imageID=22&name=name&instanceType=instanceType",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, GetFirstInstanceInList.class);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -486,23 +479,23 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testCreateInstanceInLocationWithOptions() throws SecurityException, NoSuchMethodException, IOException { public void testCreateInstanceInLocationWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class, String.class,
String.class, String.class, String.class, CreateInstanceOptions[].class); String.class, String.class, CreateInstanceOptions[].class);
HttpRequest httpRequest = processor.createRequest(method, "location", HttpRequest httpRequest = processor.createRequest(method, "location", "name", "22", "instanceType",
"name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO") new CreateInstanceOptions().staticIP("1").authorizePublicKey("MOO").mountVolume("2", "/mnt")
.mountVolume("2", "/mnt").configurationData( .configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password", "myPassword2", ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password",
"report_user_password", "myPassword3"))); "myPassword2", "report_user_password", "myPassword3")));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals( assertPayloadEquals(
httpRequest, httpRequest,
"location=location&imageID=22&name=name&instanceType=instanceType&ip=1&publicKey=MOO&volumeID=2&oss.storage.id.0.mnt=%2Fmnt&insight_admin_password=myPassword1&db2_admin_password=myPassword2&report_user_password=myPassword3", "location=location&imageID=22&name=name&instanceType=instanceType&ip=1&publicKey=MOO&volumeID=2&oss.storage.id.0.mnt=%2Fmnt&insight_admin_password=myPassword1&db2_admin_password=myPassword2&report_user_password=myPassword3",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, GetFirstInstanceInList.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -511,11 +504,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteVolume", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("deleteVolume", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -528,11 +521,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListLocations() throws SecurityException, NoSuchMethodException, IOException { public void testListLocations() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listLocations"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listLocations");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -545,11 +538,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testGetLocation() throws SecurityException, NoSuchMethodException, IOException { public void testGetLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getLocation", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("getLocation", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -562,15 +555,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListAddresses() throws SecurityException, NoSuchMethodException, IOException { public void testListAddresses() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listAddresses"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listAddresses");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseAddressesFromJson.class); assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
@ -579,16 +573,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testAllocateAddressInLocation() throws SecurityException, NoSuchMethodException, IOException { public void testAllocateAddressInLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("allocateAddressInLocation", String.class, Method method = IBMSmartCloudAsyncClient.class.getMethod("allocateAddressInLocation", String.class, String.class);
String.class);
HttpRequest httpRequest = processor.createRequest(method, "1", "offering"); HttpRequest httpRequest = processor.createRequest(method, "1", "offering");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=1&offeringID=offering", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "location=1&offeringID=offering", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseAddressFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -597,11 +590,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException { public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("releaseAddress", String.class); Method method = IBMSmartCloudAsyncClient.class.getMethod("releaseAddress", String.class);
HttpRequest httpRequest = processor.createRequest(method, "1"); HttpRequest httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -614,11 +607,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListStorageOfferings() throws SecurityException, NoSuchMethodException, IOException { public void testListStorageOfferings() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listStorageOfferings"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listStorageOfferings");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/storage HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/storage HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -630,11 +623,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListAddressOfferings() throws SecurityException, NoSuchMethodException, IOException { public void testListAddressOfferings() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listAddressOfferings"); Method method = IBMSmartCloudAsyncClient.class.getMethod("listAddressOfferings");
HttpRequest httpRequest = processor.createRequest(method); HttpRequest httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/address HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/address HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -652,13 +645,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
@Override @Override
protected TypeLiteral<RestAnnotationProcessor<IBMDeveloperCloudAsyncClient>> createTypeLiteral() { protected TypeLiteral<RestAnnotationProcessor<IBMSmartCloudAsyncClient>> createTypeLiteral() {
return new TypeLiteral<RestAnnotationProcessor<IBMDeveloperCloudAsyncClient>>() { return new TypeLiteral<RestAnnotationProcessor<IBMSmartCloudAsyncClient>>() {
}; };
} }
@Override @Override
public RestContextSpec<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> createContextSpec() { public RestContextSpec<IBMSmartCloudClient, IBMSmartCloudAsyncClient> createContextSpec() {
return new RestContextFactory().createContextSpec("ibmdev", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("ibm-smartcloud", "identity", "credential", new Properties());
} }
} }

View File

@ -16,21 +16,17 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.filter;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.attachIp; import static org.jclouds.ibm.smartcloud.options.CreateInstanceOptions.Builder.authorizePublicKey;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.authorizePublicKey; import static org.jclouds.ibm.smartcloud.options.CreateInstanceOptions.Builder.secondaryIP;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -38,55 +34,47 @@ import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler; import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibmdev.domain.InstanceType; import org.jclouds.ibm.smartcloud.domain.InstanceType;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibm.smartcloud.domain.Location;
import org.jclouds.ibmdev.domain.Offering; import org.jclouds.ibm.smartcloud.domain.Offering;
import org.jclouds.ibmdev.domain.StorageOffering; import org.jclouds.ibm.smartcloud.domain.StorageOffering;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibm.smartcloud.domain.Volume;
import org.jclouds.ibmdev.domain.Instance.Software; import org.jclouds.ibm.smartcloud.domain.Instance.Software;
import org.jclouds.ibmdev.domain.StorageOffering.Format; import org.jclouds.ibm.smartcloud.domain.StorageOffering.Format;
import org.jclouds.ibmdev.predicates.AddressFree; import org.jclouds.ibm.smartcloud.predicates.AddressFree;
import org.jclouds.ibmdev.predicates.InstanceActive; import org.jclouds.ibm.smartcloud.predicates.InstanceActive;
import org.jclouds.ibmdev.predicates.InstanceActiveOrFailed; import org.jclouds.ibm.smartcloud.predicates.InstanceActiveOrFailed;
import org.jclouds.ibmdev.predicates.InstanceRemovedOrNotFound; import org.jclouds.ibm.smartcloud.predicates.InstanceRemovedOrNotFound;
import org.jclouds.ibmdev.predicates.VolumeUnmounted; import org.jclouds.ibm.smartcloud.predicates.VolumeUnmounted;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshException; import org.jclouds.ssh.SshException;
import org.jclouds.ssh.jsch.JschSshClient; import org.jclouds.ssh.jsch.JschSshClient;
import org.testng.annotations.AfterTest; import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Charsets;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ComparisonChain; import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.inject.Module;
/** /**
* Tests behavior of {@code IBMDeveloperCloudClient} * Tests behavior of {@code IBMSmartCloudClient}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "live", testName = "ibmdevelopercloud.IBMDeveloperCloudClientLiveTest") @Test(groups = "live", singleThreaded = true, testName = "IBMSmartCloudClientLiveTest")
public class IBMDeveloperCloudClientLiveTest { public class IBMSmartCloudClientLiveTest extends BaseIBMSmartCloudClientLiveTest {
private static final String OS = "Red Hat Enterprise Linux"; private static final String OS = "SUSE Linux Enterprise Server";
private static final String VERSION = "5.4"; private static final String VERSION = "11 SP1";
private static final String PLATFORM = OS + "/" + VERSION; private static final String PLATFORM = OS + "/" + VERSION;
@ -94,143 +82,43 @@ public class IBMDeveloperCloudClientLiveTest {
private static String FORMAT = "EXT3"; private static String FORMAT = "EXT3";
private IBMDeveloperCloudClient connection;
private Location location; private Location location;
private Address ip; private Address ip;
private ImmutableMap<String, String> keyPair;
private Key key; private Key key;
private Volume volume; private Volume volume;
private String identity;
private Instance instance2; private Instance instance2;
private Instance instance; private Instance instance;
private RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> context;
private InstanceType instanceType; private InstanceType instanceType;
private Image image; private Image image;
private StorageOffering cheapestStorage; private StorageOffering cheapestStorage;
private static final String TAG = System.getProperty("user.name"); private static final String GROUP = System.getProperty("user.name");
@BeforeGroups(groups = { "live" })
public void setupClient() {
String endpoint = System.getProperty("jclouds.test.endpoint");
identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");
Properties props = new Properties();
if (endpoint != null)
props.setProperty("ibmdev.endpoint", endpoint);
context = new RestContextFactory().createContext("ibmdev", identity, credential, ImmutableSet
.<Module> of(new Log4JLoggingModule()), props);
connection = context.getApi();
for (Instance instance : connection.listInstances()) {
try {
connection.deleteInstance(instance.getId());
} catch (Exception e) {
}
}
}
@Test
public void testListImages() throws Exception {
Set<? extends Image> response = connection.listImages();
assertNotNull(response);
}
@Test
public void testGetImage() throws Exception {
Set<? extends Image> response = connection.listImages();
assertNotNull(response);
if (response.size() > 0) {
Image image = Iterables.get(response, 0);
assertEquals(connection.getImage(image.getId()).getId(), image.getId());
}
}
@Test
public void testListInstances() throws Exception {
Set<? extends Instance> response = connection.listInstances();
assertNotNull(response);
}
@Test
public void testListInstancesFromRequestReturnsEmptySet() throws Exception {
Set<? extends Instance> response = connection.listInstancesFromRequest(Long.MAX_VALUE + "");
assertEquals(response.size(), 0);
}
@Test
public void testGetInstance() throws Exception {
Set<? extends Instance> response = connection.listInstances();
assertNotNull(response);
if (response.size() > 0) {
Instance instance = Iterables.get(response, 0);
assertEquals(connection.getInstance(instance.getId()).getId(), instance.getId());
}
}
@Test
public void testListKeys() throws Exception {
Set<? extends Key> response = connection.listKeys();
assertNotNull(response);
}
@Test
public void testGetKey() throws Exception {
Set<? extends Key> response = connection.listKeys();
assertNotNull(response);
if (response.size() > 0) {
Key key = Iterables.get(response, 0);
assertEquals(connection.getKey(key.getName()).getName(), key.getName());
}
}
@Test
public void testListVolumes() throws Exception {
Set<? extends Volume> response = connection.listVolumes();
assertNotNull(response);
}
@Test
public void testGetVolume() throws Exception {
Set<? extends Volume> response = connection.listVolumes();
assertNotNull(response);
if (response.size() > 0) {
Volume image = Iterables.get(response, 0);
assertEquals(connection.getVolume(image.getId()).getId(), image.getId());
}
}
@Test
public void testListLocations() throws Exception {
Set<? extends Location> response = connection.listLocations();
assertNotNull(response);
}
@Test @Test
public void testGetLocation() throws Exception { public void testGetLocation() throws Exception {
Set<? extends Location> response = connection.listLocations(); Set<? extends Location> response = connection.listLocations();
assertNotNull(response); assertNotNull(response);
if (response.size() > 0) { if (response.size() > 0) {
location = Iterables.get(response, 0); location = Iterables.find(response, new Predicate<Location>() {
@Override
public boolean apply(Location arg0) {
// ontario is the least used
return "101".equals(arg0.getId());
}
});
assertEquals(connection.getLocation(location.getId()).getId(), location.getId()); assertEquals(connection.getLocation(location.getId()).getId(), location.getId());
} }
} }
@Test
public void testListAddresss() throws Exception {
Set<? extends Address> response = connection.listAddresses();
assertNotNull(response);
}
@Test(dependsOnMethods = "testGetLocation") @Test(dependsOnMethods = "testGetLocation")
public void testAddPublicKey() throws Exception { public void testAddPublicKey() throws Exception {
try { try {
connection.addPublicKey(TAG, keyPair.get("public")); connection.addPublicKey(GROUP, keyPair.get("public"));
key = connection.getKey(TAG); key = connection.getKey(GROUP);
try { try {
assert key.getInstanceIds().equals(ImmutableSet.<String> of()) : key; assert key.getInstanceIds().equals(ImmutableSet.<String> of()) : key;
} catch (AssertionError e) { } catch (AssertionError e) {
@ -239,8 +127,8 @@ public class IBMDeveloperCloudClientLiveTest {
} }
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// must have been found // must have been found
connection.updatePublicKey(TAG, keyPair.get("public")); connection.updatePublicKey(GROUP, keyPair.get("public"));
key = connection.getKey(TAG); key = connection.getKey(GROUP);
for (String instanceId : key.getInstanceIds()) { for (String instanceId : key.getInstanceIds()) {
Instance instance = connection.getInstance(instanceId); Instance instance = connection.getInstance(instanceId);
if (instance.getStatus() == Instance.Status.FAILED || instance.getStatus() == Instance.Status.ACTIVE) { if (instance.getStatus() == Instance.Status.FAILED || instance.getStatus() == Instance.Status.ACTIVE) {
@ -248,7 +136,7 @@ public class IBMDeveloperCloudClientLiveTest {
} }
} }
} }
assertEquals(key.getName(), TAG); assertEquals(key.getName(), GROUP);
assert keyPair.get("public").indexOf(key.getKeyMaterial()) > 0; assert keyPair.get("public").indexOf(key.getKeyMaterial()) > 0;
assertNotNull(key.getLastModifiedTime()); assertNotNull(key.getLastModifiedTime());
} }
@ -267,7 +155,7 @@ public class IBMDeveloperCloudClientLiveTest {
try { try {
ip = connection.allocateAddressInLocation(location.getId(), offering.getId()); ip = connection.allocateAddressInLocation(location.getId(), offering.getId());
System.out.println(ip); System.out.println(ip);
assertEquals(ip.getIp(), null); assertEquals(ip.getIP(), null);
// wait up to 30 seconds for this to become "free" // wait up to 30 seconds for this to become "free"
new RetryablePredicate<Address>(new AddressFree(connection), 30, 2, TimeUnit.SECONDS).apply(ip); new RetryablePredicate<Address>(new AddressFree(connection), 30, 2, TimeUnit.SECONDS).apply(ip);
refreshIpAndReturnAllAddresses(); refreshIpAndReturnAllAddresses();
@ -304,19 +192,19 @@ public class IBMDeveloperCloudClientLiveTest {
}.reverse(); }.reverse();
Iterable<? extends StorageOffering> storageOfferingsThatAreInOurLocationAndCorrectFormat = filter(connection Iterable<? extends StorageOffering> storageOfferingsThatAreInOurLocationAndCorrectFormat = filter(connection
.listStorageOfferings(), new Predicate<StorageOffering>() { .listStorageOfferings(), new Predicate<StorageOffering>() {
@Override @Override
public boolean apply(StorageOffering arg0) { public boolean apply(StorageOffering arg0) {
return arg0.getLocation().equals(location.getId()) return arg0.getLocation().equals(location.getId())
&& Iterables.any(arg0.getFormats(), new Predicate<StorageOffering.Format>() { && Iterables.any(arg0.getFormats(), new Predicate<StorageOffering.Format>() {
@Override @Override
public boolean apply(Format arg0) { public boolean apply(Format arg0) {
return arg0.getId().equals(FORMAT); return arg0.getId().equals(FORMAT);
} }
}); });
} }
}); });
cheapestStorage = cheapestOrdering.max(storageOfferingsThatAreInOurLocationAndCorrectFormat); cheapestStorage = cheapestOrdering.max(storageOfferingsThatAreInOurLocationAndCorrectFormat);
@ -326,8 +214,8 @@ public class IBMDeveloperCloudClientLiveTest {
@Test(dependsOnMethods = "testResolveVolumeOffering") @Test(dependsOnMethods = "testResolveVolumeOffering")
public void testCreateVolume() throws Exception { public void testCreateVolume() throws Exception {
try { try {
volume = connection.createVolumeInLocation(location.getId(), TAG, FORMAT, cheapestStorage.getName(), volume = connection.createVolumeInLocation(location.getId(), GROUP, FORMAT, cheapestStorage.getName(),
cheapestStorage.getId()); cheapestStorage.getId());
// wait up to 5 minutes for this to become "unmounted" // wait up to 5 minutes for this to become "unmounted"
assert new RetryablePredicate<Volume>(new VolumeUnmounted(connection), 300, 5, TimeUnit.SECONDS).apply(volume); assert new RetryablePredicate<Volume>(new VolumeUnmounted(connection), 300, 5, TimeUnit.SECONDS).apply(volume);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
@ -344,7 +232,7 @@ public class IBMDeveloperCloudClientLiveTest {
}); });
} catch (NoSuchElementException ex) { } catch (NoSuchElementException ex) {
killInstance(TAG + 1); killInstance(GROUP + 1);
} }
} else { } else {
throw e; throw e;
@ -372,13 +260,13 @@ public class IBMDeveloperCloudClientLiveTest {
@Test(dependsOnMethods = "testGetLocation") @Test(dependsOnMethods = "testGetLocation")
public void resolveImageAndInstanceType() throws Exception { public void resolveImageAndInstanceType() throws Exception {
Iterable<? extends Image> imagesThatAreInOurLocationAndNotBYOL = filter(connection.listImages(), Iterable<? extends Image> imagesThatAreInOurLocationAndNotBYOL = filter(connection.listImages(),
new Predicate<Image>() { new Predicate<Image>() {
@Override @Override
public boolean apply(Image arg0) { public boolean apply(Image arg0) {
return arg0.getLocation().equals(location.getId()) && arg0.getPlatform().equals(PLATFORM) return arg0.getLocation().equals(location.getId()) && arg0.getPlatform().equals(PLATFORM)
&& !arg0.getName().contains("BYOL") && !arg0.getName().contains("PAYG"); && arg0.getName().startsWith(OS);
} }
}); });
Ordering<InstanceType> cheapestOrdering = new Ordering<InstanceType>() { Ordering<InstanceType> cheapestOrdering = new Ordering<InstanceType>() {
public int compare(InstanceType left, InstanceType right) { public int compare(InstanceType left, InstanceType right) {
@ -405,22 +293,21 @@ public class IBMDeveloperCloudClientLiveTest {
}); });
System.err.println(image); System.err.println(image);
connection.getManifest(connection.getImage(image.getId()).getManifest()); System.err.println(connection.getManifestOfImage(image.getId()));
connection.getManifest(connection.getImage(image.getId()).getDocumentation());
} }
@Test(dependsOnMethods = { "testAddPublicKey", "resolveImageAndInstanceType" }) @Test(dependsOnMethods = { "testAddPublicKey", "resolveImageAndInstanceType" })
public void testCreateInstance() throws Exception { public void testCreateInstance() throws Exception {
killInstance(TAG); killInstance(GROUP);
instance = connection.createInstanceInLocation(location.getId(), TAG, image.getId(), instanceType.getId(), instance = connection.createInstanceInLocation(location.getId(), GROUP, image.getId(), instanceType.getId(),
authorizePublicKey(key.getName())); authorizePublicKey(key.getName()).isMiniEphemeral(true));
assertBeginState(instance, TAG); assertBeginState(instance, GROUP);
assertIpHostNullAndStatusNEW(instance); assertIpHostNullAndStatusNEW(instance);
blockUntilRunning(instance); blockUntilRunning(instance);
instance = assertRunning(instance, TAG); instance = assertRunning(instance, GROUP);
sshAndDf(new IPSocket(instance.getIp(), 22), new Credentials("idcuser", key.getKeyMaterial())); sshAndDf(new IPSocket(instance.getPrimaryIP().getIP(), 22), new Credentials("idcuser", key.getKeyMaterial()));
} }
private void killInstance(final String nameToKill) { private void killInstance(final String nameToKill) {
@ -435,16 +322,16 @@ public class IBMDeveloperCloudClientLiveTest {
}); });
if (instance.getStatus() != Instance.Status.DEPROVISIONING if (instance.getStatus() != Instance.Status.DEPROVISIONING
&& instance.getStatus() != Instance.Status.DEPROVISION_PENDING) { && instance.getStatus() != Instance.Status.DEPROVISION_PENDING) {
System.out.println("deleting instance: " + instance); System.out.println("deleting instance: " + instance);
int timeout = (instance.getStatus() == Instance.Status.NEW || instance.getStatus() == Instance.Status.PROVISIONING) ? 300 int timeout = (instance.getStatus() == Instance.Status.NEW || instance.getStatus() == Instance.Status.PROVISIONING) ? 300
: 30; : 30;
assert new RetryablePredicate<Instance>(new InstanceActiveOrFailed(connection), timeout, 2, assert new RetryablePredicate<Instance>(new InstanceActiveOrFailed(connection), timeout, 2,
TimeUnit.SECONDS).apply(instance) : instance; TimeUnit.SECONDS).apply(instance) : instance;
connection.deleteInstance(instance.getId()); connection.deleteInstance(instance.getId());
} }
assert new RetryablePredicate<Instance>(new InstanceRemovedOrNotFound(connection), 120, 2, TimeUnit.SECONDS) assert new RetryablePredicate<Instance>(new InstanceRemovedOrNotFound(connection), 120, 2, TimeUnit.SECONDS)
.apply(instance) : instance; .apply(instance) : instance;
} catch (NoSuchElementException ex) { } catch (NoSuchElementException ex) {
} }
} }
@ -469,7 +356,7 @@ public class IBMDeveloperCloudClientLiveTest {
private void blockUntilRunning(Instance instance) { private void blockUntilRunning(Instance instance) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
assert new RetryablePredicate<Instance>(new InstanceActive(connection), 15 * 60 * 1000).apply(instance) : connection assert new RetryablePredicate<Instance>(new InstanceActive(connection), 15 * 60 * 1000).apply(instance) : connection
.getInstance(instance.getId()); .getInstance(instance.getId());
System.out.println(((System.currentTimeMillis() - start) / 1000) + " seconds"); System.out.println(((System.currentTimeMillis() - start) / 1000) + " seconds");
} }
@ -487,7 +374,7 @@ public class IBMDeveloperCloudClientLiveTest {
} }
private void assertConsistent(Instance instance, String name) { private void assertConsistent(Instance instance, String name) {
assertNotNull(instance.getId()); assert (instance.getId() != null) : instance;
assertEquals(instance.getName(), name); assertEquals(instance.getName(), name);
assertEquals(instance.getInstanceType(), instanceType.getId()); assertEquals(instance.getInstanceType(), instanceType.getId());
assertEquals(instance.getLocation(), location.getId()); assertEquals(instance.getLocation(), location.getId());
@ -503,31 +390,29 @@ public class IBMDeveloperCloudClientLiveTest {
} }
private void assertIpHostNullAndStatusNEW(Instance instance) { private void assertIpHostNullAndStatusNEW(Instance instance) {
assertEquals(instance.getIp(), null); assertEquals(instance.getPrimaryIP(), null);
assertEquals(instance.getHostname(), null);
assertEquals(instance.getStatus(), Instance.Status.NEW); assertEquals(instance.getStatus(), Instance.Status.NEW);
} }
private void assertIpHostAndStatusNEW(Instance instance) { private void assertIpHostAndStatusNEW(Instance instance) {
assertNotNull(instance.getIp()); assertNotNull(instance.getPrimaryIP());
assertNotNull(instance.getHostname());
assertEquals(instance.getStatus(), Instance.Status.NEW); assertEquals(instance.getStatus(), Instance.Status.NEW);
} }
private void assertIpHostAndStatusACTIVE(Instance instance) { private void assertIpHostAndStatusACTIVE(Instance instance) {
assertNotNull(instance.getIp()); assertNotNull(instance.getPrimaryIP());
assertNotNull(instance.getHostname());
assertEquals(instance.getStatus(), Instance.Status.ACTIVE); assertEquals(instance.getStatus(), Instance.Status.ACTIVE);
} }
@Test(dependsOnMethods = { "testAddPublicKey", "testAllocateIpAddress", "testCreateVolume", @Test(dependsOnMethods = { "testAddPublicKey", "testAllocateIpAddress", "testCreateVolume",
"resolveImageAndInstanceType" }) "resolveImageAndInstanceType" })
public void testCreateInstanceWithIpAndVolume() throws Exception { public void testCreateInstanceWithIpAndVolume() throws Exception {
String name = TAG + "1"; String name = GROUP + "1";
killInstance(name); killInstance(name);
instance2 = connection.createInstanceInLocation(location.getId(), name, image.getId(), instanceType.getId(), instance2 = connection.createInstanceInLocation(location.getId(), name, image.getId(), instanceType.getId(),
attachIp(ip.getId()).authorizePublicKey(key.getName()).mountVolume(volume.getId(), "/mnt")); secondaryIP(ip.getId()).isMiniEphemeral(true).authorizePublicKey(key.getName()).mountVolume(
volume.getId(), "/mnt"));
assertBeginState(instance2, name); assertBeginState(instance2, name);
assertIpHostAndStatusNEW(instance2); assertIpHostAndStatusNEW(instance2);
@ -539,8 +424,8 @@ public class IBMDeveloperCloudClientLiveTest {
refreshIpAndReturnAllAddresses(); refreshIpAndReturnAllAddresses();
assertEquals(ip.getInstanceId(), instance2.getId()); assertEquals(ip.getInstanceId(), instance2.getId());
assertEquals(ip.getIp(), instance2.getIp()); assertEquals(ip.getIP(), instance2.getPrimaryIP().getIP());
sshAndDf(new IPSocket(instance2.getIp(), 22), new Credentials("idcuser", keyPair.get("private"))); sshAndDf(new IPSocket(instance2.getPrimaryIP().getIP(), 22), new Credentials("idcuser", keyPair.get("private")));
} }
private Set<? extends Address> refreshIpAndReturnAllAddresses() { private Set<? extends Address> refreshIpAndReturnAllAddresses() {
@ -609,36 +494,22 @@ public class IBMDeveloperCloudClientLiveTest {
private void _sshAndDf(IPSocket socket, Credentials credentials) { private void _sshAndDf(IPSocket socket, Credentials credentials) {
RetryablePredicate<IPSocket> socketOpen = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 180, RetryablePredicate<IPSocket> socketOpen = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 180,
5, TimeUnit.SECONDS); 5, TimeUnit.SECONDS);
socketOpen.apply(socket); socketOpen.apply(socket);
SshClient ssh = new JschSshClient(new BackoffLimitedRetryHandler(), socket, 60000, credentials.identity, null, SshClient ssh = new JschSshClient(new BackoffLimitedRetryHandler(), socket, 60000, credentials.identity, null,
credentials.credential.getBytes()); credentials.credential.getBytes());
try { try {
ssh.connect(); ssh.connect();
ExecResponse hello = ssh.exec("echo hello"); ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello"); assertEquals(hello.getOutput().trim(), "hello");
ExecResponse exec = ssh.exec("df"); ExecResponse exec = ssh.exec("df");
assertTrue(exec.getOutput().contains("Filesystem"), assertTrue(exec.getOutput().contains("Filesystem"),
"The output should've contained filesystem information, but it didn't. Output: " + exec); "The output should've contained filesystem information, but it didn't. Output: " + exec);
} finally { } finally {
if (ssh != null) if (ssh != null)
ssh.disconnect(); ssh.disconnect();
} }
} }
@BeforeGroups(groups = { "live" })
protected void setupKeyPair() throws FileNotFoundException, IOException {
String secretKeyFile;
try {
secretKeyFile = checkNotNull(System.getProperty("jclouds.test.ssh.keyfile"), "jclouds.test.ssh.keyfile");
} catch (NullPointerException e) {
secretKeyFile = System.getProperty("user.home") + "/.ssh/id_rsa";
}
String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8);
assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret;
keyPair = ImmutableMap.<String, String> of("private", secret, "public", Files.toString(new File(secretKeyFile
+ ".pub"), Charsets.UTF_8));
}
} }

View File

@ -16,7 +16,7 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev; package org.jclouds.ibm.smartcloud;
import org.jclouds.compute.util.ComputeServiceUtils; import org.jclouds.compute.util.ComputeServiceUtils;
import org.jclouds.rest.Providers; import org.jclouds.rest.Providers;
@ -35,13 +35,13 @@ public class ProvidersInPropertiesTest {
@Test @Test
public void testSupportedProviders() { public void testSupportedProviders() {
Iterable<String> providers = Providers.getSupportedProviders(); Iterable<String> providers = Providers.getSupportedProviders();
assert Iterables.contains(providers, "ibmdev") : providers; assert Iterables.contains(providers, "ibm-smartcloud") : providers;
} }
@Test @Test
public void testSupportedComputeServiceProviders() { public void testSupportedComputeServiceProviders() {
Iterable<String> providers = ComputeServiceUtils.getSupportedProviders(); Iterable<String> providers = ComputeServiceUtils.getSupportedProviders();
assert Iterables.contains(providers, "ibmdev") : providers; assert Iterables.contains(providers, "ibm-smartcloud") : providers;
} }
} }

View File

@ -0,0 +1,125 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.util.Set;
import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.ibm.smartcloud.domain.Location;
import org.jclouds.ibm.smartcloud.domain.Volume;
import org.testng.annotations.Test;
import com.google.common.collect.Iterables;
/**
* Tests behavior of {@code IBMSmartCloudClient}
*
* @author Adrian Cole
*/
@Test(groups = "live", testName = "IBMSmartCloudClientLiveTest")
public class ReadOnlyIBMSmartCloudClientLiveTest extends BaseIBMSmartCloudClientLiveTest {
@Test
public void testListImages() throws Exception {
Set<? extends Image> response = connection.listImages();
assertNotNull(response);
}
@Test
public void testGetImage() throws Exception {
Set<? extends Image> response = connection.listImages();
assertNotNull(response);
if (response.size() > 0) {
Image image = Iterables.get(response, 0);
assertEquals(connection.getImage(image.getId()).getId(), image.getId());
}
}
@Test
public void testListInstances() throws Exception {
Set<? extends Instance> response = connection.listInstances();
assertNotNull(response);
}
@Test
public void testListInstancesFromRequestReturnsEmptySet() throws Exception {
Set<? extends Instance> response = connection.listInstancesFromRequest(Long.MAX_VALUE + "");
assertEquals(response.size(), 0);
}
@Test
public void testGetInstance() throws Exception {
Set<? extends Instance> response = connection.listInstances();
assertNotNull(response);
if (response.size() > 0) {
Instance instance = Iterables.get(response, 0);
assertEquals(connection.getInstance(instance.getId()).getId(), instance.getId());
}
}
@Test
public void testListKeys() throws Exception {
Set<? extends Key> response = connection.listKeys();
assertNotNull(response);
}
@Test
public void testGetKey() throws Exception {
Set<? extends Key> response = connection.listKeys();
assertNotNull(response);
if (response.size() > 0) {
Key key = Iterables.get(response, 0);
assertEquals(connection.getKey(key.getName()).getName(), key.getName());
}
}
@Test
public void testListVolumes() throws Exception {
Set<? extends Volume> response = connection.listVolumes();
assertNotNull(response);
}
@Test
public void testGetVolume() throws Exception {
Set<? extends Volume> response = connection.listVolumes();
assertNotNull(response);
if (response.size() > 0) {
Volume image = Iterables.get(response, 0);
assertEquals(connection.getVolume(image.getId()).getId(), image.getId());
}
}
@Test
public void testListLocations() throws Exception {
Set<? extends Location> response = connection.listLocations();
assertNotNull(response);
}
@Test
public void testListAddresss() throws Exception {
Set<? extends Address> response = connection.listAddresses();
assertNotNull(response);
}
}

View File

@ -16,31 +16,27 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibm.smartcloud.compute;
import javax.inject.Inject; import org.jclouds.compute.BaseComputeServiceLiveTest;
import javax.inject.Singleton; import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.BeforeClass;
import org.jclouds.http.HttpResponse; import org.testng.annotations.Test;
import org.jclouds.ibmdev.domain.Instance;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Test(groups = "live", enabled = true, singleThreaded = true, testName = "IBMSmartCloudComputeServiceLiveTest")
public class GetFirstInstanceInList implements Function<HttpResponse, Instance> { public class IBMSmartCloudComputeServiceLiveTest extends BaseComputeServiceLiveTest {
private ParseInstancesFromJson listParser;
@Inject @BeforeClass
public GetFirstInstanceInList(ParseInstancesFromJson mapper) { @Override
this.listParser = mapper; public void setServiceDefaults() {
provider = "ibm-smartcloud";
} }
@Override @Override
public Instance apply(HttpResponse from) { protected JschSshClientModule getSshModule() {
return Iterables.getOnlyElement(listParser.apply(from)); return new JschSshClientModule();
} }
} }

View File

@ -0,0 +1,83 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.compute;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Set;
import org.jclouds.compute.BaseTemplateBuilderLiveTest;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.OsFamilyVersion64Bit;
import org.jclouds.compute.domain.Template;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
/**
*
* @author Adrian Cole
*/
@Test(groups = "live", testName = "IBMSmartCloudTemplateBuilderLiveTest")
public class IBMSmartCloudTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {
public IBMSmartCloudTemplateBuilderLiveTest() {
provider = "ibm-smartcloud";
}
@Override
protected Predicate<OsFamilyVersion64Bit> defineUnsupportedOperatingSystems() {
return new Predicate<OsFamilyVersion64Bit>() {
@Override
public boolean apply(OsFamilyVersion64Bit input) {
switch (input.family) {
case SUSE:
return !input.version.equals("") && !input.version.equals("11") && !input.version.equals("11 SP1");
case RHEL:
return !input.version.equals("") && !input.version.equals("5.4") && !input.version.equals("5.5");
case WINDOWS:
return !input.version.equals("") && !(input.version.equals("2008 R2") && input.is64Bit)
&& !input.version.equals("2008 R1") && !input.version.equals("2003 R2");
default:
return true;
}
}
};
}
@Override
public void testDefaultTemplateBuilder() throws IOException {
Template defaultTemplate = context.getComputeService().templateBuilder().build();
assertEquals(defaultTemplate.getLocation().getIso3166Codes(), ImmutableSet.of("CA-ON"));
assertEquals(defaultTemplate.getImage().getId(), "20015393");
assertEquals(defaultTemplate.getHardware().getId(), "20015393/COP32.1/2048/60");
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "11 SP1");
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), false);
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.SUSE);
}
@Override
protected Set<String> getIso3166Codes() {
return ImmutableSet.of("US-NC", "DE-BW", "US-CO", "CA-ON", "JP-12", "SG");
}
}

View File

@ -16,42 +16,40 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibm.smartcloud.parse;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import org.jclouds.http.HttpResponse; import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule; import org.jclouds.io.Payload;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
import org.testng.annotations.BeforeTest; import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Tests behavior of {@code ParseExpirationTimeFromJson}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", sequential = true, testName = "ibmdev.ParseExpirationTimeFromJsonTest") @Test(groups = "unit", testName = "ExtendReservationForInstanceTest")
public class ParseExpirationTimeFromJsonTest { public class ExtendReservationForInstanceTest extends BaseItemParserTest<Date> {
private ParseExpirationTimeFromJson handler; protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
@BeforeTest
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new IBMDeveloperCloudParserModule(), new GsonModule());
handler = injector.getInstance(ParseExpirationTimeFromJson.class);
} }
public void test() { @Override
Date compare = handler.apply(new HttpResponse(200, "ok", Payloads protected Payload payload() {
.newStringPayload("{ \"expirationTime\":1249876800000 }"))); return Payloads.newStringPayload("{ \"expirationTime\":1249876800000 }");
assertEquals(compare, new Date(1249876800000l)); }
@Override
@Unwrap
public Date expected() {
return new Date(1249876800000l);
} }
} }

View File

@ -16,22 +16,26 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.compute.config; package org.jclouds.ibm.smartcloud.parse;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.json.BaseItemParserTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
*
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "ibmdev.IBMDeveloperCloudComputeServiceDependenciesModuleTest") @Test(groups = "unit", testName = "GetAddressTest")
public class IBMDeveloperCloudComputeServiceDependenciesModuleTest { public class GetAddressTest extends BaseItemParserTest<Address> {
public void testAllStatusCovered() { @Override
public String resource() {
for (Instance.Status state : Instance.Status.values()) { return "/address.json";
assert IBMDeveloperCloudComputeServiceDependenciesModule.instanceStatusToNodeState.containsKey(state) : state; }
}
@Override
public Address expected() {
return new Address(2, "1", "129.33.196.243", "1217", "1");
} }
} }

View File

@ -0,0 +1,76 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import org.jclouds.http.HttpUtils;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibm.smartcloud.domain.InstanceType;
import org.jclouds.ibm.smartcloud.domain.Price;
import org.jclouds.ibm.smartcloud.domain.Image.Visibility;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "GetImageTest")
public class GetImageTest extends BaseItemParserTest<Image> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/image.json";
}
@Override
public Image expected() {
return new Image(
"SUSE Linux Enterprise Server 11 for x86",
HttpUtils
.createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/parameters.xml"),
Image.State.AVAILABLE,
Visibility.PUBLIC,
"SYSTEM",
"SUSE Linux Enterprise Server/11",
Image.Architecture.I386,
new Date(1216944000000l),
"41",
ImmutableSet.<InstanceType> of(new InstanceType("Bronze 32 bit", new Price(0.17, "UHR ", "897", null,
"USD", 1), "BRZ32.1/2048/175"), new InstanceType("Gold 32 bit", new Price(0.41, "UHR ", "897",
null, "USD", 1), "GLD32.4/4096/350"), new InstanceType("Silver 32 bit", new Price(0.265,
"UHR ", "897", null, "USD", 1), "SLV32.2/4096/350")),
ImmutableSet.<String> of("ifeE7VOzRG6SGvoDlRPTQw"),
HttpUtils
.createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/GettingStarted.html"),
"20001150", "SUSE Linux Enterprise Server 11 for x86 Base OS 32-bit with pay for use licensing");
}
}

View File

@ -0,0 +1,61 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.IP;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibm.smartcloud.domain.Instance.Software;
import org.jclouds.ibm.smartcloud.domain.Instance.Status;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "GetInstanceTest")
public class GetInstanceTest extends BaseItemParserTest<Instance> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/instance.json";
}
@Override
public Instance expected() {
return Instance.builder().launchTime(new Date(1305351683883l)).software(
ImmutableSet.of(new Software("SUSE Linux Enterprise Server", "OS", "11 SP1"))).primaryIP(
new IP(" ", " ", 0)).requestId("80890").keyName("adriancole").name(
"adriancole").instanceType("COP32.1/2048/60").status(Status.NEW).owner("adrian@cloudconscious.com")
.location("101").imageId("20015393").rootOnly(true).requestName("adriancole").id("80590")
.expirationTime(new Date(1368423692824l)).diskSize(60).build();
}
}

View File

@ -0,0 +1,54 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "GetKeyTest")
public class GetKeyTest extends BaseItemParserTest<Key> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/key.json";
}
@Override
public Key expected() {
return new Key(true, ImmutableSet.<String> of("1"), "AAAB3NzaC1yc2EAAAADAQABAAABAQCqBw7a+...", "DEFAULT",
new Date(1260428507510l));
}
}

View File

@ -0,0 +1,50 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Volume;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
@Test(groups = "unit", testName = "GetVolumeTest")
public class GetVolumeTest extends BaseItemParserTest<Volume> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/volume.json";
}
@Override
public Volume expected() {
return new Volume("2", 5, 50, "aadelucc@us.ibm.com", new Date(1260469075119l), "1", ImmutableSet.<String> of(),
"ext3", "New Storage", "67");
}
}

View File

@ -16,34 +16,33 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibm.smartcloud.parse;
import javax.inject.Inject; import java.util.Set;
import javax.inject.Singleton;
import org.jclouds.http.HttpResponse; import org.jclouds.ibm.smartcloud.domain.Address;
import org.jclouds.http.functions.ParseJson; import org.jclouds.json.BaseSetParserTest;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.collect.ImmutableSet;
/** /**
*
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Test(groups = "unit", testName = "ListAddressesTest")
public class ParseImageFromJson implements Function<HttpResponse, Image> { public class ListAddressesTest extends BaseSetParserTest<Address> {
private final ParseJson<Image> json; @Override
public String resource() {
@Inject return "/addresses.json";
ParseImageFromJson(ParseJson<Image> json) {
this.json = json;
} }
@Override @Override
public Image apply(HttpResponse arg0) { @Unwrap
Image input = json.apply(arg0); public Set<Address> expected() {
ParseUtils.CLEAN_IMAGE.apply(input); return ImmutableSet.of(new Address(2, "1", "129.33.196.243", "1217", "1"), new Address(3, "2", "129.33.196.244",
return input; "1218", null));
} }
} }

View File

@ -0,0 +1,80 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import java.util.Set;
import org.jclouds.http.HttpUtils;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Image;
import org.jclouds.ibm.smartcloud.domain.InstanceType;
import org.jclouds.ibm.smartcloud.domain.Price;
import org.jclouds.ibm.smartcloud.domain.Image.Visibility;
import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", singleThreaded = true, testName = "ListImagesTest")
public class ListImagesTest extends BaseSetParserTest<Image> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/images.json";
}
@Override
@Unwrap
public Set<Image> expected() {
return ImmutableSet
.of(new Image(
"SUSE Linux Enterprise Server 11 for x86",
HttpUtils
.createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/parameters.xml"),
Image.State.AVAILABLE,
Visibility.PUBLIC,
"SYSTEM",
"SUSE Linux Enterprise Server/11",
Image.Architecture.X86_64,
new Date(1216944000000l),
"41",
ImmutableSet.<InstanceType> of(new InstanceType("Bronze 32 bit", new Price(0.17, "UHR ",
"897", null, "USD", 1), "BRZ32.1/2048/175"), new InstanceType("Gold 32 bit",
new Price(0.41, "UHR ", "897", null, "USD", 1), "GLD32.4/4096/350"),
new InstanceType("Silver 32 bit", new Price(0.265, "UHR ", "897", null, "USD", 1),
"SLV32.2/4096/350")),
ImmutableSet.<String> of("ifeE7VOzRG6SGvoDlRPTQw"),
HttpUtils
.createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/GettingStarted.html"),
"20001150", "SUSE Linux Enterprise Server 11 for x86 Base OS 32-bit with pay for use licensing"));
}
}

View File

@ -0,0 +1,66 @@
/**
*
* Copyright (C) 2011 Cloud Conscious) LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License) Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing) software
* distributed under the License is distributed on an "AS IS" BASIS)
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND) either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import java.util.Set;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.IP;
import org.jclouds.ibm.smartcloud.domain.Instance;
import org.jclouds.ibm.smartcloud.domain.Instance.Software;
import org.jclouds.ibm.smartcloud.domain.Instance.Status;
import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ListInstancesTest")
public class ListInstancesTest extends BaseSetParserTest<Instance> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/instances.json";
}
@Override
@Unwrap
public Set<Instance> expected() {
return ImmutableSet.of(Instance.builder().launchTime(new Date(1305351683883l)).software(
ImmutableSet.of(new Software("SUSE Linux Enterprise Server", "OS", "11 SP1"))).primaryIP(
new IP(" ", " ", 0)).requestId("80890").keyName("adriancole").name("adriancole").instanceType(
"COP32.1/2048/60").status(Status.NEW).owner("adrian@cloudconscious.com").location("101").imageId(
"20015393").rootOnly(true).requestName("adriancole").id("80590")
.expirationTime(new Date(1368423692824l)).diskSize(60).build());
}
}

View File

@ -0,0 +1,58 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import java.util.Set;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Key;
import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ListKeyesTest")
public class ListKeysTest extends BaseSetParserTest<Key> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/keys.json";
}
@Override
@Unwrap
public Set<Key> expected() {
return ImmutableSet.of(new Key(true, ImmutableSet.<String> of("1"), "AAAB3NzaC1yc2EAAAADAQABAAABAQCqBw7a+...",
"DEFAULT", new Date(1260428507510l)), new Key(false, ImmutableSet.<String> of(),
"AAAB3NzaC1yc2EAAAADAQABAAABAQCqBw7a+", "BEAR", new Date(1260428507511l)));
}
}

View File

@ -0,0 +1,66 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import java.util.Set;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Price;
import org.jclouds.ibm.smartcloud.domain.StorageOffering;
import org.jclouds.ibm.smartcloud.domain.StorageOffering.Format;
import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ListStorageOfferingsTest")
public class ListStorageOfferingsTest extends BaseSetParserTest<StorageOffering> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/storage-offerings.json";
}
@Override
@Unwrap
public Set<StorageOffering> expected() {
return ImmutableSet.of(//
new StorageOffering("41", new Price(0.039, "UHR", "897", new Date(1279497600000l), "USD", 1), 256,
"Small", "20001208", ImmutableSet.of(new Format("ext3", "EXT3"))),//
new StorageOffering("41", new Price(0.312, "UHR", "897", new Date(1279497600000l), "USD", 1), 2048,
"Large", "20001210", ImmutableSet.of(new Format("ext3", "EXT3"))),//
new StorageOffering("41", new Price(0.078, "UHR", "897", new Date(1279497600000l), "USD", 1), 512,
"Medium", "20001209", ImmutableSet.of(new Format("ext3", "EXT3")))//
);
}
}

View File

@ -0,0 +1,57 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibm.smartcloud.parse;
import java.util.Date;
import java.util.Set;
import org.jclouds.ibm.smartcloud.config.IBMSmartCloudParserModule;
import org.jclouds.ibm.smartcloud.domain.Volume;
import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.annotations.Unwrap;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ListVolumesTest")
public class ListVolumesTest extends BaseSetParserTest<Volume> {
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new IBMSmartCloudParserModule());
}
@Override
public String resource() {
return "/volumes.json";
}
@Override
@Unwrap
public Set<Volume> expected() {
return ImmutableSet.of(new Volume("2", 5, 50, "aadelucc@us.ibm.com", new Date(1260469075119l), "1", ImmutableSet
.<String> of(), "ext3", "New Storage", "67"), new Volume(null, 6, 51, "aadelucc@us.ibm.com", new Date(
1260469075120l), "2", ImmutableSet.<String> of("abrad"), "ext3", "New Storage1", "68"));
}
}

View File

@ -4,6 +4,7 @@
"state": 1, "state": 1,
"visibility": "PUBLIC", "visibility": "PUBLIC",
"owner": "SYSTEM", "owner": "SYSTEM",
"architecture": "i386",
"platform": "SUSE Linux Enterprise Server/11", "platform": "SUSE Linux Enterprise Server/11",
"createdTime": 1216944000000, "createdTime": 1216944000000,
"location": "41", "location": "41",

View File

@ -6,6 +6,7 @@
"state": 1, "state": 1,
"visibility": "PUBLIC", "visibility": "PUBLIC",
"owner": "SYSTEM", "owner": "SYSTEM",
"architecture": "x86_64",
"platform": "SUSE Linux Enterprise Server/11", "platform": "SUSE Linux Enterprise Server/11",
"createdTime": 1216944000000, "createdTime": 1216944000000,
"location": "41", "location": "41",

View File

@ -0,0 +1,29 @@
{
"launchTime": 1305351683883,
"software": [{
"version": "11 SP1",
"type": "OS",
"name": "SUSE Linux Enterprise Server"
}],
"primaryIP": {
"hostname": " ",
"ip": " ",
"type": 0
},
"requestId": "80890",
"keyName": "adriancole",
"name": "adriancole",
"instanceType": "COP32.1/2048/60",
"status": 0,
"owner": "adrian@cloudconscious.com",
"location": "101",
"imageId": "20015393",
"root-only": "true",
"productCodes": [],
"volumes": [],
"requestName": "adriancole",
"id": "80590",
"secondaryIP": [],
"expirationTime": 1368423692824,
"diskSize": "60"
}

View File

@ -0,0 +1,31 @@
{
"instances": [{
"launchTime": 1305351683883,
"software": [{
"version": "11 SP1",
"type": "OS",
"name": "SUSE Linux Enterprise Server"
}],
"primaryIP": {
"hostname": " ",
"ip": " ",
"type": 0
},
"requestId": "80890",
"keyName": "adriancole",
"name": "adriancole",
"instanceType": "COP32.1/2048/60",
"status": 0,
"owner": "adrian@cloudconscious.com",
"location": "101",
"imageId": "20015393",
"root-only": "true",
"productCodes": [],
"volumes": [],
"requestName": "adriancole",
"id": "80590",
"secondaryIP": [],
"expirationTime": 1368423692824,
"diskSize": "60"
}]
}

Some files were not shown because too many files have changed in this diff Show More