joyent now w/keypair & metadata works in computeservice

This commit is contained in:
Adrian Cole 2012-06-14 23:02:20 -04:00
parent 6cb7829b1b
commit 05bf76d589
43 changed files with 1176 additions and 219 deletions

View File

@ -23,6 +23,7 @@ import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.joyent.sdc.v6_5.features.DatacenterAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.DatasetAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.KeyAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.MachineAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.PackageAsyncClient;
import org.jclouds.location.Zone;
@ -56,6 +57,12 @@ public interface SDCAsyncClient {
@Delegate
DatacenterAsyncClient getDatacenterClient();
/**
* Provides asynchronous access to Key features.
*/
@Delegate
KeyAsyncClient getKeyClient();
/**
* Provides asynchronous access to Machine features.
*/

View File

@ -25,6 +25,7 @@ import org.jclouds.concurrent.Timeout;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.joyent.sdc.v6_5.features.DatacenterClient;
import org.jclouds.joyent.sdc.v6_5.features.DatasetClient;
import org.jclouds.joyent.sdc.v6_5.features.KeyClient;
import org.jclouds.joyent.sdc.v6_5.features.MachineClient;
import org.jclouds.joyent.sdc.v6_5.features.PackageClient;
import org.jclouds.location.Zone;
@ -58,7 +59,13 @@ public interface SDCClient {
*/
@Delegate
DatacenterClient getDatacenterClient();
/**
* Provides synchronous access to Key features.
*/
@Delegate
KeyClient getKeyClient();
/**
* Provides synchronous access to Machine features.
*/

View File

@ -0,0 +1,54 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.binders;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.http.HttpRequest;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
import org.jclouds.json.Json;
import org.jclouds.rest.binders.BindToJsonPayload;
/**
*
* @author Adrian Cole
*
*/
@Singleton
public class BindKeyToJsonPayload extends BindToJsonPayload {
@Inject
public BindKeyToJsonPayload(Json jsonBinder) {
super(jsonBinder);
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
// don't include created in the http request
return super.bindToRequest(request, Key.class.cast(toBind).toBuilder().created(null).build());
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
throw new IllegalStateException("This should be assigned only a single arg");
}
}

View File

@ -20,6 +20,7 @@ package org.jclouds.joyent.sdc.v6_5.compute;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;
import java.util.Set;
@ -77,16 +78,16 @@ public class SDCComputeServiceAdapter implements
LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder();
CreateMachineOptions options = new CreateMachineOptions();
// TODO: assign template.getOptions.metadata/tags
options.name(name);
options.packageName(template.getHardware().getProviderId());
options.metadata(metadataAndTagsAsCommaDelimitedValue(template.getOptions()));
String datacenterId = template.getLocation().getId();
String datasetId = template.getImage().getProviderId();
String packageId = template.getHardware().getProviderId();
String datasetURN = template.getImage().getProviderId();
logger.debug(">> creating new machine datacenter(%s) name(%s) package(%s) dataset(%s) options(%s)", datacenterId,
name, packageId, datasetId, options);
Machine machine = sdcClient.getMachineClientForDatacenter(datacenterId).createMachine(name, packageId, datasetId,
logger.debug(">> creating new machine datacenter(%s) datasetURN(%s) options(%s)", datacenterId, datasetURN,
options);
Machine machine = sdcClient.getMachineClientForDatacenter(datacenterId).createWithDataset(datasetURN, options);
logger.trace("<< machine(%s)", machine.getId());
@ -102,7 +103,7 @@ public class SDCComputeServiceAdapter implements
public Iterable<PackageInDatacenter> listHardwareProfiles() {
Builder<PackageInDatacenter> builder = ImmutableSet.builder();
for (final String datacenterId : datacenterIds.get()) {
builder.addAll(transform(sdcClient.getPackageClientForDatacenter(datacenterId).listPackages(),
builder.addAll(transform(sdcClient.getPackageClientForDatacenter(datacenterId).list(),
new Function<org.jclouds.joyent.sdc.v6_5.domain.Package, PackageInDatacenter>() {
@Override
@ -119,7 +120,7 @@ public class SDCComputeServiceAdapter implements
public Iterable<DatasetInDatacenter> listImages() {
Builder<DatasetInDatacenter> builder = ImmutableSet.builder();
for (final String datacenterId : datacenterIds.get()) {
builder.addAll(transform(sdcClient.getDatasetClientForDatacenter(datacenterId).listDatasets(),
builder.addAll(transform(sdcClient.getDatasetClientForDatacenter(datacenterId).list(),
new Function<Dataset, DatasetInDatacenter>() {
@Override
@ -136,7 +137,7 @@ public class SDCComputeServiceAdapter implements
public Iterable<MachineInDatacenter> listNodes() {
Builder<MachineInDatacenter> builder = ImmutableSet.builder();
for (final String datacenterId : datacenterIds.get()) {
builder.addAll(transform(sdcClient.getMachineClientForDatacenter(datacenterId).listMachines(),
builder.addAll(transform(sdcClient.getMachineClientForDatacenter(datacenterId).list(),
new Function<Machine, MachineInDatacenter>() {
@Override
@ -158,7 +159,7 @@ public class SDCComputeServiceAdapter implements
@Override
public MachineInDatacenter getNode(String id) {
DatacenterAndId datacenterAndId = DatacenterAndId.fromSlashEncoded(id);
Machine machine = sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).getMachine(
Machine machine = sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).get(
datacenterAndId.getId());
return machine == null ? null : new MachineInDatacenter(machine, datacenterAndId.getDatacenter());
}
@ -166,7 +167,7 @@ public class SDCComputeServiceAdapter implements
@Override
public DatasetInDatacenter getImage(String id) {
DatacenterAndId datacenterAndId = DatacenterAndId.fromSlashEncoded(id);
Dataset dataset = sdcClient.getDatasetClientForDatacenter(datacenterAndId.getDatacenter()).getDataset(
Dataset dataset = sdcClient.getDatasetClientForDatacenter(datacenterAndId.getDatacenter()).get(
datacenterAndId.getId());
return dataset == null ? null : new DatasetInDatacenter(dataset, datacenterAndId.getDatacenter());
}
@ -174,26 +175,26 @@ public class SDCComputeServiceAdapter implements
@Override
public void destroyNode(String id) {
DatacenterAndId datacenterAndId = DatacenterAndId.fromSlashEncoded(id);
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).deleteMachine(datacenterAndId.getId());
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).delete(datacenterAndId.getId());
}
@Override
public void rebootNode(String id) {
DatacenterAndId datacenterAndId = DatacenterAndId.fromSlashEncoded(id);
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).rebootMachine(datacenterAndId.getId());
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).reboot(datacenterAndId.getId());
}
@Override
public void resumeNode(String id) {
DatacenterAndId datacenterAndId = DatacenterAndId.fromSlashEncoded(id);
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).stopMachine(datacenterAndId.getId());
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).stop(datacenterAndId.getId());
}
@Override
public void suspendNode(String id) {
DatacenterAndId datacenterAndId = DatacenterAndId.fromSlashEncoded(id);
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).startMachine(datacenterAndId.getId());
sdcClient.getMachineClientForDatacenter(datacenterAndId.getDatacenter()).start(datacenterAndId.getId());
}

View File

@ -109,9 +109,12 @@ public class SDCComputeServiceContextModule extends
@VisibleForTesting
public static final Map<Machine.State, NodeMetadata.Status> toPortableNodeStatus = ImmutableMap
.<Machine.State, NodeMetadata.Status> builder()
.put(Machine.State.PROVISIONING, NodeMetadata.Status.PENDING)
.put(Machine.State.RUNNING, NodeMetadata.Status.RUNNING)
.put(Machine.State.STOPPING, NodeMetadata.Status.PENDING)
.put(Machine.State.OFFLINE, NodeMetadata.Status.PENDING)
.put(Machine.State.STOPPED, NodeMetadata.Status.SUSPENDED)
.put(Machine.State.PUBLISHING, NodeMetadata.Status.PENDING)
.put(Machine.State.DELETED, NodeMetadata.Status.TERMINATED)
.put(Machine.State.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).build();
@Singleton

View File

@ -56,7 +56,7 @@ public class DatasetInDatacenterToImage implements Function<DatasetInDatacenter,
Location location = locationIndex.get().get(datasetInDatacenter.getDatacenter());
checkState(location != null, "location %s not in locationIndex: %s", datasetInDatacenter.getDatacenter(),
locationIndex.get());
Dataset dataset = datasetInDatacenter.getDataset();
Dataset dataset = datasetInDatacenter.get();
return new ImageBuilder()
.id(datasetInDatacenter.slashEncode())
.providerId(dataset.getId())

View File

@ -17,11 +17,12 @@
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.tryFind;
import static com.google.common.collect.Maps.filterKeys;
import static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromCommaDelimitedValue;
import static org.jclouds.compute.util.ComputeServiceUtils.getSpace;
@ -46,12 +47,12 @@ import org.jclouds.joyent.sdc.v6_5.domain.Machine;
import org.jclouds.joyent.sdc.v6_5.domain.datacenterscoped.DatacenterAndId;
import org.jclouds.joyent.sdc.v6_5.domain.datacenterscoped.DatacenterAndName;
import org.jclouds.joyent.sdc.v6_5.domain.datacenterscoped.MachineInDatacenter;
import org.jclouds.joyent.sdc.v6_5.reference.MetadataKeys;
import org.jclouds.logging.Logger;
import org.jclouds.util.InetAddresses2;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
/**
@ -87,7 +88,7 @@ public class MachineInDatacenterToNodeMetadata implements Function<MachineInData
Location zone = locationIndex.get().get(machineInDatacenter.getDatacenter());
checkState(zone != null, "location %s not in locationIndex: %s", machineInDatacenter.getDatacenter(),
locationIndex.get());
Machine from = machineInDatacenter.getMachine();
Machine from = machineInDatacenter.get();
NodeMetadataBuilder builder = new NodeMetadataBuilder();
builder.id(machineInDatacenter.slashEncode());
@ -95,14 +96,25 @@ public class MachineInDatacenterToNodeMetadata implements Function<MachineInData
builder.name(from.getName());
builder.hostname(from.getName());
builder.location(zone);
addMetadataAndParseTagsFromCommaDelimitedValue(builder, from.getMetadata());
addMetadataAndParseTagsFromCommaDelimitedValue(builder, filterKeys(from.getMetadata(), new Predicate<String>() {
@Override
public boolean apply(String input) {
// TODO make this more efficient
for (MetadataKeys key : MetadataKeys.values())
if (key.key().equals(input))
return false;
return true;
}
}));
builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName()));
builder.imageId(DatacenterAndName.fromDatacenterAndName(machineInDatacenter.getDatacenter(), from.getDataset())
builder.imageId(DatacenterAndName.fromDatacenterAndName(machineInDatacenter.getDatacenter(), from.get())
.slashEncode());
builder.operatingSystem(findOperatingSystemForMachineOrNull(machineInDatacenter));
builder.hardware(findHardwareForMachineOrNull(machineInDatacenter));
builder.status(toPortableNodeStatus.get(from.getState()));
builder.publicAddresses(filter(from.getIps(), Predicates.not(InetAddresses2.IsPrivateIPAddress.INSTANCE)));
builder.publicAddresses(filter(from.getIps(), not(InetAddresses2.IsPrivateIPAddress.INSTANCE)));
builder.privateAddresses(filter(from.getIps(), InetAddresses2.IsPrivateIPAddress.INSTANCE));
return builder.build();
}
@ -111,16 +123,16 @@ public class MachineInDatacenterToNodeMetadata implements Function<MachineInData
return tryFind(hardwares.get(), new Predicate<Hardware>() {
@Override
public boolean apply(Hardware input) {
return input.getRam() == machineInDatacenter.getMachine().getMemorySizeMb()
&& getSpace(input) == machineInDatacenter.getMachine().getDiskSizeGb()
return input.getRam() == machineInDatacenter.get().getMemorySizeMb()
&& getSpace(input) == machineInDatacenter.get().getDiskSizeGb()
&& input.getLocation().getId().equals(machineInDatacenter.getDatacenter());
}
}).orNull();
}
protected OperatingSystem findOperatingSystemForMachineOrNull(MachineInDatacenter machineInDatacenter) {
Image image = findObjectOfTypeForMachineOrNull(images.get(), "image", machineInDatacenter.getMachine()
.getDataset(), machineInDatacenter);
Image image = findObjectOfTypeForMachineOrNull(images.get(), "image", machineInDatacenter.get()
.get(), machineInDatacenter);
return (image != null) ? image.getOperatingSystem() : null;
}

View File

@ -55,7 +55,7 @@ public class PackageInDatacenterToHardware implements Function<PackageInDatacent
Location location = locationIndex.get().get(pkgInDatacenter.getDatacenter());
checkState(location != null, "location %s not in locationIndex: %s", pkgInDatacenter.getDatacenter(),
locationIndex.get());
org.jclouds.joyent.sdc.v6_5.domain.Package pkg = pkgInDatacenter.getPackage();
org.jclouds.joyent.sdc.v6_5.domain.Package pkg = pkgInDatacenter.get();
return new HardwareBuilder().id(pkgInDatacenter.slashEncode()).providerId(pkg.getName()).name(pkg.getName())
.ram(pkg.getMemorySizeMb())
// TODO: no api call to get processors.. either hard-code or

View File

@ -30,6 +30,8 @@ import org.jclouds.joyent.sdc.v6_5.features.DatacenterAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.DatacenterClient;
import org.jclouds.joyent.sdc.v6_5.features.DatasetAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.DatasetClient;
import org.jclouds.joyent.sdc.v6_5.features.KeyAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.KeyClient;
import org.jclouds.joyent.sdc.v6_5.features.MachineAsyncClient;
import org.jclouds.joyent.sdc.v6_5.features.MachineClient;
import org.jclouds.joyent.sdc.v6_5.features.PackageAsyncClient;
@ -51,6 +53,7 @@ import com.google.common.collect.ImmutableMap;
public class SDCRestClientModule extends RestClientModule<SDCClient, SDCAsyncClient> {
public static final Map<Class<?>, Class<?>> DELEGATE_MAP = ImmutableMap.<Class<?>, Class<?>> builder()
.put(DatacenterClient.class, DatacenterAsyncClient.class)
.put(KeyClient.class, KeyAsyncClient.class)
.put(MachineClient.class, MachineAsyncClient.class)
.put(DatasetClient.class, DatasetAsyncClient.class)
.put(PackageClient.class, PackageAsyncClient.class).build();

View File

@ -0,0 +1,109 @@
package org.jclouds.joyent.sdc.v6_5.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Date;
import com.google.common.base.Objects;
/**
* Keys are the means by which you operate on your SSH/signing keys. Currently
* CloudAPI supports uploads of public keys in the OpenSSH format.
*
* @author Adrian Cole
* @see <a href="http://apidocs.joyent.com/sdcapidoc/cloudapi/#keys" >docs</a>
*/
public class Key implements Comparable<Key> {
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return builder().fromKey(this);
}
public static class Builder {
private String name;
private String key;
private Date created;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder key(String key) {
this.key = key;
return this;
}
public Builder created(Date created) {
this.created = created;
return this;
}
public Key build() {
return new Key(name, key, created);
}
public Builder fromKey(Key in) {
return name(in.getName()).key(in.get()).created(in.getCreated());
}
}
protected final String name;
protected final String key;
protected final Date created;
public Key(String name, String key, Date created) {
this.name = checkNotNull(name, "name");
this.key = checkNotNull(key, "key: OpenSSH formatted public key");
this.created = created;
}
/**
* Name for this key
*/
public String getName() {
return name;
}
/**
* OpenSSH formatted public key
*/
public String get() {
return key;
}
public Date getCreated() {
return created;
}
@Override
public int compareTo(Key other) {
return name.compareTo(other.getName());
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Key) {
return Objects.equal(name, ((Key) object).name);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public String toString() {
return String.format("[name=%s, key=%s, created=%s]", name, key, created);
}
}

View File

@ -24,10 +24,18 @@ import java.util.Date;
import java.util.Map;
import java.util.Set;
import org.jclouds.domain.JsonBall;
import org.jclouds.joyent.sdc.v6_5.reference.MetadataKeys;
import org.jclouds.json.Json;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.gson.annotations.SerializedName;
/**
@ -39,7 +47,7 @@ import com.google.gson.annotations.SerializedName;
public class Machine implements Comparable<Machine> {
public static enum State {
PUBLISHING, RUNNING, STOPPED, UNRECOGNIZED;
PROVISIONING, RUNNING, STOPPING, STOPPED, OFFLINE, DELETED, UNRECOGNIZED;
public static State fromValue(String state) {
try {
@ -74,7 +82,7 @@ public class Machine implements Comparable<Machine> {
private Set<String> ips;
private Date created;
private Date updated;
private Map<String, String> metadata = ImmutableMap.of();
private Map<String, JsonBall> metadata = ImmutableMap.of();
public Builder id(String id) {
this.id = id;
@ -129,7 +137,7 @@ public class Machine implements Comparable<Machine> {
/**
* @see Machine#getMetadata()
*/
public Builder metadata(Map<String, String> metadata) {
public Builder metadata(Map<String, JsonBall> metadata) {
this.metadata = metadata;
return this;
}
@ -139,9 +147,9 @@ public class Machine implements Comparable<Machine> {
}
public Builder fromMachine(Machine in) {
return id(in.getId()).name(in.getName()).type(in.getType()).state(in.getState()).dataset(in.getDataset())
return id(in.getId()).name(in.getName()).type(in.getType()).state(in.getState()).dataset(in.get())
.memorySizeMb(in.getMemorySizeMb()).diskSizeGb(in.getDiskSizeGb()).ips(in.getIps())
.metadata(in.getMetadata()).created(in.getCreated()).updated(in.getUpdated());
.metadata(in.metadata).created(in.getCreated()).updated(in.getUpdated());
}
}
@ -169,7 +177,7 @@ public class Machine implements Comparable<Machine> {
protected final Date updated;
// metadata Object[String => String] Any "extra" metadata this machine has
private final Map<String, String> metadata;
private final Map<String, JsonBall> metadata;
@Override
public int compareTo(Machine other) {
@ -177,7 +185,7 @@ public class Machine implements Comparable<Machine> {
}
public Machine(String id, String name, Type type, State state, String dataset, int memorySizeMb, int diskSizeGb,
Set<String> ips, Date created, Date updated, final Map<String, String> metadata) {
Set<String> ips, Date created, Date updated, final Map<String, JsonBall> metadata) {
super();
this.id = id;
this.name = name;
@ -208,7 +216,7 @@ public class Machine implements Comparable<Machine> {
return state;
}
public String getDataset() {
public String get() {
return dataset;
}
@ -232,10 +240,39 @@ public class Machine implements Comparable<Machine> {
return updated;
}
public Map<String, String> getMetadata() {
return metadata;
/**
* If the value is a string, it will be quoted, as that's how json strings are represented.
*
* @return key to a json literal of the value
* @see MetadataKeys#valueType
* @see Json#fromJson
*/
public Map<String, String> getMetadataAsJsonLiterals() {
return Maps.transformValues(metadata, Functions.toStringFunction());
}
/**
* Note!! metadata can contain arbitrarily complex values. If the value has structure, you should use {@link #getMetadataAsJsonLiterals}
*
* @return metadata
*/
public Map<String, String> getMetadata() {
return Maps.transformValues(metadata, Functions.compose(Functions.toStringFunction(), unquoteString));
}
@VisibleForTesting
static final Function<JsonBall, String> unquoteString = new Function<JsonBall, String>() {
@Override
public String apply(JsonBall input) {
String value = input.toString();
if (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(input.length() - 1) == '"')
return value.substring(1, input.length() - 1);
return value;
}
};
@Override
public boolean equals(Object object) {
if (this == object) {

View File

@ -33,7 +33,7 @@ public class DatasetInDatacenter extends DatacenterAndId {
this.dataset = dataset;
}
public Dataset getDataset() {
public Dataset get() {
return dataset;
}

View File

@ -0,0 +1,48 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.domain.datacenterscoped;
import static com.google.common.base.Preconditions.checkNotNull;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
/**
* @author Adrian Cole
*/
public class KeyInDatacenter extends DatacenterAndName {
protected final Key key;
public KeyInDatacenter(Key key, String datacenterId) {
super(datacenterId, checkNotNull(key, "key").getName());
this.key = key;
}
public Key get() {
return key;
}
// superclass hashCode/equals are good enough, and help us use DatacenterAndId and PackageInDatacenter
// interchangeably as Map keys
@Override
public String toString() {
return "[key=" + key + ", datacenterId=" + datacenterId + "]";
}
}

View File

@ -33,7 +33,7 @@ public class MachineInDatacenter extends DatacenterAndId {
this.machine = machine;
}
public Machine getMachine() {
public Machine get() {
return machine;
}

View File

@ -31,7 +31,7 @@ public class PackageInDatacenter extends DatacenterAndName {
this.pkg = pkg;
}
public org.jclouds.joyent.sdc.v6_5.domain.Package getPackage() {
public org.jclouds.joyent.sdc.v6_5.domain.Package get() {
return pkg;
}

View File

@ -32,20 +32,20 @@ import com.google.common.util.concurrent.ListenableFuture;
@RequestFilters(BasicAuthentication.class)
public interface DatasetAsyncClient {
/**
* @see DatasetClient#listMachines
* @see DatasetClient#list
*/
@GET
@Path("/my/datasets")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<Dataset>> listDatasets();
ListenableFuture<Set<Dataset>> list();
/**
* @see DatasetClient#getMachineDetails
* @see DatasetClient#get
*/
@GET
@Path("/my/datasets/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Dataset> getDataset(@PathParam("id") String id);
ListenableFuture<Dataset> get(@PathParam("id") String id);
}

View File

@ -22,7 +22,7 @@ public interface DatasetClient {
*
* @return
*/
Set<Dataset> listDatasets();
Set<Dataset> list();
/**
* Gets an individual dataset by id.
@ -31,5 +31,5 @@ public interface DatasetClient {
* the id of the dataset
* @return
*/
Dataset getDataset(String id);
Dataset get(String id);
}

View File

@ -0,0 +1,69 @@
package org.jclouds.joyent.sdc.v6_5.features;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.joyent.sdc.v6_5.binders.BindKeyToJsonPayload;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture;
/**
* @author Adrian Cole
* @see KeyClient
* @see <a href="http://apidocs.joyent.com/sdcapidoc/cloudapi/#keys">api doc</a>
*/
@SkipEncoding({ '/', '=' })
@Headers(keys = "X-Api-Version", values = "{jclouds.api-version}")
@RequestFilters(BasicAuthentication.class)
public interface KeyAsyncClient {
/**
* @see KeyClient#list
*/
@GET
@Path("/my/keys")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<Key>> list();
/**
* @see KeyClient#get
*/
@GET
@Path("/my/keys/{name}")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Key> get(@PathParam("name") String name);
/**
* @see KeyClient#create
*/
@POST
@Path("/my/keys")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Key> create(@BinderParam(BindKeyToJsonPayload.class) Key key);
/**
* @see KeyClient#delete
*/
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Path("/my/keys/{name}")
ListenableFuture<Void> delete(@PathParam("name") String name);
}

View File

@ -0,0 +1,40 @@
package org.jclouds.joyent.sdc.v6_5.features;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
/**
* Keys are the means by which you operate on your SSH/signing keys. Currently
* CloudAPI supports uploads of public keys in the OpenSSH format.
*
* @author Adrian Cole
* @see KeyAsyncClient
* @see <a href="http://apidocs.joyent.com/sdcapidoc/cloudapi/#keys">api doc</a>
*/
@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS)
public interface KeyClient {
/**
* Lists all public keys we have on record for the specified account.
*/
Set<Key> list();
/**
* Retrieves an individual key record.
*/
Key get(String name);
/**
* Uploads a new OpenSSH key to SmartDataCenter for use in SSH and HTTP
* signing.
*/
Key create(Key key);
/**
* Deletes an SSH key by name.
*/
void delete(String name);
}

View File

@ -27,6 +27,7 @@ import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.jclouds.http.filters.BasicAuthentication;
@ -34,7 +35,6 @@ import org.jclouds.joyent.sdc.v6_5.domain.Machine;
import org.jclouds.joyent.sdc.v6_5.options.CreateMachineOptions;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers;
import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.Payload;
import org.jclouds.rest.annotations.PayloadParam;
import org.jclouds.rest.annotations.RequestFilters;
@ -58,81 +58,86 @@ import com.google.common.util.concurrent.ListenableFuture;
public interface MachineAsyncClient {
/**
* @see MachineClient#listMachines
* @see MachineClient#list
*/
@GET
@Path("/my/machines")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<Machine>> listMachines();
ListenableFuture<Set<Machine>> list();
/**
* @see MachineClient#getMachineDetails
* @see MachineClient#get
*/
@GET
@Path("/my/machines/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Machine> getMachine(@PathParam("id") String id);
ListenableFuture<Machine> get(@PathParam("id") String id);
/**
* @see MachineClient#createWithDataset(String)
*/
@POST
@Path("/my/machines")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Machine> createWithDataset(@QueryParam("dataset") String datasetURN);
/**
* @see MachineClient#createMachine
* @see MachineClient#createWithDataset(String, CreateMachineOptions)
*/
@POST
@Path("/my/machines")
@Consumes(MediaType.APPLICATION_JSON)
@MapBinder(CreateMachineOptions.class)
ListenableFuture<Machine> createMachine(@PayloadParam("name") String name,
@PayloadParam("package") String packageSDC,
@PayloadParam("dataset") String dataset,CreateMachineOptions... options);
@Path("/my/machines")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Machine> createWithDataset(@QueryParam("dataset") String datasetURN, CreateMachineOptions options);
/**
* @see MachineClient#stopMachine
* @see MachineClient#stop
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/my/machines/{id}")
@Payload("action=stop")
ListenableFuture<Void> stopMachine(@PathParam("id") String id);
ListenableFuture<Void> stop(@PathParam("id") String id);
/**
* @see MachineClient#startMachine
* @see MachineClient#start
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/my/machines/{id}")
@Payload("action=start")
ListenableFuture<Void> startMachine(@PathParam("id") String id);
ListenableFuture<Void> start(@PathParam("id") String id);
/**
* @see MachineClient#rebootMachine
* @see MachineClient#reboot
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/my/machines/{id}")
@Payload("action=reboot")
ListenableFuture<Void> rebootMachine(@PathParam("id") String id);
ListenableFuture<Void> reboot(@PathParam("id") String id);
/**
* @see MachineClient#resizeMachine
* @see MachineClient#resize
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/my/machines/{id}")
@Payload("action=resize&package={package}")
ListenableFuture<Void> resizeMachine(@PathParam("id") String id,@PayloadParam("package") String packageSDC);
ListenableFuture<Void> resize(@PathParam("id") String id,@PayloadParam("package") String packageSDC);
/**
* @see MachineClient#deleteMachine
* @see MachineClient#delete
*/
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Path("/my/machines/{id}")
ListenableFuture<Void> deleteMachine(@PathParam("id") String id);
ListenableFuture<Void> delete(@PathParam("id") String id);

View File

@ -41,7 +41,7 @@ public interface MachineClient {
*
* @return an account's associated machine objects.
*/
Set<Machine> listMachines();
Set<Machine> list();
/**
* Gets the details for an individual machine.
@ -50,21 +50,47 @@ public interface MachineClient {
* the id of the machine
* @return
*/
Machine getMachine(String id);
Machine get(String id);
/**
* Allows you to provision a machine. Note that if you do not specify a
* package, you'll get the datacenter defaults for it. If
* you do not specify a name, CloudAPI will generate a random one for you.
* Your machine will initially be not available for login (SmartDataCenter
* must provision and boot it). You can poll {@link #get} for status. When the
* state field is equal to running, you can login.
*
* <p/>
* With regards to login, if the machine is of type smartmachine, you can use
* any of the SSH keys managed under the keys section of CloudAPI to login,
* as any POSIX user on the OS. You can add/remove them over time, and the
* machine will automatically work with that set.
*
* <p/>
* If the the machine is a virtualmachine, and of a UNIX-derived OS (e.g.
* Linux), you must have keys uploaded before provisioning; that entire set
* of keys will be written out to /root/.ssh/authorized_keys, and you can ssh
* in using one of those. Changing the keys over time under your account will
* not affect the running virtual machine in any way; those keys are
* statically written at provisioning-time only, and you will need to
* manually manage them.
*
* <p/>
* If the dataset you create a machine from is set to generate passwords for
* you, the username/password pairs will be returned in the metadata response
* as a nested object, like:
*
* @param datasetURN urn of the dataset to install
*
* @param name
* friendly name for this machine; default is a randomly generated name
* @param packageSDC
* Name of the package to use on provisioning; default is indicated in ListPackages
* @param dataset
* dataset URN; default is indicated in ListDatasets
* @param options
* optional parameters to be passed into the machine creation request
* @return the newly created machine
*/
Machine createMachine(String name, String packageSDC, String dataset, CreateMachineOptions... options);
Machine createWithDataset(String datasetURN, CreateMachineOptions options);
/**
*
* @see #createWithDataset(CreateMachineOptions)
*/
Machine createWithDataset(String datasetURN);
/**
* Allows you to shut down a machine.
@ -72,7 +98,7 @@ public interface MachineClient {
* @param id
* the id of the machine to stop
*/
void stopMachine(String id);
void stop(String id);
/**
* Allows you to boot up a machine.
@ -80,7 +106,7 @@ public interface MachineClient {
* @param id
* the id of the machine to start
*/
void startMachine(String id);
void start(String id);
/**
* Allows you to reboot a machine.
@ -88,7 +114,7 @@ public interface MachineClient {
* @param id
* the id of the machine to reboot
*/
void rebootMachine(String id);
void reboot(String id);
/**
* Allows you to resize a machine. (Works only for smart machines)
@ -98,14 +124,15 @@ public interface MachineClient {
* @param packageSDC
* the package to use for the machine
*/
void resizeMachine(String id, String packageSDC);
void resize(String id, String packageSDC);
/**
* Allows you to delete a machine (the machine must be stopped before it can be deleted).
* Allows you to delete a machine (the machine must be stopped before it can
* be deleted).
*
* @param id
* the id of the machine to delete
*/
void deleteMachine(String id);
void delete(String id);
}

View File

@ -31,20 +31,20 @@ import com.google.common.util.concurrent.ListenableFuture;
@RequestFilters(BasicAuthentication.class)
public interface PackageAsyncClient {
/**
* @see PackageClient#listPackages
* @see PackageClient#list
*/
@GET
@Path("/my/packages")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<org.jclouds.joyent.sdc.v6_5.domain.Package>> listPackages();
ListenableFuture<Set<org.jclouds.joyent.sdc.v6_5.domain.Package>> list();
/**
* @see PackageClient#getPackageDetails
* @see PackageClient#get
*/
@GET
@Path("/my/packages/{name}")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<org.jclouds.joyent.sdc.v6_5.domain.Package> getPackage(@PathParam("name") String name);
ListenableFuture<org.jclouds.joyent.sdc.v6_5.domain.Package> get(@PathParam("name") String name);
}

View File

@ -21,7 +21,7 @@ public interface PackageClient {
*
* @return
*/
Set<org.jclouds.joyent.sdc.v6_5.domain.Package> listPackages();
Set<org.jclouds.joyent.sdc.v6_5.domain.Package> list();
/**
* Gets an individual package by id.
@ -30,5 +30,5 @@ public interface PackageClient {
* the name of the package
* @return
*/
org.jclouds.joyent.sdc.v6_5.domain.Package getPackage(String name);
org.jclouds.joyent.sdc.v6_5.domain.Package get(String name);
}

View File

@ -24,28 +24,25 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import org.jclouds.http.options.BaseHttpRequestOptions;
import org.jclouds.joyent.sdc.v6_5.features.PackageClient;
import org.jclouds.util.Maps2;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableMap;
import com.google.gson.annotations.SerializedName;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
/**
*
* @author Gerald Pereira
* @author Adrian Cole
*
*/
public class CreateMachineOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
public class CreateMachineOptions extends BaseHttpRequestOptions {
private String name;
private String pkg;
private Map<String, String> metadata = ImmutableMap.of();
private Map<String, String> tag = ImmutableMap.of();
@Override
public boolean equals(Object object) {
@ -54,7 +51,7 @@ public class CreateMachineOptions implements MapBinder {
}
if (object instanceof CreateMachineOptions) {
final CreateMachineOptions other = CreateMachineOptions.class.cast(object);
return equal(tag, tag) && equal(metadata, other.metadata);
return equal(name, other.name) && equal(pkg, other.pkg) && equal(metadata, other.metadata);
} else {
return false;
}
@ -62,40 +59,51 @@ public class CreateMachineOptions implements MapBinder {
@Override
public int hashCode() {
return Objects.hashCode(tag, metadata);
}
protected ToStringHelper string() {
return toStringHelper("").add("metadata", metadata).add("tag", tag);
return Objects.hashCode(name, pkg, metadata);
}
@Override
public String toString() {
return string().toString();
return toStringHelper("").add("name", name).add("package", name).add("metadata", metadata).toString();
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
return jsonBinder.bindToRequest(request, input);
}
public Multimap<String, String> buildQueryParameters() {
Multimap<String, String> params = super.buildQueryParameters();
if (name != null)
params.put("name", name);
if (pkg != null)
params.put("package", pkg);
params.putAll(Multimaps.forMap(Maps2.transformKeys(metadata, new Function<String, String>() {
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
MachineRequest machine = new MachineRequest(checkNotNull(postParams.get("name"), "name parameter not present")
.toString(), checkNotNull(postParams.get("package"), "package parameter not present").toString(),
checkNotNull(postParams.get("dataset"), "dataset parameter not present").toString());
@Override
public String apply(String input) {
return "metadata." + input;
}
if (metadata.size() > 0)
machine.metadata = metadata;
if (tag.size() > 0)
machine.tag = tag;
return bindToRequest(request, machine);
})));
return params;
}
/**
* An arbitrary set of metadata key/value pairs can be set at provision time, but they must be
* prefixed with "metadata."
* friendly name for this machine; default is a randomly generated name
*/
public CreateMachineOptions name(String name) {
this.name = checkNotNull(name, "name");
return this;
}
/**
* Name of the package to use on provisioning; default is indicated in
* {@link PackageClient#list}
*/
public CreateMachineOptions packageName(String packageName) {
this.pkg = checkNotNull(packageName, "packageName");
return this;
}
/**
* An arbitrary set of metadata key/value pairs.
*/
public CreateMachineOptions metadata(Map<String, String> metadata) {
checkNotNull(metadata, "metadata");
@ -103,33 +111,23 @@ public class CreateMachineOptions implements MapBinder {
return this;
}
/**
* An arbitrary set of tags can be set at provision time, but they must be prefixed with "tag."
*/
public CreateMachineOptions tag(Map<String, String> tag) {
checkNotNull(tag, "tag");
this.tag = ImmutableMap.copyOf(tag);
return this;
}
public static class Builder {
@SuppressWarnings("unused")
private class MachineRequest {
final String name;
@SerializedName("package")
final String packageSDC;
final String dataset;
Map<String, String> metadata;
Map<String, String> tag;
private MachineRequest(String name, String packageSDC, String dataset) {
this.name = name;
this.packageSDC = packageSDC;
this.dataset = dataset;
/**
* @see CreateMachineOptions#name
*/
public static CreateMachineOptions name(String name) {
CreateMachineOptions options = new CreateMachineOptions();
return options.name(name);
}
}
public static class Builder {
/**
* @see CreateMachineOptions#packageName
*/
public static CreateMachineOptions packageName(String packageName) {
CreateMachineOptions options = new CreateMachineOptions();
return options.packageName(packageName);
}
/**
* @see CreateMachineOptions#metadata(Map<String, String>)
@ -139,13 +137,6 @@ public class CreateMachineOptions implements MapBinder {
return options.metadata(metadata);
}
/**
* @see CreateMachineOptions#tag(Map<String, String>)
*/
public static CreateMachineOptions tag(Map<String, String> tag) {
CreateMachineOptions options = new CreateMachineOptions();
return options.tag(tag);
}
}
}

View File

@ -0,0 +1,67 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.reference;
import java.lang.reflect.Type;
import java.util.Map;
import com.google.common.base.CaseFormat;
import com.google.common.reflect.TypeToken;
/**
* Known keys for metadata
*
* @author Adrian Cole
*/
public enum MetadataKeys {
ROOT_AUTHORIZED_KEYS(TypeToken.of(String.class).getType()),
/**
* If the dataset you create a machine from is set to generate passwords for
* you, the username/password pairs will be returned in the metadata response
* as a nested object, like:
*
* <pre>
* "credentials": {
* "root": "s8v9kuht5e",
* "admin": "mf4bteqhpy"
* }
* </pre>
*/
CREDENTIALS(new TypeToken<Map<String, String>>() {
private static final long serialVersionUID = -433136967305618708L;
}.getType());
private final Type valueType;
MetadataKeys(Type valueType) {
this.valueType = valueType;
}
public String key() {
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE, name());
}
/**
* type of the value;
*/
public Type type() {
return valueType;
}
}

View File

@ -135,8 +135,8 @@ public class MachineInDatacenterToNodeMetadataTest {
assertEquals(convertedNodeMetadata.getPublicAddresses(), ImmutableSet.of("37.153.96.62"));
assertNotNull(convertedNodeMetadata.getUserMetadata());
assertEquals(convertedNodeMetadata.getUserMetadata(),
ImmutableMap.<String, String> of("root_authorized_keys", "ssh-rsa XXXXXX== test@xxxx.ovh.net\n"));
// ensure filtered out root_authorized_keys!
assertEquals(convertedNodeMetadata.getUserMetadata(), ImmutableMap.<String, String> of());
}
}

View File

@ -37,27 +37,27 @@ import com.google.common.collect.ImmutableSet;
*/
@Test(groups = "unit", testName = "DatasetClientExpectTest")
public class DatasetClientExpectTest extends BaseSDCClientExpectTest {
HttpRequest listDatasets = HttpRequest.builder().method("GET").endpoint(
HttpRequest list = HttpRequest.builder().method("GET").endpoint(
URI.create("https://us-sw-1.api.joyentcloud.com/my/datasets")).headers(
ImmutableMultimap.<String, String> builder().put("X-Api-Version", "~6.5").put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build();
public void testListDatasetsWhenResponseIs2xx() {
HttpResponse listDatasetsResponse = HttpResponse.builder().statusCode(200).payload(
HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/dataset_list.json")).build();
SDCClient clientWhenDatasetsExists = requestsSendResponses(getDatacenters, getDatacentersResponse, listDatasets, listDatasetsResponse);
SDCClient clientWhenDatasetsExists = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(clientWhenDatasetsExists.getDatasetClientForDatacenter("us-sw-1").listDatasets().toString(), new ParseDatasetListTest()
assertEquals(clientWhenDatasetsExists.getDatasetClientForDatacenter("us-sw-1").list().toString(), new ParseDatasetListTest()
.expected().toString());
}
public void testListDatasetsWhenResponseIs404() {
HttpResponse listDatasetsResponse = HttpResponse.builder().statusCode(404).build();
HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();
SDCClient listDatasetsWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, listDatasets, listDatasetsResponse);
SDCClient listWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(listDatasetsWhenNone.getDatasetClientForDatacenter("us-sw-1").listDatasets(), ImmutableSet.of());
assertEquals(listWhenNone.getDatasetClientForDatacenter("us-sw-1").list(), ImmutableSet.of());
}
// [id=e4cd7b9e-4330-11e1-81cf-3bb50a972bda, name=centos-6, type=VIRTUALMACHINE, version=1.0.1,

View File

@ -36,10 +36,10 @@ public class DatasetClientLiveTest extends BaseSDCClientLiveTest {
public void testListAndGetDatasets() throws Exception {
for (String datacenterId : sdcContext.getApi().getConfiguredDatacenters()) {
DatasetClient client = sdcContext.getApi().getDatasetClientForDatacenter(datacenterId);
Set<Dataset> response = client.listDatasets();
Set<Dataset> response = client.list();
assert null != response;
for (Dataset dataset : response) {
Dataset newDetails = client.getDataset(dataset.getId());
Dataset newDetails = client.get(dataset.getId());
assertEquals(newDetails.getId(), dataset.getId());
assertEquals(newDetails.getName(), dataset.getName());
assertEquals(newDetails.getType(), dataset.getType());

View File

@ -0,0 +1,85 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unles 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 expres or implied. See the License for the
* specific language governing permisions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.features;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.joyent.sdc.v6_5.SDCClient;
import org.jclouds.joyent.sdc.v6_5.internal.BaseSDCClientExpectTest;
import org.jclouds.joyent.sdc.v6_5.parse.ParseKeyListTest;
import org.jclouds.joyent.sdc.v6_5.parse.ParseKeyTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "KeyClientExpectTest")
public class KeyClientExpectTest extends BaseSDCClientExpectTest {
HttpRequest list = HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.joyentcloud.com/my/keys")).headers(
ImmutableMultimap.<String, String> builder().put("X-Api-Version", "~6.5").put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build();
public void testListKeysWhenResponseIs2xx() {
HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/key_list.json")).build();
SDCClient clientWhenKeysExists = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(clientWhenKeysExists.getKeyClient().list(), new ParseKeyListTest().expected());
}
public void testListKeysWhenResponseIs404() {
HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();
SDCClient listWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(listWhenNone.getKeyClient().list(), ImmutableSet.of());
}
public void testCreateKeyWhenResponseIs202() throws Exception {
HttpRequest create = HttpRequest
.builder()
.method("POST")
.endpoint(URI.create("https://api.joyentcloud.com/my/keys"))
.headers(
ImmutableMultimap.<String, String> builder().put("X-Api-Version", "~6.5").put("Accept",
"application/json").put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(
payloadFromStringWithContentType(
"{\"name\":\"rsa\",\"key\":\"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...\"}",
"application/json")).build();
HttpResponse createResponse = HttpResponse.builder().statusCode(202).message("HTTP/1.1 202 Accepted")
.payload(payloadFromResourceWithContentType("/key.json", "application/json; charset=UTF-8"))
.build();
SDCClient clientWithNewKey = requestsSendResponses(getDatacenters, getDatacentersResponse, create, createResponse);
assertEquals(clientWithNewKey.getKeyClient().create(new ParseKeyTest().expected())
.toString(), new ParseKeyTest().expected().toString());
}
}

View File

@ -0,0 +1,86 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.features;
import static org.testng.Assert.assertEquals;
import java.util.Set;
import org.jclouds.crypto.SshKeys;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
import org.jclouds.joyent.sdc.v6_5.internal.BaseSDCClientLiveTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "live", singleThreaded = true, testName = "KeyClientLiveTest")
public class KeyClientLiveTest extends BaseSDCClientLiveTest {
@Test
public void testListAndGetKeys() throws Exception {
KeyClient client = sdcContext.getApi().getKeyClient();
Set<Key> response = client.list();
assert null != response;
for (Key key : response) {
Key newDetails = client.get(key.getName());
assertEquals(newDetails.getName(), key.getName());
assertEquals(newDetails.get(), key.get());
assertEquals(newDetails.getCreated(), key.getCreated());
}
}
private String keyText;
private String fingerprint;
@BeforeTest
public void initKeys() {
keyText = SshKeys.generate().get("public");
fingerprint = SshKeys.fingerprintPublicKey(keyText);
}
public void testCreateKey() {
KeyClient client = sdcContext.getApi().getKeyClient();
Key newKey = client.create(Key.builder().name(fingerprint).key(keyText).build());
assertEquals(newKey.getName(), fingerprint);
assertEquals(newKey.get(), keyText);
newKey = client.get(fingerprint);
assertEquals(newKey.getName(), fingerprint);
assertEquals(newKey.get(), keyText);
}
@Test(dependsOnMethods = "testCreateKey", expectedExceptions = IllegalStateException.class)
public void testDuplicateKey() {
KeyClient client = sdcContext.getApi().getKeyClient();
client.create(Key.builder().name(fingerprint).key(keyText).build());
}
@Test(dependsOnMethods = "testDuplicateKey")
public void testDestroyKey() {
final KeyClient client = sdcContext.getApi().getKeyClient();
client.delete(fingerprint);
// not that eventhough the key is destroyed it is visible via GET for at
// least 45 seconds. This may be a cache issue on the server
}
}

View File

@ -26,6 +26,7 @@ import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.joyent.sdc.v6_5.SDCClient;
import org.jclouds.joyent.sdc.v6_5.internal.BaseSDCClientExpectTest;
import org.jclouds.joyent.sdc.v6_5.options.CreateMachineOptions;
import org.jclouds.joyent.sdc.v6_5.parse.ParseCreatedMachineTest;
import org.jclouds.joyent.sdc.v6_5.parse.ParseMachineListTest;
import org.testng.annotations.Test;
@ -38,48 +39,50 @@ import com.google.common.collect.ImmutableSet;
*/
@Test(groups = "unit", testName = "MachineClientExpectTest")
public class MachineClientExpectTest extends BaseSDCClientExpectTest {
HttpRequest listMachines = HttpRequest.builder().method("GET").endpoint(
HttpRequest list = HttpRequest.builder().method("GET").endpoint(
URI.create("https://us-sw-1.api.joyentcloud.com/my/machines")).headers(
ImmutableMultimap.<String, String> builder().put("X-Api-Version", "~6.5").put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build();
public void testListMachinesWhenResponseIs2xx() {
HttpResponse listMachinesResponse = HttpResponse.builder().statusCode(200).payload(
HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/machine_list.json")).build();
SDCClient clientWhenMachinesExists = requestsSendResponses(getDatacenters, getDatacentersResponse, listMachines, listMachinesResponse);
SDCClient clientWhenMachinesExists = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(clientWhenMachinesExists.getMachineClientForDatacenter("us-sw-1").listMachines(), new ParseMachineListTest().expected());
assertEquals(clientWhenMachinesExists.getMachineClientForDatacenter("us-sw-1").list(), new ParseMachineListTest().expected());
}
public void testListMachinesWhenResponseIs404() {
HttpResponse listMachinesResponse = HttpResponse.builder().statusCode(404).build();
HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();
SDCClient listMachinesWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, listMachines, listMachinesResponse);
SDCClient listWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(listMachinesWhenNone.getMachineClientForDatacenter("us-sw-1").listMachines(), ImmutableSet.of());
assertEquals(listWhenNone.getMachineClientForDatacenter("us-sw-1").list(), ImmutableSet.of());
}
public void testCreateMachineWhenResponseIs202() throws Exception {
HttpRequest createMachine = HttpRequest
HttpRequest createWithDataset = HttpRequest
.builder()
.method("POST")
.endpoint(URI.create("https://us-sw-1.api.joyentcloud.com/my/machines"))
.headers(
ImmutableMultimap.<String, String> builder().put("X-Api-Version", "~6.5").put("Accept",
"application/json").put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(
payloadFromStringWithContentType(
"{\"name\":\"sample-e92\",\"package\":\"Small 1GB\",\"dataset\":\"sdc:sdc:centos-5.7:1.2.1\"}",
"application/json")).build();
.endpoint(URI.create("https://us-sw-1.api.joyentcloud.com/my/machines?dataset=sdc%3Asdc%3Acentos-5.7%3A1.2.1&name=sample-e92&package=Small%201GB"))
.headers(ImmutableMultimap.<String, String> builder()
.put("X-Api-Version", "~6.5")
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.build();
HttpResponse createMachineResponse = HttpResponse.builder().statusCode(202).message("HTTP/1.1 202 Accepted")
HttpResponse createWithDatasetResponse = HttpResponse.builder().statusCode(202).message("HTTP/1.1 202 Accepted")
.payload(payloadFromResourceWithContentType("/new_machine.json", "application/json; charset=UTF-8"))
.build();
SDCClient clientWithNewMachine = requestsSendResponses(getDatacenters, getDatacentersResponse, createMachine, createMachineResponse);
SDCClient clientWithNewMachine = requestsSendResponses(getDatacenters, getDatacentersResponse, createWithDataset, createWithDatasetResponse);
assertEquals(clientWithNewMachine.getMachineClientForDatacenter("us-sw-1").createMachine("sample-e92", "Small 1GB",
"sdc:sdc:centos-5.7:1.2.1").toString(), new ParseCreatedMachineTest().expected().toString());
assertEquals(
clientWithNewMachine
.getMachineClientForDatacenter("us-sw-1")
.createWithDataset("sdc:sdc:centos-5.7:1.2.1",
CreateMachineOptions.Builder.name("sample-e92").packageName("Small 1GB")).toString(),
new ParseCreatedMachineTest().expected().toString());
}
}

View File

@ -18,16 +18,39 @@
*/
package org.jclouds.joyent.sdc.v6_5.features;
import static com.google.common.base.Predicates.not;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.crypto.SshKeys;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
import org.jclouds.joyent.sdc.v6_5.domain.Machine;
import org.jclouds.joyent.sdc.v6_5.internal.BaseSDCClientLiveTest;
import org.jclouds.joyent.sdc.v6_5.options.CreateMachineOptions;
import org.jclouds.joyent.sdc.v6_5.reference.MetadataKeys;
import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.util.InetAddresses2;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.net.HostAndPort;
import com.google.inject.Module;
/**
* @author Gerald Pereira
* @author Adrian Cole
*/
@Test(groups = "live", testName = "MachineClientLiveTest")
public class MachineClientLiveTest extends BaseSDCClientLiveTest {
@ -36,15 +59,15 @@ public class MachineClientLiveTest extends BaseSDCClientLiveTest {
public void testListAndGetMachines() throws Exception {
for (String datacenterId : sdcContext.getApi().getConfiguredDatacenters()) {
MachineClient client = sdcContext.getApi().getMachineClientForDatacenter(datacenterId);
Set<Machine> response = client.listMachines();
Set<Machine> response = client.list();
assert null != response;
for (Machine machine : response) {
Machine newDetails = client.getMachine(machine.getId());
Machine newDetails = client.get(machine.getId());
assertEquals(newDetails.getId(), machine.getId());
assertEquals(newDetails.getName(), machine.getName());
assertEquals(newDetails.getType(), machine.getType());
assertEquals(newDetails.getState(), machine.getState());
assertEquals(newDetails.getDataset(), machine.getDataset());
assertEquals(newDetails.get(), machine.get());
assertEquals(newDetails.getMemorySizeMb(), machine.getMemorySizeMb());
assertEquals(newDetails.getDiskSizeGb(), machine.getDiskSizeGb());
assertEquals(newDetails.getIps(), machine.getIps());
@ -54,4 +77,99 @@ public class MachineClientLiveTest extends BaseSDCClientLiveTest {
}
}
}
private Map<String, String> keypair;
private String fingerprint;
private RetryablePredicate<HostAndPort> socketTester;
private Predicate<Machine> machineRunning;
private MachineClient client;
private Machine machine;
protected String datasetURN = System.getProperty("test." + provider + ".image-id", "sdc:sdc:ubuntu-10.04:1.0.1");
private String name;
@BeforeGroups(groups = { "integration", "live" })
@Override
public void setupContext() {
super.setupContext();
keypair = SshKeys.generate();
fingerprint = SshKeys.fingerprintPublicKey(keypair.get("public"));
sdcContext.getApi().getKeyClient().create(Key.builder().name(fingerprint).key(keypair.get("public")).build());
client = sdcContext.getApi().getMachineClientForDatacenter(
Iterables.get(sdcContext.getApi().getConfiguredDatacenters(), 0));
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 180, 1, 1, TimeUnit.SECONDS);
machineRunning = new RetryablePredicate<Machine>(new Predicate<Machine>() {
@Override
public boolean apply(Machine input) {
return client.get(input.getId()).getState() == Machine.State.RUNNING;
}
}, 600, 5, 5, TimeUnit.SECONDS);
machineRunning = new RetryablePredicate<Machine>(new Predicate<Machine>() {
@Override
public boolean apply(Machine input) {
return client.get(input.getId()).getState() == Machine.State.RUNNING;
}
}, 600, 5, 5, TimeUnit.SECONDS);
}
public void testCreateMachine() {
Machine newMachine = client.createWithDataset(datasetURN,
CreateMachineOptions.Builder.metadata(ImmutableMap.of("foo", "bar")));
machine = newMachine;
name = newMachine.getName();
assertEquals(newMachine.getMetadata().get("foo").toString(), "bar");
assertTrue(
newMachine.getMetadata().get(MetadataKeys.ROOT_AUTHORIZED_KEYS.key()).indexOf(keypair.get("public")) != -1,
newMachine + "; key: " + keypair.get("public"));
assertTrue(machineRunning.apply(newMachine), newMachine.toString());
machine = client.get(newMachine.getId());
}
@Test(dependsOnMethods = "testCreateMachine", expectedExceptions = IllegalStateException.class)
public void testDuplicateMachineThrowsIllegalStateException() {
client.createWithDataset(datasetURN, CreateMachineOptions.Builder.name(name));
}
@Test(dependsOnMethods = "testCreateMachine")
protected void testSsh() {
String publicAddress = Iterables.find(machine.getIps(), not(InetAddresses2.IsPrivateIPAddress.INSTANCE));
HostAndPort socket = HostAndPort.fromParts(publicAddress, 22);
assertTrue(socketTester.apply(socket), socket.toString());
SshClient client = context.utils().injector().getInstance(SshClient.Factory.class)
.create(socket, LoginCredentials.builder().user("root").privateKey(keypair.get("private")).build());
try {
client.connect();
ExecResponse exec = client.exec("echo hello");
System.out.println(exec);
assertEquals(exec.getOutput().trim(), "hello");
} finally {
if (client != null)
client.disconnect();
}
}
@Test(dependsOnMethods = "testSsh")
public void testDeleteMachine() {
client.delete(machine.getId());
}
@Override
@AfterGroups(groups = "live")
protected void tearDown() {
if (machine != null)
client.delete(machine.getId());
sdcContext.getApi().getKeyClient().delete(fingerprint);
super.tearDown();
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
}

View File

@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableSet;
*/
@Test(groups = "unit", testName = "PackageClientExpectTest")
public class PackageClientExpectTest extends BaseSDCClientExpectTest {
HttpRequest listPackages = HttpRequest
HttpRequest list = HttpRequest
.builder()
.method("GET")
.endpoint(URI.create("https://us-sw-1.api.joyentcloud.com/my/packages"))
@ -47,19 +47,19 @@ public class PackageClientExpectTest extends BaseSDCClientExpectTest {
.build()).build();
public void testListPackagesWhenResponseIs2xx() {
HttpResponse listPackagesResponse = HttpResponse.builder().statusCode(200)
HttpResponse listResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/package_list.json")).build();
SDCClient clientWhenPackagesExists = requestsSendResponses(getDatacenters, getDatacentersResponse, listPackages, listPackagesResponse);
SDCClient clientWhenPackagesExists = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(clientWhenPackagesExists.getPackageClientForDatacenter("us-sw-1").listPackages(), new ParsePackageListTest().expected());
assertEquals(clientWhenPackagesExists.getPackageClientForDatacenter("us-sw-1").list(), new ParsePackageListTest().expected());
}
public void testListPackagesWhenResponseIs404() {
HttpResponse listPackagesResponse = HttpResponse.builder().statusCode(404).build();
HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();
SDCClient listPackagesWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, listPackages, listPackagesResponse);
SDCClient listWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(listPackagesWhenNone.getPackageClientForDatacenter("us-sw-1").listPackages(), ImmutableSet.of());
assertEquals(listWhenNone.getPackageClientForDatacenter("us-sw-1").list(), ImmutableSet.of());
}
}

View File

@ -36,10 +36,10 @@ public class PackageClientLiveTest extends BaseSDCClientLiveTest {
public void testListAndGetPackages() throws Exception {
for (String datacenterId : sdcContext.getApi().getConfiguredDatacenters()) {
PackageClient client = sdcContext.getApi().getPackageClientForDatacenter(datacenterId);
Set<Package> response = client.listPackages();
Set<Package> response = client.list();
assert null != response;
for (Package pkg : response) {
Package newDetails = client.getPackage(pkg.getName());
Package newDetails = client.get(pkg.getName());
assertEquals(newDetails.getName(), pkg.getName());
assertEquals(newDetails.getMemorySizeMb(), pkg.getMemorySizeMb());
assertEquals(newDetails.getDiskSizeGb(), pkg.getDiskSizeGb());

View File

@ -18,16 +18,16 @@
*/
package org.jclouds.joyent.sdc.v6_5.internal;
import org.jclouds.apis.BaseContextLiveTest;
import org.jclouds.joyent.sdc.v6_5.SDCApiMetadata;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.joyent.sdc.v6_5.SDCAsyncClient;
import org.jclouds.joyent.sdc.v6_5.SDCClient;
import org.jclouds.rest.RestContext;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.reflect.TypeToken;
import com.google.inject.Module;
/**
* Tests behavior of {@code SDCClient}
@ -35,7 +35,7 @@ import com.google.common.reflect.TypeToken;
* @author Adrian Cole
*/
@Test(groups = "live")
public class BaseSDCClientLiveTest extends BaseContextLiveTest<RestContext<SDCClient, SDCAsyncClient>> {
public class BaseSDCClientLiveTest extends BaseComputeServiceContextLiveTest {
public BaseSDCClientLiveTest() {
provider = "joyent-sdc";
@ -47,7 +47,7 @@ public class BaseSDCClientLiveTest extends BaseContextLiveTest<RestContext<SDCCl
@Override
public void setupContext() {
super.setupContext();
sdcContext = context;
sdcContext = view.unwrap();
}
@AfterGroups(groups = "live")
@ -57,8 +57,7 @@ public class BaseSDCClientLiveTest extends BaseContextLiveTest<RestContext<SDCCl
}
@Override
protected TypeToken<RestContext<SDCClient, SDCAsyncClient>> contextType() {
return SDCApiMetadata.CONTEXT_TOKEN;
protected Module getSshModule() {
return new SshjSshClientModule();
}
}

View File

@ -22,6 +22,7 @@ import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.domain.JsonBall;
import org.jclouds.joyent.sdc.v6_5.config.SDCParserModule;
import org.jclouds.joyent.sdc.v6_5.domain.Machine;
import org.jclouds.joyent.sdc.v6_5.domain.Type;
@ -58,7 +59,9 @@ public class ParseCreatedMachineTest extends BaseItemParserTest<Machine> {
.ips(ImmutableSet. <String>builder().add("37.153.96.62").add("10.224.0.63").build())
.memorySizeMb(1024)
.diskSizeGb(61440)
.metadata(ImmutableMap. <String,String>builder().put("root_authorized_keys","ssh-rsa XXXXXX== test@xxxx.ovh.net\n").build())
.metadata(
ImmutableMap.<String, JsonBall> builder()
.put("root_authorized_keys", new JsonBall("ssh-rsa XXXXXX== test@xxxx.ovh.net\n")).build())
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-09T13:32:46+00:00"))
.updated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-11T08:44:53+00:00"))
.build();

View File

@ -0,0 +1,71 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.parse;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.joyent.sdc.v6_5.config.SDCParserModule;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
import org.jclouds.json.BaseSetParserTest;
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 = "ParseKeyListTest")
public class ParseKeyListTest extends BaseSetParserTest<Key> {
@Override
public String resource() {
return "/key_list.json";
}
@Override
@Consumes(MediaType.APPLICATION_JSON)
public Set<Key> expected() {
return ImmutableSet.of(
Key.builder()
.name("rsa")
.key("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...")
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2011-04-13T22:14:46+00:00"))
.build()
);
}
protected Injector injector() {
return Guice.createInjector(new SDCParserModule(), new GsonModule() {
@Override
protected void configure() {
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
super.configure();
}
});
}
}

View File

@ -0,0 +1,66 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.sdc.v6_5.parse;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.joyent.sdc.v6_5.config.SDCParserModule;
import org.jclouds.joyent.sdc.v6_5.domain.Key;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ParseKeyTest")
public class ParseKeyTest extends BaseItemParserTest<Key> {
@Override
public String resource() {
return "/key.json";
}
@Override
@Consumes(MediaType.APPLICATION_JSON)
public Key expected() {
return Key.builder()
.name("rsa")
.key("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...")
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2011-04-13T22:14:46+00:00"))
.build();
}
protected Injector injector() {
return Guice.createInjector(new SDCParserModule(), new GsonModule() {
@Override
protected void configure() {
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
super.configure();
}
});
}
}

View File

@ -24,6 +24,7 @@ import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.domain.JsonBall;
import org.jclouds.joyent.sdc.v6_5.config.SDCParserModule;
import org.jclouds.joyent.sdc.v6_5.domain.Machine;
import org.jclouds.joyent.sdc.v6_5.domain.Type;
@ -62,8 +63,8 @@ public class ParseMachineListTest extends BaseSetParserTest<Machine> {
.memorySizeMb(1024)
.diskSizeGb(61440)
.metadata(
ImmutableMap.<String, String> builder()
.put("root_authorized_keys", "ssh-rsa XXXXXX== test@xxxx.ovh.net\n").build())
ImmutableMap.<String, JsonBall> builder()
.put("root_authorized_keys", new JsonBall("ssh-rsa XXXXXX== test@xxxx.ovh.net\n")).build())
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-09T13:32:46+00:00"))
.updated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-11T09:00:33+00:00"))
.build(),
@ -71,7 +72,7 @@ public class ParseMachineListTest extends BaseSetParserTest<Machine> {
Machine.builder().id("d73cb0b0-7d1f-44ef-8c40-e040eef0f726").name("sample-e922").type(Type.SMARTMACHINE)
.state(Machine.State.RUNNING).dataset("sdc:sdc:smartosplus:3.1.0")
.ips(ImmutableSet.<String> builder().add("37.153.96.56").add("10.224.0.57").build())
.memorySizeMb(1024).diskSizeGb(61440).metadata(ImmutableMap.<String, String> of())
.memorySizeMb(1024).diskSizeGb(61440).metadata(ImmutableMap.<String, JsonBall> of())
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-09T13:39:43+00:00"))
.updated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-09T13:43:45+00:00"))
.build()

View File

@ -22,6 +22,7 @@ import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.domain.JsonBall;
import org.jclouds.joyent.sdc.v6_5.config.SDCParserModule;
import org.jclouds.joyent.sdc.v6_5.domain.Machine;
import org.jclouds.joyent.sdc.v6_5.domain.Type;
@ -59,8 +60,8 @@ public class ParseMachineTest extends BaseItemParserTest<Machine> {
.memorySizeMb(1024)
.diskSizeGb(61440)
.metadata(
ImmutableMap.<String, String> builder()
.put("root_authorized_keys", "ssh-rsa XXXXXX== test@xxxx.ovh.net\n").build())
ImmutableMap.<String, JsonBall> builder()
.put("root_authorized_keys", new JsonBall("ssh-rsa XXXXXX== test@xxxx.ovh.net\n")).build())
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-09T13:32:46+00:00"))
.updated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-11T08:44:53+00:00")).build();
}

View File

@ -0,0 +1,5 @@
{
"name": "rsa",
"key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...",
"created": "2011-04-13T22:14:46+00:00"
}

View File

@ -0,0 +1,7 @@
[
{
"name": "rsa",
"key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...",
"created": "2011-04-13T22:14:46+00:00"
}
]

View File

@ -0,0 +1,32 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.joyent.joyentcloud.features;
import org.jclouds.joyent.sdc.v6_5.features.KeyClientLiveTest;
import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "live", testName = "JoyentCloudKeyClientLiveTest")
public class JoyentCloudKeyClientLiveTest extends KeyClientLiveTest {
public JoyentCloudKeyClientLiveTest() {
provider = "joyentcloud";
}
}