Merge branch 'master' of github.com:jclouds/jclouds into nodepool

* 'master' of github.com:jclouds/jclouds:
  Issue 997:support AWS IAM api
  added paginated set functionality
  glesys: updating to API version 0.1.29
  glesys: removing ArchiveDetails (duplicate of Archive)
  glesys: bean cleaning, using ConstructorProperties for deserialization (note no serialization annotations as we don't currently serialize any of these beans)
  glesys: adjusting ParserModule - removing support for odd dates (no longer present in api) and adding support for "yes"/"no" Boolean fields
  Specifically adding the osgi import org.apache.commons.io.input;version=[1.4,3)
  Upgrading commons-io dependency of sshj driver to 2.0
  Improve Maven build time dramatically by moving source and javadoc to profiles.
  Issue 992: Fix AWS S3 to work with non-DNS, but still valid, named buckets.
  Issue 995: handle illegal argument in vcloud images
  Issue 994: fix vcloud sax parsing of namespaces
  cloudstack: don't set networkId to default when iptonetworklist is populated
  Fix for iptonetworklist (was incorrectly sending ipnetworklist)
  Adjusting general strategy to accept @Named in place of @SerializedName. Adding TypeAdapterFactory to handle deserialization based on constructor annotations (Inject/Named and/or ConstructorProperties).
  added min-disk to compute2.clj
  Issue 988:Extra port added to swift url
  consistent ordering of hardware
  fixed missing provider name on ninefold test
  Eliminate unlikely transient blobstore TOCTOU bug
This commit is contained in:
Adrian Cole 2012-06-25 16:01:54 -07:00
commit 8030d0044d
162 changed files with 9268 additions and 2461 deletions

View File

@ -48,7 +48,7 @@ public class AdvancedNetworkOptionsConverter implements OptionsConverter {
checkArgument(templateOptions.getSecurityGroupIds().isEmpty(), "security groups cannot be specified for locations (zones) that use advanced networking"); checkArgument(templateOptions.getSecurityGroupIds().isEmpty(), "security groups cannot be specified for locations (zones) that use advanced networking");
if (templateOptions.getNetworkIds().size() > 0) { if (templateOptions.getNetworkIds().size() > 0) {
options.networkIds(templateOptions.getNetworkIds()); options.networkIds(templateOptions.getNetworkIds());
} else { } else if (templateOptions.getIpsToNetworks().isEmpty()) {
checkArgument(!networks.isEmpty(), "please setup a network for zone: " + zoneId); checkArgument(!networks.isEmpty(), "please setup a network for zone: " + zoneId);
Network defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), and(defaultNetworkInZone(zoneId), supportsStaticNAT())), null); Network defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), and(defaultNetworkInZone(zoneId), supportsStaticNAT())), null);
if(defaultNetworkInZone == null) { if(defaultNetworkInZone == null) {

View File

@ -129,8 +129,8 @@ public class DeployVirtualMachineOptions extends AccountInDomainOptions {
public DeployVirtualMachineOptions ipsToNetworks(Map<String, String> ipsToNetworks) { public DeployVirtualMachineOptions ipsToNetworks(Map<String, String> ipsToNetworks) {
int count = 0; int count = 0;
for (String ip : ipsToNetworks.keySet()) { for (String ip : ipsToNetworks.keySet()) {
this.queryParameters.replaceValues(String.format("ipnetworklist[%d].ip", count), ImmutableSet.of(ip)); this.queryParameters.replaceValues(String.format("iptonetworklist[%d].ip", count), ImmutableSet.of(ip));
this.queryParameters.replaceValues(String.format("ipnetworklist[%d].networkid", count), this.queryParameters.replaceValues(String.format("iptonetworklist[%d].networkid", count),
ImmutableSet.of("" + ipsToNetworks.get(ip))); ImmutableSet.of("" + ipsToNetworks.get(ip)));
count += 1; count += 1;
} }

View File

@ -63,7 +63,14 @@ public class BindAsHostPrefixIfConfigured implements Binder {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Object payload) { public <R extends HttpRequest> R bindToRequest(R request, Object payload) {
if (isVhostStyle) { // If we have a payload/bucket/container that is not all lowercase, vhost-style URLs are not an option and must be
// automatically converted to their path-based equivalent. This should only be possible for AWS-S3 since it is
// the only S3 implementation configured to allow uppercase payload/bucket/container names.
//
// http://code.google.com/p/jclouds/issues/detail?id=992
String payloadAsString = payload.toString();
if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) {
request = bindAsHostPrefix.bindToRequest(request, payload); request = bindAsHostPrefix.bindToRequest(request, payload);
String host = request.getEndpoint().getHost(); String host = request.getEndpoint().getHost();
if (request.getEndpoint().getPort() != -1) { if (request.getEndpoint().getPort() != -1) {
@ -80,7 +87,7 @@ public class BindAsHostPrefixIfConfigured implements Binder {
indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert = indexToInsert == -1 ? 0 : indexToInsert;
indexToInsert += servicePath.length(); indexToInsert += servicePath.length();
} }
path.insert(indexToInsert, "/" + payload.toString()); path.insert(indexToInsert, "/" + payloadAsString);
builder.replacePath(path.toString()); builder.replacePath(path.toString());
return (R) request.toBuilder().endpoint(builder.buildFromEncodedMap(ImmutableMap.<String, Object> of())) return (R) request.toBuilder().endpoint(builder.buildFromEncodedMap(ImmutableMap.<String, Object> of()))
.build(); .build();

View File

@ -33,8 +33,8 @@ import java.lang.annotation.Annotation;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Locale; import java.util.Locale;
import java.util.Set;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
@ -161,8 +161,7 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign
} }
appendAmzHeaders(canonicalizedHeaders, buffer); appendAmzHeaders(canonicalizedHeaders, buffer);
if (isVhostStyle) appendBucketName(request, buffer);
appendBucketName(request, buffer);
appendUriPath(request, buffer); appendUriPath(request, buffer);
if (signatureWire.enabled()) if (signatureWire.enabled())
signatureWire.output(buffer.toString()); signatureWire.output(buffer.toString());
@ -232,19 +231,14 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign
@VisibleForTesting @VisibleForTesting
void appendBucketName(HttpRequest req, StringBuilder toSign) { void appendBucketName(HttpRequest req, StringBuilder toSign) {
checkArgument(req instanceof GeneratedHttpRequest<?>, "this should be a generated http request"); String bucketName = getBucketName(req);
GeneratedHttpRequest<?> request = GeneratedHttpRequest.class.cast(req);
String bucketName = null; // If we have a payload/bucket/container that is not all lowercase, vhost-style URLs are not an option and must be
// automatically converted to their path-based equivalent. This should only be possible for AWS-S3 since it is
for (int i = 0; i < request.getJavaMethod().getParameterAnnotations().length; i++) { // the only S3 implementation configured to allow uppercase payload/bucket/container names.
if (any(Arrays.asList(request.getJavaMethod().getParameterAnnotations()[i]), ANNOTATIONTYPE_BUCKET)) { //
bucketName = (String) request.getArgs().get(i); // http://code.google.com/p/jclouds/issues/detail?id=992
break; if (isVhostStyle && bucketName!= null && bucketName.equals(bucketName.toLowerCase()))
}
}
if (bucketName != null)
toSign.append(servicePath).append(bucketName); toSign.append(servicePath).append(bucketName);
} }
@ -271,4 +265,21 @@ public class RequestAuthorizeSignature implements HttpRequestFilter, RequestSign
} }
} }
} }
private String getBucketName(HttpRequest req) {
checkArgument(req instanceof GeneratedHttpRequest<?>, "this should be a generated http request");
GeneratedHttpRequest<?> request = GeneratedHttpRequest.class.cast(req);
String bucketName = null;
for (int i = 0; i < request.getJavaMethod().getParameterAnnotations().length; i++) {
if (any(Arrays.asList(request.getJavaMethod().getParameterAnnotations()[i]), ANNOTATIONTYPE_BUCKET)) {
bucketName = (String) request.getArgs().get(i);
break;
}
}
return bucketName;
}
} }

View File

@ -25,12 +25,14 @@ import static com.google.common.collect.Lists.newArrayList;
import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH; import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;
import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS; import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;
import java.net.URI;
import java.util.List; import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.jclouds.aws.domain.AWSError; import org.jclouds.aws.domain.AWSError;
import org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent; import org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent;
import org.jclouds.aws.util.AWSUtils; import org.jclouds.aws.util.AWSUtils;
@ -39,9 +41,7 @@ import org.jclouds.blobstore.KeyNotFoundException;
import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.s3.S3ApiMetadata;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -54,7 +54,7 @@ public class ParseS3ErrorFromXmlContent extends ParseAWSErrorFromXmlContent {
private final boolean isVhostStyle; private final boolean isVhostStyle;
@Inject @Inject
ParseS3ErrorFromXmlContent(AWSUtils utils, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, public ParseS3ErrorFromXmlContent(AWSUtils utils, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath) { @Named(PROPERTY_S3_SERVICE_PATH) String servicePath) {
super(utils); super(utils);
this.servicePath = servicePath; this.servicePath = servicePath;
@ -66,8 +66,19 @@ public class ParseS3ErrorFromXmlContent extends ParseAWSErrorFromXmlContent {
switch (response.getStatusCode()) { switch (response.getStatusCode()) {
case 404: case 404:
if (!command.getCurrentRequest().getMethod().equals("DELETE")) { if (!command.getCurrentRequest().getMethod().equals("DELETE")) {
// If we have a payload/bucket/container that is not all lowercase, vhost-style URLs are not an option
// and must be automatically converted to their path-based equivalent. This should only be possible for
// AWS-S3 since it is the only S3 implementation configured to allow uppercase payload/bucket/container
// names.
//
// http://code.google.com/p/jclouds/issues/detail?id=992
URI defaultS3Endpoint = URI.create(new S3ApiMetadata().getDefaultEndpoint().get());
URI requestEndpoint = command.getCurrentRequest().getEndpoint();
boolean wasPathBasedRequest = requestEndpoint.getHost().contains(defaultS3Endpoint.getHost()) &&
requestEndpoint.getHost().equals(defaultS3Endpoint.getHost());
exception = new ResourceNotFoundException(message, exception); exception = new ResourceNotFoundException(message, exception);
if (isVhostStyle) { if (isVhostStyle && !wasPathBasedRequest) {
String container = command.getCurrentRequest().getEndpoint().getHost(); String container = command.getCurrentRequest().getEndpoint().getHost();
String key = command.getCurrentRequest().getEndpoint().getPath(); String key = command.getCurrentRequest().getEndpoint().getPath();
if (key == null || key.equals("/")) if (key == null || key.equals("/"))

View File

@ -40,7 +40,7 @@ import com.google.inject.Singleton;
public class BucketNameValidator extends DnsNameValidator { public class BucketNameValidator extends DnsNameValidator {
@Inject @Inject
BucketNameValidator() { public BucketNameValidator() {
super(3, 63); super(3, 63);
} }

View File

@ -20,17 +20,12 @@ package org.jclouds.openstack.swift;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.CREDENTIAL_TYPE;
import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.SERVICE_TYPE;
import java.net.URI; import java.net.URI;
import java.util.Properties; import java.util.Properties;
import org.jclouds.apis.ApiMetadata; import org.jclouds.apis.ApiMetadata;
import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.BlobStoreContext;
import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes;
import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties;
import org.jclouds.openstack.services.ServiceType;
import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule;
import org.jclouds.openstack.swift.config.SwiftRestClientModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule;
import org.jclouds.openstack.swift.config.SwiftRestClientModule.StorageEndpointModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule.StorageEndpointModule;
@ -69,12 +64,8 @@ public class SwiftApiMetadata extends BaseRestApiMetadata {
public static Properties defaultProperties() { public static Properties defaultProperties() {
Properties properties = BaseRestApiMetadata.defaultProperties(); Properties properties = BaseRestApiMetadata.defaultProperties();
properties.setProperty(SERVICE_TYPE, ServiceType.OBJECT_STORE);
// TODO: this doesn't actually do anything yet.
properties.setProperty(KeystoneProperties.VERSION, "2.0");
properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.API_ACCESS_KEY_CREDENTIALS);
properties.setProperty(PROPERTY_REGIONS, "DEFAULT");
properties.setProperty(PROPERTY_USER_METADATA_PREFIX, "X-Object-Meta-"); properties.setProperty(PROPERTY_USER_METADATA_PREFIX, "X-Object-Meta-");
properties.setProperty(PROPERTY_REGIONS, "DEFAULT");
return properties; return properties;
} }
@ -82,8 +73,8 @@ public class SwiftApiMetadata extends BaseRestApiMetadata {
protected Builder(Class<?> syncClient, Class<?> asyncClient){ protected Builder(Class<?> syncClient, Class<?> asyncClient){
super(syncClient, asyncClient); super(syncClient, asyncClient);
id("swift") id("swift")
.name("OpenStack Swift Pre-Diablo API") .name("OpenStack Swift with SwiftAuth")
.identityName("tenantName:user or user") .identityName("tenantId:user")
.credentialName("password") .credentialName("password")
.documentation(URI.create("http://api.openstack.org/")) .documentation(URI.create("http://api.openstack.org/"))
.version("1.0") .version("1.0")

View File

@ -19,10 +19,15 @@
package org.jclouds.openstack.swift; package org.jclouds.openstack.swift;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.CREDENTIAL_TYPE;
import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.SERVICE_TYPE;
import java.util.Properties; import java.util.Properties;
import org.jclouds.apis.ApiMetadata; import org.jclouds.apis.ApiMetadata;
import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes;
import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties;
import org.jclouds.openstack.services.ServiceType;
import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule;
import org.jclouds.openstack.swift.config.SwiftKeystoneRestClientModule; import org.jclouds.openstack.swift.config.SwiftKeystoneRestClientModule;
import org.jclouds.openstack.swift.config.SwiftRestClientModule.KeystoneStorageEndpointModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule.KeystoneStorageEndpointModule;
@ -64,6 +69,10 @@ public class SwiftKeystoneApiMetadata extends SwiftApiMetadata {
public static Properties defaultProperties() { public static Properties defaultProperties() {
Properties properties = SwiftApiMetadata.defaultProperties(); Properties properties = SwiftApiMetadata.defaultProperties();
properties.setProperty(SERVICE_TYPE, ServiceType.OBJECT_STORE);
// TODO: this doesn't actually do anything yet.
properties.setProperty(KeystoneProperties.VERSION, "2.0");
properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.API_ACCESS_KEY_CREDENTIALS);
properties.remove(PROPERTY_REGIONS); properties.remove(PROPERTY_REGIONS);
return properties; return properties;
} }
@ -72,6 +81,9 @@ public class SwiftKeystoneApiMetadata extends SwiftApiMetadata {
protected Builder(){ protected Builder(){
super(SwiftKeystoneClient.class, SwiftKeystoneAsyncClient.class); super(SwiftKeystoneClient.class, SwiftKeystoneAsyncClient.class);
id("swift-keystone") id("swift-keystone")
.name("OpenStack Swift with Keystone authentication")
.identityName("tenantName:user or user")
.credentialName("password")
.context(CONTEXT_TOKEN) .context(CONTEXT_TOKEN)
.defaultModules(ImmutableSet.<Class<? extends Module>>of(KeystoneStorageEndpointModule.class, SwiftKeystoneRestClientModule.class, SwiftBlobStoreContextModule.class)); .defaultModules(ImmutableSet.<Class<? extends Module>>of(KeystoneStorageEndpointModule.class, SwiftKeystoneRestClientModule.class, SwiftBlobStoreContextModule.class));
} }

View File

@ -0,0 +1,73 @@
/**
* 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.openstack.swift;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.swift.internal.BaseSwiftExpectTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
/**
*
* @author Adrian Cole
*/
@Test(testName = "SwiftClientExpectTest")
public class SwiftClientExpectTest extends BaseSwiftExpectTest<SwiftClient> {
public void testContainerExistsWhenResponseIs2xxReturnsTrue() throws Exception {
HttpRequest headContainer = HttpRequest.builder()
.method("HEAD")
.endpoint(URI.create(swiftEndpointWithHostReplaced + "/foo"))
.headers(
ImmutableMultimap.<String, String> builder()
.put("X-Auth-Token", authToken).build()).build();
HttpResponse headContainerResponse = HttpResponse.builder().statusCode(200).build();
SwiftClient clientWhenContainerExists = requestsSendResponses(authRequest,
authResponse, headContainer, headContainerResponse);
assertTrue(clientWhenContainerExists.containerExists("foo"));
}
public void testContainerExistsWhenResponseIs404ReturnsFalse() throws Exception {
HttpRequest headContainer = HttpRequest.builder()
.method("HEAD")
.endpoint(URI.create(swiftEndpointWithHostReplaced + "/foo"))
.headers(
ImmutableMultimap.<String, String> builder()
.put("X-Auth-Token", authToken).build()).build();
HttpResponse headContainerResponse = HttpResponse.builder().statusCode(404).build();
SwiftClient clientWhenContainerDoesntExist = requestsSendResponses(authRequest,
authResponse, headContainer, headContainerResponse);
assertFalse(clientWhenContainerDoesntExist.containerExists("foo"));
}
}

View File

@ -0,0 +1,75 @@
/**
* 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.openstack.swift.internal;
import java.net.URI;
import java.util.Properties;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.rest.internal.BaseRestClientExpectTest;
import com.google.common.collect.ImmutableMultimap;
/**
* Base class for writing Swift Expect tests
*
* @author Adrian Cole
*/
public class BaseSwiftExpectTest<T> extends BaseRestClientExpectTest<T> {
protected String endpoint = "http://myhost:8080/auth";
protected HttpRequest authRequest;
public BaseSwiftExpectTest() {
provider = "swift";
identity = "test:tester";
credential = "testing";
authRequest = HttpRequest.builder()
.method("GET")
.endpoint(URI.create(endpoint+ "/v1.0"))
.headers(ImmutableMultimap.<String, String>builder()
.put("X-Auth-User", identity)
.put("X-Auth-Key", credential)
.put("Accept", "*/*")
.put("Host", "myhost:8080").build()).build();
}
protected String authToken = "AUTH_tk36dabe83ca744cc296a98ec46089ec35";
protected String swiftEndpoint = "http://127.0.0.1:8080/v1/AUTH_test";
/**
* often swift returns the localhost url when requested via a dns name. this
* test ensures that replacement works.
*/
protected String swiftEndpointWithHostReplaced = swiftEndpoint.replace("127.0.0.1", "myhost");
protected HttpResponse authResponse = HttpResponse.builder()
.statusCode(200)
.message("HTTP/1.1 200 OK")
.headers(ImmutableMultimap.<String, String>builder()
.put("X-Storage-Url", swiftEndpoint)
.put("X-Auth-Token", authToken).build()).build();
protected Properties setupProperties() {
Properties props = super.setupProperties();
props.put(provider+".endpoint", endpoint);
return props;
}
}

View File

@ -36,6 +36,7 @@ import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.ovf.Envelope; import org.jclouds.ovf.Envelope;
import org.jclouds.util.Throwables2;
import org.jclouds.vcloud.TaskInErrorStateException; import org.jclouds.vcloud.TaskInErrorStateException;
import org.jclouds.vcloud.TaskStillRunningException; import org.jclouds.vcloud.TaskStillRunningException;
import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.VCloudClient;
@ -109,6 +110,14 @@ public class VCloudComputeServiceAdapter implements ComputeServiceAdapter<VApp,
} catch (IllegalArgumentException e){ } catch (IllegalArgumentException e){
logger.warn("Unsupported: "+ e.getMessage()); logger.warn("Unsupported: "+ e.getMessage());
return false; return false;
} catch (RuntimeException e) {
IllegalArgumentException e2 = Throwables2.getFirstThrowableOfType(e, IllegalArgumentException.class);
if (e2 != null) {
logger.warn("Unsupported: "+ e2.getMessage());
return false;
} else {
throw e;
}
} }
return true; return true;
} }

View File

@ -70,13 +70,13 @@ public class CatalogHandler extends ParseSax.HandlerWithResult<Catalog> {
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (qName.equals("Catalog")) { if (SaxUtils.equalsOrSuffix(qName, "Catalog")) {
catalog = newReferenceType(attributes, VCloudMediaType.CATALOG_XML); catalog = newReferenceType(attributes, VCloudMediaType.CATALOG_XML);
} else if (qName.equals("CatalogItem")) { } else if (SaxUtils.equalsOrSuffix(qName, "CatalogItem")) {
putReferenceType(contents, attributes); putReferenceType(contents, attributes);
} else if (qName.equals("Link") && "up".equals(attributes.get("rel"))) { } else if (SaxUtils.equalsOrSuffix(qName, "Link") && "up".equals(attributes.get("rel"))) {
org = newReferenceType(attributes); org = newReferenceType(attributes);
} else if (qName.equals("Link") && "add".equals(attributes.get("rel"))) { } else if (SaxUtils.equalsOrSuffix(qName, "Link") && "add".equals(attributes.get("rel"))) {
readOnly = false; readOnly = false;
} else { } else {
taskHandler.startElement(uri, localName, qName, attrs); taskHandler.startElement(uri, localName, qName, attrs);
@ -85,11 +85,11 @@ public class CatalogHandler extends ParseSax.HandlerWithResult<Catalog> {
public void endElement(String uri, String name, String qName) { public void endElement(String uri, String name, String qName) {
taskHandler.endElement(uri, name, qName); taskHandler.endElement(uri, name, qName);
if (qName.equals("Task")) { if (SaxUtils.equalsOrSuffix(qName, "Task")) {
this.tasks.add(taskHandler.getResult()); this.tasks.add(taskHandler.getResult());
} else if (qName.equals("Description")) { } else if (SaxUtils.equalsOrSuffix(qName, "Description")) {
description = currentOrNull(); description = currentOrNull();
} else if (qName.equals("IsPublished")) { } else if (SaxUtils.equalsOrSuffix(qName, "IsPublished")) {
published = Boolean.parseBoolean(currentOrNull()); published = Boolean.parseBoolean(currentOrNull());
} }
currentText = new StringBuilder(); currentText = new StringBuilder();

View File

@ -53,19 +53,19 @@ public class CatalogItemHandler extends ParseSax.HandlerWithResult<CatalogItem>
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (qName.equals("CatalogItem")) { if (SaxUtils.equalsOrSuffix(qName, "CatalogItem")) {
catalogItem = newReferenceType(attributes); catalogItem = newReferenceType(attributes);
} else if (qName.equals("Entity")) { } else if (SaxUtils.equalsOrSuffix(qName, ("Entity"))) {
entity = newReferenceType(attributes); entity = newReferenceType(attributes);
} else if (qName.equals("Property")) { } else if (SaxUtils.equalsOrSuffix(qName, ("Property"))) {
key = attributes.get("key"); key = attributes.get("key");
} }
} }
public void endElement(String uri, String name, String qName) { public void endElement(String uri, String name, String qName) {
if (qName.equals("Description")) { if (SaxUtils.equalsOrSuffix(qName, ("Description"))) {
description = currentOrNull(); description = currentOrNull();
} else if (qName.equals("Property")) { } else if (SaxUtils.equalsOrSuffix(qName, ("Property"))) {
properties.put(key, currentOrNull()); properties.put(key, currentOrNull());
key = null; key = null;
} }

View File

@ -40,7 +40,7 @@ public class ErrorHandler extends ParseSax.HandlerWithResult<VCloudError> {
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (qName.equals("Error")) { if (SaxUtils.equalsOrSuffix(qName, "Error")) {
error = Utils.newError(attributes); error = Utils.newError(attributes);
} }
} }

View File

@ -145,13 +145,13 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (qName.equals("OrgNetwork")) { if (SaxUtils.equalsOrSuffix(qName, "OrgNetwork")) {
network = newReferenceType(attributes); network = newReferenceType(attributes);
} else if (qName.equals("FirewallRule")) { } else if (SaxUtils.equalsOrSuffix(qName, "FirewallRule")) {
this.inFirewallRule = true; this.inFirewallRule = true;
} else if (qName.equals("ParentNetwork")) { } else if (SaxUtils.equalsOrSuffix(qName, "ParentNetwork")) {
parentNetwork = newReferenceType(attributes); parentNetwork = newReferenceType(attributes);
} else if (qName.equals("Link") && "up".equals(attributes.get("rel"))) { } else if (SaxUtils.equalsOrSuffix(qName, "Link") && "up".equals(attributes.get("rel"))) {
org = newReferenceType(attributes); org = newReferenceType(attributes);
} else { } else {
taskHandler.startElement(uri, localName, qName, attrs); taskHandler.startElement(uri, localName, qName, attrs);
@ -166,38 +166,38 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
public void endElement(String uri, String name, String qName) { public void endElement(String uri, String name, String qName) {
taskHandler.endElement(uri, name, qName); taskHandler.endElement(uri, name, qName);
if (qName.equals("Task")) { if (SaxUtils.equalsOrSuffix(qName, "Task")) {
this.tasks.add(taskHandler.getResult()); this.tasks.add(taskHandler.getResult());
} else if (qName.equals("Description")) { } else if (SaxUtils.equalsOrSuffix(qName, "Description")) {
if (inFirewallRule) if (inFirewallRule)
firewallRuleDescription = currentOrNull(); firewallRuleDescription = currentOrNull();
else else
orgDescription = currentOrNull(); orgDescription = currentOrNull();
} else if (qName.equals("FenceMode")) { } else if (SaxUtils.equalsOrSuffix(qName, "FenceMode")) {
fenceMode = FenceMode.fromValue(currentOrNull()); fenceMode = FenceMode.fromValue(currentOrNull());
} else if (qName.equals("StartAddress")) { } else if (SaxUtils.equalsOrSuffix(qName, "StartAddress")) {
startAddress = currentOrNull(); startAddress = currentOrNull();
} else if (qName.equals("EndAddress")) { } else if (SaxUtils.equalsOrSuffix(qName, "EndAddress")) {
endAddress = currentOrNull(); endAddress = currentOrNull();
} else if (qName.equals("AllocatedIpAddress")) { } else if (SaxUtils.equalsOrSuffix(qName, "AllocatedIpAddress")) {
allocatedIpAddresses.add(currentOrNull()); allocatedIpAddresses.add(currentOrNull());
} else if (qName.equals("IpRange")) { } else if (SaxUtils.equalsOrSuffix(qName, "IpRange")) {
ipRanges.add(new IpRange(startAddress, endAddress)); ipRanges.add(new IpRange(startAddress, endAddress));
this.startAddress = null; this.startAddress = null;
this.endAddress = null; this.endAddress = null;
} else if (qName.equals("IsInherited")) { } else if (SaxUtils.equalsOrSuffix(qName, "IsInherited")) {
inherited = Boolean.parseBoolean(currentOrNull()); inherited = Boolean.parseBoolean(currentOrNull());
} else if (qName.equals("Gateway")) { } else if (SaxUtils.equalsOrSuffix(qName, "Gateway")) {
gateway = currentOrNull(); gateway = currentOrNull();
} else if (qName.equals("Netmask")) { } else if (SaxUtils.equalsOrSuffix(qName, "Netmask")) {
netmask = currentOrNull(); netmask = currentOrNull();
} else if (qName.equals("Dns1")) { } else if (SaxUtils.equalsOrSuffix(qName, "Dns1")) {
dns1 = currentOrNull(); dns1 = currentOrNull();
} else if (qName.equals("Dns2")) { } else if (SaxUtils.equalsOrSuffix(qName, "Dns2")) {
dns2 = currentOrNull(); dns2 = currentOrNull();
} else if (qName.equals("DnsSuffix")) { } else if (SaxUtils.equalsOrSuffix(qName, "DnsSuffix")) {
dnsSuffix = currentOrNull(); dnsSuffix = currentOrNull();
} else if (qName.equals("IpScope")) { } else if (SaxUtils.equalsOrSuffix(qName, "IpScope")) {
ipScope = new IpScope(inherited, gateway, netmask, dns1, dns2, dnsSuffix, ipRanges, allocatedIpAddresses); ipScope = new IpScope(inherited, gateway, netmask, dns1, dns2, dnsSuffix, ipRanges, allocatedIpAddresses);
this.inherited = false; this.inherited = false;
this.gateway = null; this.gateway = null;
@ -207,38 +207,38 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
this.dnsSuffix = null; this.dnsSuffix = null;
this.ipRanges = Sets.newLinkedHashSet(); this.ipRanges = Sets.newLinkedHashSet();
this.allocatedIpAddresses = Sets.newLinkedHashSet(); this.allocatedIpAddresses = Sets.newLinkedHashSet();
} else if (qName.equals("IsEnabled")) { } else if (SaxUtils.equalsOrSuffix(qName, "IsEnabled")) {
if (inFirewallRule) if (inFirewallRule)
firewallRuleEnabled = Boolean.parseBoolean(currentOrNull()); firewallRuleEnabled = Boolean.parseBoolean(currentOrNull());
else else
serviceEnabled = Boolean.parseBoolean(currentOrNull()); serviceEnabled = Boolean.parseBoolean(currentOrNull());
} else if (qName.equals("DefaultLeaseTime")) { } else if (SaxUtils.equalsOrSuffix(qName, "DefaultLeaseTime")) {
defaultLeaseTime = Integer.parseInt(currentOrNull()); defaultLeaseTime = Integer.parseInt(currentOrNull());
} else if (qName.equals("MaxLeaseTime")) { } else if (SaxUtils.equalsOrSuffix(qName, "MaxLeaseTime")) {
maxLeaseTime = Integer.parseInt(currentOrNull()); maxLeaseTime = Integer.parseInt(currentOrNull());
} else if (qName.equals("DhcpService")) { } else if (SaxUtils.equalsOrSuffix(qName, "DhcpService")) {
this.dhcpService = new DhcpService(serviceEnabled, defaultLeaseTime, maxLeaseTime, Iterables this.dhcpService = new DhcpService(serviceEnabled, defaultLeaseTime, maxLeaseTime, Iterables
.getOnlyElement(ipRanges)); .getOnlyElement(ipRanges));
this.serviceEnabled = false; this.serviceEnabled = false;
this.defaultLeaseTime = null; this.defaultLeaseTime = null;
this.maxLeaseTime = null; this.maxLeaseTime = null;
this.ipRanges = Sets.newLinkedHashSet(); this.ipRanges = Sets.newLinkedHashSet();
} else if (qName.equals("Policy")) { } else if (SaxUtils.equalsOrSuffix(qName, "Policy")) {
if (inFirewallRule) if (inFirewallRule)
firewallPolicy = FirewallPolicy.fromValue(currentOrNull()); firewallPolicy = FirewallPolicy.fromValue(currentOrNull());
else else
natPolicy = NatPolicy.fromValue(currentOrNull()); natPolicy = NatPolicy.fromValue(currentOrNull());
} else if (qName.equals("Tcp")) { } else if (SaxUtils.equalsOrSuffix(qName, "Tcp")) {
tcp = Boolean.parseBoolean(currentOrNull()); tcp = Boolean.parseBoolean(currentOrNull());
} else if (qName.equals("Udp")) { } else if (SaxUtils.equalsOrSuffix(qName, "Udp")) {
udp = Boolean.parseBoolean(currentOrNull()); udp = Boolean.parseBoolean(currentOrNull());
} else if (qName.equals("Protocols")) { } else if (SaxUtils.equalsOrSuffix(qName, "Protocols")) {
this.protocols = new FirewallProtocols(tcp, udp); this.protocols = new FirewallProtocols(tcp, udp);
this.tcp = false; this.tcp = false;
this.udp = false; this.udp = false;
} else if (qName.equals("DestinationIp")) { } else if (SaxUtils.equalsOrSuffix(qName, "DestinationIp")) {
this.destinationIp = currentOrNull(); this.destinationIp = currentOrNull();
} else if (qName.equals("FirewallRule")) { } else if (SaxUtils.equalsOrSuffix(qName, "FirewallRule")) {
this.inFirewallRule = false; this.inFirewallRule = false;
this.firewallRules.add(new FirewallRule(firewallRuleEnabled, firewallRuleDescription, firewallPolicy, this.firewallRules.add(new FirewallRule(firewallRuleEnabled, firewallRuleDescription, firewallPolicy,
protocols, port, destinationIp)); protocols, port, destinationIp));
@ -248,13 +248,13 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
this.protocols = null; this.protocols = null;
this.port = -1; this.port = -1;
this.destinationIp = null; this.destinationIp = null;
} else if (qName.equals("FirewallService")) { } else if (SaxUtils.equalsOrSuffix(qName, "FirewallService")) {
firewallService = new FirewallService(serviceEnabled, firewallRules); firewallService = new FirewallService(serviceEnabled, firewallRules);
this.serviceEnabled = false; this.serviceEnabled = false;
this.firewallRules = Lists.newArrayList(); this.firewallRules = Lists.newArrayList();
} else if (qName.equals("NatType")) { } else if (SaxUtils.equalsOrSuffix(qName, "NatType")) {
natType = NatType.fromValue(currentOrNull()); natType = NatType.fromValue(currentOrNull());
} else if (qName.equals("MappingMode")) { } else if (SaxUtils.equalsOrSuffix(qName, "MappingMode")) {
mappingMode = MappingMode.fromValue(currentOrNull()); mappingMode = MappingMode.fromValue(currentOrNull());
} else if (qName.equalsIgnoreCase("ExternalIP")) { } else if (qName.equalsIgnoreCase("ExternalIP")) {
externalIP = currentOrNull(); externalIP = currentOrNull();
@ -264,7 +264,7 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
vAppScopedLocalId = currentOrNull(); vAppScopedLocalId = currentOrNull();
} else if (qName.equalsIgnoreCase("vmNicId")) { } else if (qName.equalsIgnoreCase("vmNicId")) {
vmNicId = Integer.parseInt(currentOrNull()); vmNicId = Integer.parseInt(currentOrNull());
} else if (qName.equals("OneToOneVmRule")) { } else if (SaxUtils.equalsOrSuffix(qName, "OneToOneVmRule")) {
natRules.add(new OneToOneVmRule(mappingMode, externalIP, vAppScopedVmId, vmNicId)); natRules.add(new OneToOneVmRule(mappingMode, externalIP, vAppScopedVmId, vmNicId));
this.mappingMode = null; this.mappingMode = null;
this.externalIP = null; this.externalIP = null;
@ -278,14 +278,14 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
internalPort = Integer.parseInt(currentOrNull()); internalPort = Integer.parseInt(currentOrNull());
} else if (equalsOrSuffix(qName, "Protocol")) { } else if (equalsOrSuffix(qName, "Protocol")) {
natProtocol = NatProtocol.valueOf(currentOrNull()); natProtocol = NatProtocol.valueOf(currentOrNull());
} else if (qName.equals("PortForwardingRule")) { } else if (SaxUtils.equalsOrSuffix(qName, "PortForwardingRule")) {
natRules.add(new PortForwardingRule(externalIP, externalPort, internalIP, internalPort, natProtocol)); natRules.add(new PortForwardingRule(externalIP, externalPort, internalIP, internalPort, natProtocol));
this.externalIP = null; this.externalIP = null;
this.externalPort = -1; this.externalPort = -1;
this.internalIP = null; this.internalIP = null;
this.internalPort = -1; this.internalPort = -1;
this.natProtocol = null; this.natProtocol = null;
} else if (qName.equals("VmRule")) { } else if (SaxUtils.equalsOrSuffix(qName, "VmRule")) {
natRules.add(new VmRule(externalIP, externalPort, vAppScopedLocalId, vmNicId, internalPort, natProtocol)); natRules.add(new VmRule(externalIP, externalPort, vAppScopedLocalId, vmNicId, internalPort, natProtocol));
this.externalIP = null; this.externalIP = null;
this.externalPort = -1; this.externalPort = -1;
@ -293,24 +293,24 @@ public class OrgNetworkHandler extends ParseSax.HandlerWithResult<OrgNetwork> {
this.vmNicId = -1; this.vmNicId = -1;
this.internalPort = -1; this.internalPort = -1;
this.natProtocol = null; this.natProtocol = null;
} else if (qName.equals("NatService")) { } else if (SaxUtils.equalsOrSuffix(qName, "NatService")) {
this.natService = new NatService(serviceEnabled, natType, natPolicy, natRules); this.natService = new NatService(serviceEnabled, natType, natPolicy, natRules);
this.serviceEnabled = false; this.serviceEnabled = false;
this.natType = null; this.natType = null;
this.natPolicy = null; this.natPolicy = null;
this.natRules = Lists.newArrayList(); this.natRules = Lists.newArrayList();
} else if (qName.equals("Features")) { } else if (SaxUtils.equalsOrSuffix(qName, "Features")) {
this.features = new Features(dhcpService, firewallService, natService); this.features = new Features(dhcpService, firewallService, natService);
this.dhcpService = null; this.dhcpService = null;
this.firewallService = null; this.firewallService = null;
this.natService = null; this.natService = null;
} else if (qName.equals("Configuration")) { } else if (SaxUtils.equalsOrSuffix(qName, "Configuration")) {
configuration = new OrgNetworkImpl.ConfigurationImpl(ipScope, parentNetwork, fenceMode, features); configuration = new OrgNetworkImpl.ConfigurationImpl(ipScope, parentNetwork, fenceMode, features);
this.ipScope = null; this.ipScope = null;
this.parentNetwork = null; this.parentNetwork = null;
this.fenceMode = null; this.fenceMode = null;
this.features = null; this.features = null;
} else if (qName.equals("AllowedExternalIpAddress")) { } else if (SaxUtils.equalsOrSuffix(qName, "AllowedExternalIpAddress")) {
allowedExternalIpAddresses.add(currentOrNull()); allowedExternalIpAddresses.add(currentOrNull());
} }
currentText = new StringBuilder(); currentText = new StringBuilder();

View File

@ -22,6 +22,7 @@ import java.net.URI;
import java.util.SortedMap; import java.util.SortedMap;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.util.SaxUtils;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
@ -40,11 +41,11 @@ public class SupportedVersionsHandler extends ParseSax.HandlerWithResult<SortedM
} }
public void endElement(String uri, String name, String qName) { public void endElement(String uri, String name, String qName) {
if (qName.equals("Version")) { if (SaxUtils.equalsOrSuffix(qName, "Version")) {
version = currentOrNull(); version = currentOrNull();
} else if (qName.equals("LoginUrl")) { } else if (SaxUtils.equalsOrSuffix(qName, "LoginUrl")) {
location = URI.create(currentOrNull()); location = URI.create(currentOrNull());
} else if (qName.equals("VersionInfo")) { } else if (SaxUtils.equalsOrSuffix(qName, "VersionInfo")) {
contents.put(version, location); contents.put(version, location);
} }
currentText = new StringBuilder(); currentText = new StringBuilder();

View File

@ -56,9 +56,9 @@ public class TasksListHandler extends ParseSax.HandlerWithResult<TasksList> {
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (qName.equals("TasksList")) { if (SaxUtils.equalsOrSuffix(qName, "TasksList")) {
resource = Utils.newReferenceType(attributes); resource = Utils.newReferenceType(attributes);
} else if (qName.equals("Link") && "self".equals(attributes.get("rel"))) { } else if (SaxUtils.equalsOrSuffix(qName, "Link") && "self".equals(attributes.get("rel"))) {
resource = Utils.newReferenceType(attributes); resource = Utils.newReferenceType(attributes);
} else { } else {
taskHandler.startElement(uri, localName, qName, attrs); taskHandler.startElement(uri, localName, qName, attrs);
@ -68,7 +68,7 @@ public class TasksListHandler extends ParseSax.HandlerWithResult<TasksList> {
@Override @Override
public void endElement(String uri, String localName, String qName) throws SAXException { public void endElement(String uri, String localName, String qName) throws SAXException {
taskHandler.endElement(uri, localName, qName); taskHandler.endElement(uri, localName, qName);
if (qName.equals("Task")) { if (SaxUtils.equalsOrSuffix(qName, "Task")) {
this.tasks.add(taskHandler.getResult()); this.tasks.add(taskHandler.getResult());
} }
} }

View File

@ -113,12 +113,12 @@ public class VmHandler extends ParseSax.HandlerWithResult<Vm> {
guestCustomizationHandler.startElement(uri, localName, qName, attrs); guestCustomizationHandler.startElement(uri, localName, qName, attrs);
} else if (inTasks) { } else if (inTasks) {
taskHandler.startElement(uri, localName, qName, attrs); taskHandler.startElement(uri, localName, qName, attrs);
} else if (qName.equals("Vm")) { } else if (SaxUtils.equalsOrSuffix(qName, "Vm")) {
vm = newReferenceType(attributes); vm = newReferenceType(attributes);
String status = attributes.get("status"); String status = attributes.get("status");
if (status != null) if (status != null)
this.status = Status.fromValue(Integer.parseInt(status)); this.status = Status.fromValue(Integer.parseInt(status));
} else if (qName.equals("Link") && "up".equals(attributes.get("rel"))) { } else if (SaxUtils.equalsOrSuffix(qName, "Link") && "up".equals(attributes.get("rel"))) {
vdc = newReferenceType(attributes); vdc = newReferenceType(attributes);
} }
} }
@ -150,9 +150,9 @@ public class VmHandler extends ParseSax.HandlerWithResult<Vm> {
networkConnectionSectionHandler.endElement(uri, name, qName); networkConnectionSectionHandler.endElement(uri, name, qName);
} else if (inTasks) { } else if (inTasks) {
taskHandler.endElement(uri, name, qName); taskHandler.endElement(uri, name, qName);
} else if (qName.equals("Description")) { } else if (SaxUtils.equalsOrSuffix(qName, "Description")) {
description = currentOrNull(); description = currentOrNull();
} else if (qName.equals("VAppScopedLocalId")) { } else if (SaxUtils.equalsOrSuffix(qName, "VAppScopedLocalId")) {
vAppScopedLocalId = currentOrNull(); vAppScopedLocalId = currentOrNull();
} }
currentText = new StringBuilder(); currentText = new StringBuilder();

View File

@ -131,6 +131,10 @@ public abstract class BaseVCloudComputeServiceExpectTest extends BaseRestClientE
.message("HTTP/1.1 200 OK").payload(payloadFromResourceWithContentType("/template1.0-vcd15.xml", VCloudMediaType.VAPPTEMPLATE_XML +";version=1.0")) .message("HTTP/1.1 200 OK").payload(payloadFromResourceWithContentType("/template1.0-vcd15.xml", VCloudMediaType.VAPPTEMPLATE_XML +";version=1.0"))
.build(); .build();
protected HttpResponse successfulVersion1_0GetVAppTemplateResponseFromVCD1_5WithMultipleVMsAndVDCParent = HttpResponse.builder().statusCode(200)
.message("HTTP/1.1 200 OK").payload(payloadFromResourceWithContentType("/template1.0-vcd15-multi-vm.xml", VCloudMediaType.VAPPTEMPLATE_XML +";version=1.0"))
.build();
protected HttpRequest version1_0GetOVFForVAppTemplateRequest = HttpRequest.builder().method("GET").endpoint( protected HttpRequest version1_0GetOVFForVAppTemplateRequest = HttpRequest.builder().method("GET").endpoint(
URI.create(ENDPOINT + "/v1.0/vAppTemplate/" + templateId + "/ovf")) URI.create(ENDPOINT + "/v1.0/vAppTemplate/" + templateId + "/ovf"))
.headers(ImmutableMultimap.<String, String> builder() .headers(ImmutableMultimap.<String, String> builder()
@ -141,6 +145,10 @@ public abstract class BaseVCloudComputeServiceExpectTest extends BaseRestClientE
.message("HTTP/1.1 200 OK").payload(payloadFromResourceWithContentType("/ovf-ubuntu64.xml", MediaType.TEXT_XML +";version=1.0")) .message("HTTP/1.1 200 OK").payload(payloadFromResourceWithContentType("/ovf-ubuntu64.xml", MediaType.TEXT_XML +";version=1.0"))
.build(); .build();
protected HttpResponse successfulVersion1_0GetOVFForVAppTemplateResponseFromVCD1_5WithMultipleVMs = HttpResponse.builder().statusCode(200)
.message("HTTP/1.1 200 OK").payload(payloadFromResourceWithContentType("/ovf-multi-vm.xml", MediaType.TEXT_XML +";version=1.0"))
.build();
public BaseVCloudComputeServiceExpectTest() { public BaseVCloudComputeServiceExpectTest() {
provider = "vcloud"; provider = "vcloud";
} }

View File

@ -0,0 +1,74 @@
package org.jclouds.vcloud.compute.strategy;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import java.util.Collections;
import org.jclouds.compute.ComputeService;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.vcloud.compute.BaseVCloudComputeServiceExpectTest;
import org.jclouds.vcloud.domain.VAppTemplate;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
public class VCloudComputeServiceAdapterTest extends BaseVCloudComputeServiceExpectTest {
@Test
public void testListHardwareProfiles() throws Exception {
ComputeService compute = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse> builder()
.put(versionsRequest, versionsResponseFromVCD1_5)
.put(version1_0LoginRequest, successfulVersion1_0LoginResponseFromVCD1_5WithSingleOrg)
.put(version1_0GetOrgRequest, successfulVersion1_0GetOrgResponseFromVCD1_5WithSingleTasksListVDCAndNetwork)
.put(version1_0GetCatalogRequest, successfulVersion1_0GetCatalogResponseFromVCD1_5WithSingleTemplate)
.put(version1_0GetCatalogItemRequest, successfulVersion1_0GetCatalogItemResponseFromVCD1_5ForTemplate)
.put(version1_0GetVDCRequest, successfulVersion1_0GetVDCResponseFromVCD1_5WithSingleTemplateAndNetwork)
.put(version1_0GetVAppTemplateRequest, successfulVersion1_0GetVAppTemplateResponseFromVCD1_5WithSingleVMAndVDCParent)
.put(version1_0GetOVFForVAppTemplateRequest, successfulVersion1_0GetOVFForVAppTemplateResponseFromVCD1_5WithSingleVM)
.build());
VCloudComputeServiceAdapter adapter = compute.getContext()
.utils().injector().getInstance(VCloudComputeServiceAdapter.class);
Iterable<VAppTemplate> hardwareProfiles = adapter.listHardwareProfiles();
Iterable<URI> hardwareProfileRefs = Iterables.transform(ImmutableList.copyOf(hardwareProfiles), new Function<VAppTemplate,URI>() {
@Override public URI apply(VAppTemplate input) {
return input.getHref();
}
});
assertEquals(ImmutableSet.copyOf(hardwareProfileRefs), ImmutableSet.of(URI.create("https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728")));
}
/**
* For issue 994. In BaseEnvelopeHandler when it encounters VirtualSystemCollection, it throws IllegalArgumentException
* (cannot currently create envelopes with multiple virtual systems).
* Thus we do not include the VM in the supported set, but we do return without propagating the exception.
*/
@Test
public void testListHardwareProfilesWithUnsupportedTemplate() throws Exception {
ComputeService compute = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse> builder()
.put(versionsRequest, versionsResponseFromVCD1_5)
.put(version1_0LoginRequest, successfulVersion1_0LoginResponseFromVCD1_5WithSingleOrg)
.put(version1_0GetOrgRequest, successfulVersion1_0GetOrgResponseFromVCD1_5WithSingleTasksListVDCAndNetwork)
.put(version1_0GetCatalogRequest, successfulVersion1_0GetCatalogResponseFromVCD1_5WithSingleTemplate)
.put(version1_0GetCatalogItemRequest, successfulVersion1_0GetCatalogItemResponseFromVCD1_5ForTemplate)
.put(version1_0GetVDCRequest, successfulVersion1_0GetVDCResponseFromVCD1_5WithSingleTemplateAndNetwork)
.put(version1_0GetVAppTemplateRequest, successfulVersion1_0GetVAppTemplateResponseFromVCD1_5WithMultipleVMsAndVDCParent)
.put(version1_0GetOVFForVAppTemplateRequest, successfulVersion1_0GetOVFForVAppTemplateResponseFromVCD1_5WithMultipleVMs)
.build());
VCloudComputeServiceAdapter adapter = compute.getContext()
.utils().injector().getInstance(VCloudComputeServiceAdapter.class);
Iterable<VAppTemplate> hardwareProfiles = adapter.listHardwareProfiles();
assertEquals(ImmutableSet.copyOf(hardwareProfiles), Collections.emptySet());
}
}

View File

@ -59,4 +59,30 @@ public class CatalogItemHandlerTest {
))); )));
} }
public void testApplyInputStreamWithNamespaceUsingVcloud() {
InputStream is = getClass().getResourceAsStream("/catalogItem-carrenza-with-vcloud-namespace.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
CatalogItem result = factory.create(injector.getInstance(CatalogItemHandler.class)).parse(is);
assertEquals(result, new CatalogItemImpl("ubuntu10.10x64",
URI.create("https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3"),
null, new ReferenceTypeImpl("ubuntu10.10x64", "application/vnd.vmware.vcloud.vAppTemplate+xml",
URI.create("https://myvdc.carrenza.net/api/v1.0/vAppTemplate/vappTemplate-123766ea-2b55-482c-8adf-735ab1952834")),
ImmutableSortedMap.<String,String>of()));
}
public void testApplyInputStreamWithNamespaceUsingDefault() {
InputStream is = getClass().getResourceAsStream("/catalogItem-carrenza-with-default-namespace.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
CatalogItem result = factory.create(injector.getInstance(CatalogItemHandler.class)).parse(is);
assertEquals(result, new CatalogItemImpl("ubuntu10.10x64",
URI.create("https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3"),
null, new ReferenceTypeImpl("ubuntu10.10x64", "application/vnd.vmware.vcloud.vAppTemplate+xml",
URI.create("https://myvdc.carrenza.net/api/v1.0/vAppTemplate/vappTemplate-123766ea-2b55-482c-8adf-735ab1952834")),
ImmutableSortedMap.<String,String>of()));
}
} }

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<CatalogItem xmlns="http://www.vmware.com/vcloud/v1" name="ubuntu10.10x64" type="application/vnd.vmware.vcloud.catalogItem+xml" href="https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1 http://myvdc.carrenza.net/api/v1.0/schema/master.xsd">
<Link rel="up" type="application/vnd.vmware.vcloud.catalog+xml" href="https://myvdc.carrenza.net/api/v1.0/catalog/5d2c147a-d26d-487a-9a05-577ee175186b"/>
<Link rel="edit" type="application/vnd.vmware.vcloud.catalogItem+xml" href="https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3"/>
<Link rel="remove" href="https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3"/>
<Description> </Description>
<Entity type="application/vnd.vmware.vcloud.vAppTemplate+xml" name="ubuntu10.10x64" href="https://myvdc.carrenza.net/api/v1.0/vAppTemplate/vappTemplate-123766ea-2b55-482c-8adf-735ab1952834"/>
</CatalogItem>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<vcloud:CatalogItem xmlns:vcloud="http://www.vmware.com/vcloud/v1" name="ubuntu10.10x64" type="application/vnd.vmware.vcloud.catalogItem+xml" href="https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1 http://myvdc.carrenza.net/api/v1.0/schema/master.xsd">
<vcloud:Link rel="up" type="application/vnd.vmware.vcloud.catalog+xml" href="https://myvdc.carrenza.net/api/v1.0/catalog/5d2c147a-d26d-487a-9a05-577ee175186b"/>
<vcloud:Link rel="edit" type="application/vnd.vmware.vcloud.catalogItem+xml" href="https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3"/>
<vcloud:Link rel="remove" href="https://myvdc.carrenza.net/api/v1.0/catalogItem/ecd4d3a0-0d12-4195-a6d2-14cdf9f925a3"/>
<vcloud:Description> </vcloud:Description>
<vcloud:Entity type="application/vnd.vmware.vcloud.vAppTemplate+xml" name="ubuntu10.10x64" href="https://myvdc.carrenza.net/api/v1.0/vAppTemplate/vappTemplate-123766ea-2b55-482c-8adf-735ab1952834"/>
</vcloud:CatalogItem>

View File

@ -0,0 +1,285 @@
<?xml version="1.0" encoding="UTF-8"?>
<ovf:Envelope xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:vcloud="http://www.vmware.com/vcloud/v1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2.22.0/CIM_VirtualSystemSettingData.xsd http://schemas.dmtf.org/ovf/envelope/1 http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2.22.0/CIM_ResourceAllocationSettingData.xsd http://www.vmware.com/vcloud/v1 http://zone.myvcloud.com/api/v1.0/schema/master.xsd">
<ovf:References/>
<ovf:NetworkSection>
<ovf:Info>The list of logical networks</ovf:Info>
<ovf:Network ovf:name="vapp net">
<ovf:Description/>
</ovf:Network>
</ovf:NetworkSection>
<vcloud:NetworkConfigSection ovf:required="false">
<ovf:Info>The configuration parameters for logical networks</ovf:Info>
<vcloud:NetworkConfig networkName="vapp net">
<vcloud:Description/>
<vcloud:Configuration>
<vcloud:IpScope>
<vcloud:IsInherited>false</vcloud:IsInherited>
<vcloud:Gateway>192.168.2.1</vcloud:Gateway>
<vcloud:Netmask>255.255.255.0</vcloud:Netmask>
<vcloud:Dns1>195.225.219.131</vcloud:Dns1>
<vcloud:IpRanges>
<vcloud:IpRange>
<vcloud:StartAddress>192.168.2.100</vcloud:StartAddress>
<vcloud:EndAddress>192.168.2.199</vcloud:EndAddress>
</vcloud:IpRange>
</vcloud:IpRanges>
</vcloud:IpScope>
<vcloud:FenceMode>isolated</vcloud:FenceMode>
<vcloud:Features>
<vcloud:DhcpService>
<vcloud:IsEnabled>false</vcloud:IsEnabled>
<vcloud:DefaultLeaseTime>7200</vcloud:DefaultLeaseTime>
<vcloud:MaxLeaseTime>7200</vcloud:MaxLeaseTime>
<vcloud:IpRange/>
</vcloud:DhcpService>
</vcloud:Features>
</vcloud:Configuration>
<vcloud:IsDeployed>false</vcloud:IsDeployed>
</vcloud:NetworkConfig>
</vcloud:NetworkConfigSection>
<vcloud:LeaseSettingsSection ovf:required="false">
<ovf:Info>Lease settings section</ovf:Info>
<vcloud:DeploymentLeaseInSeconds>0</vcloud:DeploymentLeaseInSeconds>
<vcloud:StorageLeaseInSeconds>0</vcloud:StorageLeaseInSeconds>
</vcloud:LeaseSettingsSection>
<vcloud:CustomizationSection ovf:required="false">
<ovf:Info>VApp template customization section</ovf:Info>
<vcloud:CustomizeOnInstantiate>true</vcloud:CustomizeOnInstantiate>
</vcloud:CustomizationSection>
<ovf:VirtualSystemCollection ovf:id="centos-web/db-5.5">
<ovf:Info>A collection of virtual machines: </ovf:Info>
<ovf:Name>centos-web/db-5.5</ovf:Name>
<ovf:StartupSection>
<ovf:Info>VApp startup section</ovf:Info>
<ovf:Item ovf:stopDelay="0" ovf:stopAction="powerOff" ovf:startDelay="0" ovf:startAction="powerOn" ovf:order="0" ovf:id="centos-web"/>
<ovf:Item ovf:stopDelay="0" ovf:stopAction="powerOff" ovf:startDelay="0" ovf:startAction="powerOn" ovf:order="0" ovf:id="centos-db"/>
</ovf:StartupSection>
<ovf:VirtualSystem ovf:id="centos-db">
<ovf:Info>A virtual machine: </ovf:Info>
<ovf:Name>centos-db</ovf:Name>
<ovf:OperatingSystemSection xmlns:vmw="http://www.vmware.com/schema/ovf" ovf:id="100" vmw:osType="other26xLinux64Guest">
<ovf:Info>Specifies the operating system installed</ovf:Info>
<ovf:Description>Other 2.6x Linux (64-bit)</ovf:Description>
</ovf:OperatingSystemSection>
<ovf:VirtualHardwareSection>
<ovf:Info>Virtual hardware requirements</ovf:Info>
<ovf:System>
<vssd:ElementName>Virtual Hardware Family</vssd:ElementName>
<vssd:InstanceID>0</vssd:InstanceID>
<vssd:VirtualSystemIdentifier>centos-db</vssd:VirtualSystemIdentifier>
<vssd:VirtualSystemType>vmx-07</vssd:VirtualSystemType>
</ovf:System>
<ovf:Item>
<rasd:Address>00:50:56:01:06:81</rasd:Address>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
<rasd:Connection vcloud:ipAddress="192.168.2.100" vcloud:primaryNetworkConnection="true" vcloud:ipAddressingMode="POOL">vapp net</rasd:Connection>
<rasd:Description>PCNet32 ethernet adapter</rasd:Description>
<rasd:ElementName>Network adapter 0</rasd:ElementName>
<rasd:InstanceID>1</rasd:InstanceID>
<rasd:ResourceSubType>PCNet32</rasd:ResourceSubType>
<rasd:ResourceType>10</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:Address>0</rasd:Address>
<rasd:Description>SCSI Controller</rasd:Description>
<rasd:ElementName>SCSI Controller 0</rasd:ElementName>
<rasd:InstanceID>2</rasd:InstanceID>
<rasd:ResourceSubType>lsilogic</rasd:ResourceSubType>
<rasd:ResourceType>6</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:Description>Hard disk</rasd:Description>
<rasd:ElementName>Hard disk 1</rasd:ElementName>
<rasd:HostResource vcloud:capacity="8192" vcloud:busType="6" vcloud:busSubType="lsilogic"/>
<rasd:InstanceID>2000</rasd:InstanceID>
<rasd:Parent>2</rasd:Parent>
<rasd:ResourceType>17</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:Address>0</rasd:Address>
<rasd:Description>IDE Controller</rasd:Description>
<rasd:ElementName>IDE Controller 0</rasd:ElementName>
<rasd:InstanceID>3</rasd:InstanceID>
<rasd:ResourceType>5</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Description>CD/DVD Drive</rasd:Description>
<rasd:ElementName>CD/DVD Drive 1</rasd:ElementName>
<rasd:HostResource/>
<rasd:InstanceID>3000</rasd:InstanceID>
<rasd:Parent>3</rasd:Parent>
<rasd:ResourceType>15</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Description>Floppy Drive</rasd:Description>
<rasd:ElementName>Floppy Drive 1</rasd:ElementName>
<rasd:HostResource/>
<rasd:InstanceID>8000</rasd:InstanceID>
<rasd:ResourceType>14</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>
<rasd:Description>Number of Virtual CPUs</rasd:Description>
<rasd:ElementName>1 virtual CPU(s)</rasd:ElementName>
<rasd:InstanceID>4</rasd:InstanceID>
<rasd:Reservation>0</rasd:Reservation>
<rasd:ResourceType>3</rasd:ResourceType>
<rasd:VirtualQuantity>1</rasd:VirtualQuantity>
<rasd:Weight>0</rasd:Weight>
</ovf:Item>
<ovf:Item>
<rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>
<rasd:Description>Memory Size</rasd:Description>
<rasd:ElementName>2048 MB of memory</rasd:ElementName>
<rasd:InstanceID>5</rasd:InstanceID>
<rasd:Reservation>0</rasd:Reservation>
<rasd:ResourceType>4</rasd:ResourceType>
<rasd:VirtualQuantity>2048</rasd:VirtualQuantity>
<rasd:Weight>0</rasd:Weight>
</ovf:Item>
</ovf:VirtualHardwareSection>
<vcloud:NetworkConnectionSection ovf:required="false">
<ovf:Info>Specifies the available VM network connections</ovf:Info>
<vcloud:PrimaryNetworkConnectionIndex>0</vcloud:PrimaryNetworkConnectionIndex>
<vcloud:NetworkConnection network="vapp net">
<vcloud:NetworkConnectionIndex>0</vcloud:NetworkConnectionIndex>
<vcloud:IpAddress>192.168.2.100</vcloud:IpAddress>
<vcloud:IsConnected>true</vcloud:IsConnected>
<vcloud:MACAddress>00:50:56:01:06:81</vcloud:MACAddress>
<vcloud:IpAddressAllocationMode>POOL</vcloud:IpAddressAllocationMode>
</vcloud:NetworkConnection>
</vcloud:NetworkConnectionSection>
<vcloud:GuestCustomizationSection ovf:required="false">
<ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
<vcloud:Enabled>true</vcloud:Enabled>
<vcloud:ChangeSid>false</vcloud:ChangeSid>
<vcloud:JoinDomainEnabled>false</vcloud:JoinDomainEnabled>
<vcloud:UseOrgSettings>false</vcloud:UseOrgSettings>
<vcloud:AdminPasswordEnabled>false</vcloud:AdminPasswordEnabled>
<vcloud:AdminPasswordAuto>true</vcloud:AdminPasswordAuto>
<vcloud:ResetPasswordRequired>false</vcloud:ResetPasswordRequired>
<vcloud:ComputerName>centos-db</vcloud:ComputerName>
</vcloud:GuestCustomizationSection>
</ovf:VirtualSystem>
<ovf:VirtualSystem ovf:id="centos-web">
<ovf:Info>A virtual machine: </ovf:Info>
<ovf:Name>centos-web</ovf:Name>
<ovf:OperatingSystemSection xmlns:vmw="http://www.vmware.com/schema/ovf" ovf:id="100" vmw:osType="other26xLinux64Guest">
<ovf:Info>Specifies the operating system installed</ovf:Info>
<ovf:Description>Other 2.6x Linux (64-bit)</ovf:Description>
</ovf:OperatingSystemSection>
<ovf:VirtualHardwareSection>
<ovf:Info>Virtual hardware requirements</ovf:Info>
<ovf:System>
<vssd:ElementName>Virtual Hardware Family</vssd:ElementName>
<vssd:InstanceID>0</vssd:InstanceID>
<vssd:VirtualSystemIdentifier>centos-web</vssd:VirtualSystemIdentifier>
<vssd:VirtualSystemType>vmx-07</vssd:VirtualSystemType>
</ovf:System>
<ovf:Item>
<rasd:Address>00:50:56:01:06:82</rasd:Address> <rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
<rasd:Connection vcloud:ipAddress="192.168.2.101" vcloud:primaryNetworkConnection="true" vcloud:ipAddressingMode="POOL">vapp net</rasd:Connection>
<rasd:Description>PCNet32 ethernet adapter</rasd:Description>
<rasd:ElementName>Network adapter 0</rasd:ElementName>
<rasd:InstanceID>1</rasd:InstanceID>
<rasd:ResourceSubType>PCNet32</rasd:ResourceSubType>
<rasd:ResourceType>10</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:Address>0</rasd:Address>
<rasd:Description>SCSI Controller</rasd:Description>
<rasd:ElementName>SCSI Controller 0</rasd:ElementName>
<rasd:InstanceID>2</rasd:InstanceID>
<rasd:ResourceSubType>lsilogic</rasd:ResourceSubType>
<rasd:ResourceType>6</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:Description>Hard disk</rasd:Description>
<rasd:ElementName>Hard disk 1</rasd:ElementName>
<rasd:HostResource vcloud:capacity="8192" vcloud:busType="6" vcloud:busSubType="lsilogic"/>
<rasd:InstanceID>2000</rasd:InstanceID>
<rasd:Parent>2</rasd:Parent>
<rasd:ResourceType>17</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:Address>0</rasd:Address>
<rasd:Description>IDE Controller</rasd:Description>
<rasd:ElementName>IDE Controller 0</rasd:ElementName>
<rasd:InstanceID>3</rasd:InstanceID>
<rasd:ResourceType>5</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Description>CD/DVD Drive</rasd:Description>
<rasd:ElementName>CD/DVD Drive 1</rasd:ElementName>
<rasd:HostResource/>
<rasd:InstanceID>3000</rasd:InstanceID>
<rasd:Parent>3</rasd:Parent>
<rasd:ResourceType>15</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Description>Floppy Drive</rasd:Description>
<rasd:ElementName>Floppy Drive 1</rasd:ElementName>
<rasd:HostResource/>
<rasd:InstanceID>8000</rasd:InstanceID>
<rasd:ResourceType>14</rasd:ResourceType>
</ovf:Item>
<ovf:Item>
<rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>
<rasd:Description>Number of Virtual CPUs</rasd:Description>
<rasd:ElementName>1 virtual CPU(s)</rasd:ElementName>
<rasd:InstanceID>4</rasd:InstanceID>
<rasd:Reservation>0</rasd:Reservation>
<rasd:ResourceType>3</rasd:ResourceType>
<rasd:VirtualQuantity>1</rasd:VirtualQuantity>
<rasd:Weight>0</rasd:Weight>
</ovf:Item>
<ovf:Item>
<rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>
<rasd:Description>Memory Size</rasd:Description>
<rasd:ElementName>2048 MB of memory</rasd:ElementName>
<rasd:InstanceID>5</rasd:InstanceID>
<rasd:Reservation>0</rasd:Reservation>
<rasd:ResourceType>4</rasd:ResourceType>
<rasd:VirtualQuantity>2048</rasd:VirtualQuantity>
<rasd:Weight>0</rasd:Weight>
</ovf:Item>
</ovf:VirtualHardwareSection>
<vcloud:NetworkConnectionSection ovf:required="false">
<ovf:Info>Specifies the available VM network connections</ovf:Info>
<vcloud:PrimaryNetworkConnectionIndex>0</vcloud:PrimaryNetworkConnectionIndex>
<vcloud:NetworkConnection network="vapp net">
<vcloud:NetworkConnectionIndex>0</vcloud:NetworkConnectionIndex>
<vcloud:IpAddress>192.168.2.101</vcloud:IpAddress>
<vcloud:IsConnected>true</vcloud:IsConnected>
<vcloud:MACAddress>00:50:56:01:06:82</vcloud:MACAddress>
<vcloud:IpAddressAllocationMode>POOL</vcloud:IpAddressAllocationMode>
</vcloud:NetworkConnection>
</vcloud:NetworkConnectionSection>
<vcloud:GuestCustomizationSection ovf:required="false">
<ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
<vcloud:Enabled>true</vcloud:Enabled>
<vcloud:ChangeSid>false</vcloud:ChangeSid>
<vcloud:JoinDomainEnabled>false</vcloud:JoinDomainEnabled>
<vcloud:UseOrgSettings>false</vcloud:UseOrgSettings>
<vcloud:AdminPasswordEnabled>false</vcloud:AdminPasswordEnabled>
<vcloud:AdminPasswordAuto>true</vcloud:AdminPasswordAuto>
<vcloud:ResetPasswordRequired>false</vcloud:ResetPasswordRequired>
<vcloud:ComputerName>centos-web</vcloud:ComputerName>
</vcloud:GuestCustomizationSection>
</ovf:VirtualSystem>
</ovf:VirtualSystemCollection>
</ovf:Envelope>

View File

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<VAppTemplate xmlns="http://www.vmware.com/vcloud/v1" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" ovfDescriptorUploaded="true" status="8" name="Windows Server 2008 R2" type="application/vnd.vmware.vcloud.vAppTemplate+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.dmtf.org/ovf/envelope/1 http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd http://www.vmware.com/vcloud/v1 http://zone.myvcloud.com/api/v1.0/schema/master.xsd">
<Link rel="up" type="application/vnd.vmware.vcloud.vdc+xml" href="https://zone.myvcloud.com/api/v1.0/vdc/cf6a0068-b7c4-425c-9e80-46ffef58782a"/>
<Link rel="catalogItem" type="application/vnd.vmware.vcloud.catalogItem+xml" href="https://zone.myvcloud.com/api/v1.0/catalogItem/9c45dbbd-910d-45c8-a811-d1e0b01e9e82"/>
<Link rel="remove" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728"/>
<Link rel="edit" type="application/vnd.vmware.vcloud.vAppTemplate+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728"/>
<Link rel="enable" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/action/enableDownload"/>
<Link rel="disable" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/action/disableDownload"/>
<Link rel="ovf" type="text/xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/ovf"/>
<Link rel="down" type="application/vnd.vmware.vcloud.owner+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/owner"/>
<Description/>
<Children>
<Vm name="Windows Server 2008 R2" type="application/vnd.vmware.vcloud.vm+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vm-24fc1b05-10f7-423e-a644-fd3368f9d0cd">
<Link rel="up" type="application/vnd.vmware.vcloud.vAppTemplate+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728"/>
<Description/>
<NetworkConnectionSection type="application/vnd.vmware.vcloud.networkConnectionSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vm-24fc1b05-10f7-423e-a644-fd3368f9d0cd/networkConnectionSection/" ovf:required="false">
<ovf:Info>Specifies the available VM network connections</ovf:Info>
<PrimaryNetworkConnectionIndex>0</PrimaryNetworkConnectionIndex>
<NetworkConnection network="none">
<NetworkConnectionIndex>0</NetworkConnectionIndex>
<IsConnected>false</IsConnected>
<MACAddress>00:50:56:b5:09:dc</MACAddress>
<IpAddressAllocationMode>NONE</IpAddressAllocationMode>
</NetworkConnection>
</NetworkConnectionSection>
<GuestCustomizationSection type="application/vnd.vmware.vcloud.guestCustomizationSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vm-24fc1b05-10f7-423e-a644-fd3368f9d0cd/guestCustomizationSection/" ovf:required="false">
<ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
<Enabled>true</Enabled>
<ChangeSid>false</ChangeSid>
<JoinDomainEnabled>false</JoinDomainEnabled>
<UseOrgSettings>false</UseOrgSettings>
<AdminPasswordEnabled>true</AdminPasswordEnabled>
<AdminPasswordAuto>true</AdminPasswordAuto>
<ResetPasswordRequired>true</ResetPasswordRequired> <ComputerName>WindowsServ-001</ComputerName>
</GuestCustomizationSection>
<VAppScopedLocalId>Windows Server 2008 R2</VAppScopedLocalId>
</Vm>
</Children>
<ovf:NetworkSection xmlns:vcloud="http://www.vmware.com/vcloud/v1" vcloud:href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/networkSection/" vcloud:type="application/vnd.vmware.vcloud.networkSection+xml"> <ovf:Info>The list of logical networks</ovf:Info>
<ovf:Network ovf:name="none">
<ovf:Description>This is a special place-holder used for disconnected network interfaces.</ovf:Description>
</ovf:Network> </ovf:NetworkSection>
<NetworkConfigSection type="application/vnd.vmware.vcloud.networkConfigSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/networkConfigSection/" ovf:required="false">
<ovf:Info>The configuration parameters for logical networks</ovf:Info>
<NetworkConfig networkName="none">
<Description>This is a special place-holder used for disconnected network interfaces.</Description>
<Configuration>
<IpScope>
<IsInherited>false</IsInherited>
<Gateway>196.254.254.254</Gateway>
<Netmask>255.255.0.0</Netmask>
<Dns1>196.254.254.254</Dns1>
</IpScope>
<FenceMode>isolated</FenceMode>
</Configuration>
<IsDeployed>false</IsDeployed>
</NetworkConfig>
</NetworkConfigSection>
<LeaseSettingsSection type="application/vnd.vmware.vcloud.leaseSettingsSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/leaseSettingsSection/" ovf:required="false">
<ovf:Info>Lease settings section</ovf:Info> <Link rel="edit" type="application/vnd.vmware.vcloud.leaseSettingsSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/leaseSettingsSection/"/>
<StorageLeaseInSeconds>0</StorageLeaseInSeconds>
</LeaseSettingsSection>
<CustomizationSection type="application/vnd.vmware.vcloud.customizationSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/customizationSection/" ovf:required="false">
<ovf:Info>VApp template customization section</ovf:Info>
<CustomizeOnInstantiate>true</CustomizeOnInstantiate>
<Link rel="edit" type="application/vnd.vmware.vcloud.customizationSection+xml" href="https://zone.myvcloud.com/api/v1.0/vAppTemplate/vappTemplate-51891b97-c5dd-47dc-a687-aabae354f728/customizationSection/"/>
</CustomizationSection>
</VAppTemplate>

View File

@ -79,8 +79,9 @@ public class TransientStorageStrategy {
} }
public void removeBlob(final String containerName, final String blobName) { public void removeBlob(final String containerName, final String blobName) {
if (containerToBlobs.containsKey(containerName)) Map<String, Blob> map = containerToBlobs.get(containerName);
containerToBlobs.get(containerName).remove(blobName); if (map != null)
map.remove(blobName);
} }
public Iterable<String> getBlobKeysInsideContainer(final String containerName) { public Iterable<String> getBlobKeysInsideContainer(final String containerName) {

View File

@ -90,9 +90,6 @@ public class ParseAuthenticationResponseFromHeaders implements Function<HttpResp
@Override @Override
public ParseAuthenticationResponseFromHeaders setContext(HttpRequest request) { public ParseAuthenticationResponseFromHeaders setContext(HttpRequest request) {
String host = request.getEndpoint().getHost(); String host = request.getEndpoint().getHost();
if (request.getEndpoint().getPort() != -1) {
host += ":" + request.getEndpoint().getPort();
}
return setHostToReplace(host); return setHostToReplace(host);
} }

View File

@ -332,7 +332,7 @@ Here's an example of creating and running a small linux node in the group webser
:os-name-matches :os-description-matches :os-version-matches :os-name-matches :os-description-matches :os-version-matches
:os-arch-matches :os-64-bit :image-name-matches :os-arch-matches :os-64-bit :image-name-matches
:image-version-matches :image-description-matches :image-matches :image-version-matches :image-description-matches :image-matches
:min-cores :min-ram]))) :min-cores :min-ram :min-disk])))
(def (def
^{:doc "TemplateOptions functions" :private true} ^{:doc "TemplateOptions functions" :private true}
@ -425,7 +425,7 @@ Options correspond to TemplateBuilder methods."
os-name-matches os-description-matches os-version-matches os-name-matches os-description-matches os-version-matches
os-arch-matches os-64-bit mage-name-matches os-arch-matches os-64-bit mage-name-matches
image-version-matches image-description-matches image-matches image-version-matches image-description-matches image-matches
min-cores min-ram smallest fastest biggest any] min-cores min-ram min-disk smallest fastest biggest any]
:as options}] :as options}]
(let [builder (.. compute (templateBuilder))] (let [builder (.. compute (templateBuilder))]
(doseq [[option value] options] (doseq [[option value] options]

View File

@ -19,7 +19,7 @@
package org.jclouds.compute.domain.internal; package org.jclouds.compute.domain.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.getCoresAndSpeed; import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.jclouds.compute.util.ComputeServiceUtils.getSpace; import static org.jclouds.compute.util.ComputeServiceUtils.getSpace;
import java.net.URI; import java.net.URI;
@ -104,9 +104,8 @@ public class HardwareImpl extends ComputeMetadataImpl implements Hardware {
public int compareTo(ResourceMetadata<ComputeType> that) { public int compareTo(ResourceMetadata<ComputeType> that) {
if (that instanceof Hardware) { if (that instanceof Hardware) {
Hardware thatHardware = Hardware.class.cast(that); Hardware thatHardware = Hardware.class.cast(that);
return ComparisonChain.start().compare(getCoresAndSpeed(this), getCoresAndSpeed(thatHardware)).compare( return ComparisonChain.start().compare(getCores(this), getCores(thatHardware)).compare(this.getRam(), thatHardware.getRam())
this.getRam(), thatHardware.getRam()).compare(getSpace(this), getSpace(thatHardware)).compare( .compare(getSpace(this), getSpace(thatHardware)).result();
getHypervisor(), thatHardware.getHypervisor()).result();
} else { } else {
return super.compareTo(that); return super.compareTo(that);
} }

View File

@ -437,6 +437,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
predicates.add(hypervisorPredicate); predicates.add(hypervisorPredicate);
predicates.add(hardwareCoresPredicate); predicates.add(hardwareCoresPredicate);
predicates.add(hardwareRamPredicate); predicates.add(hardwareRamPredicate);
predicates.add(hardwareDiskPredicate);
// looks verbose, but explicit <Hardware> type needed for this to compile // looks verbose, but explicit <Hardware> type needed for this to compile
// properly // properly

View File

@ -0,0 +1,103 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableSet;
/**
* An {@code Set} that can be continued
*
* @author Adrian Cole
*/
@Beta
public class PaginatedSet<T> extends ForwardingSet<T> {
public static <T> PaginatedSet<T> copyOf(Iterable<T> contents) {
return new PaginatedSet<T>(contents, null);
}
public static <T> PaginatedSet<T> copyOfWithMarker(Iterable<T> contents, String marker) {
return new PaginatedSet<T>(contents, marker);
}
private final Set<T> contents;
private final String marker;
protected PaginatedSet(Iterable<T> contents, @Nullable String marker) {
this.contents = ImmutableSet.<T> copyOf(checkNotNull(contents, "contents"));
this.marker = marker;
}
/**
* If there is a next marker, then the set is incomplete and you should issue another command to
* retrieve the rest, setting the option {@code marker} to this value
*
* @return next marker, or null if list is complete
*/
@Nullable
public String getNextMarker() {
return marker;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hashCode(contents, marker);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PaginatedSet<?> other = PaginatedSet.class.cast(obj);
return Objects.equal(this.contents, other.contents) && Objects.equal(this.marker, other.marker);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return Objects.toStringHelper(this).add("contents", contents).add("marker", marker).toString();
}
@Override
protected Set<T> delegate() {
return contents;
}
}

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.collect;
import java.util.Iterator;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.collect.AbstractIterator;
/**
* Utilities for using {@link PaginatedSet}s.
*
* @author Adrian Cole, Jeremy Whitlock
*/
@Beta
public class PaginatedSets {
/**
*
* @param initial
* the initial set of data
* @param markerToNext
* produces the next set based on the marker
*
* @return iterable of users fitting the criteria
*/
public static <T> Iterable<T> lazyContinue(final PaginatedSet<T> initial,
final Function<String, PaginatedSet<T>> markerToNext) {
if (initial.getNextMarker() == null)
return initial;
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new AbstractIterator<T>() {
private PaginatedSet<T> response = initial;
private Iterator<T> iterator = response.iterator();
/**
* {@inheritDoc}
*/
@Override
protected T computeNext() {
while (true) {
if (iterator == null) {
response = markerToNext.apply(response.getNextMarker());
iterator = response.iterator();
}
if (iterator.hasNext()) {
return iterator.next();
}
if (response.getNextMarker() == null) {
return endOfData();
}
iterator = null;
}
}
};
}
@Override
public String toString() {
return "lazyContinue(" + markerToNext.toString() + ")";
}
};
}
}

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.json.config; package org.jclouds.json.config;
import java.beans.ConstructorProperties;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Date; import java.util.Date;
@ -35,20 +36,29 @@ import org.jclouds.crypto.CryptoStreams;
import org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.domain.JsonBall; import org.jclouds.domain.JsonBall;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.json.internal.DeserializationConstructorAndReflectiveTypeAdapterFactory;
import org.jclouds.json.internal.EnumTypeAdapterThatReturnsFromValue; import org.jclouds.json.internal.EnumTypeAdapterThatReturnsFromValue;
import org.jclouds.json.internal.GsonWrapper; import org.jclouds.json.internal.GsonWrapper;
import org.jclouds.json.internal.NamingStrategies.AnnotationConstructorNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.AnnotationOrNameFieldNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.ExtractNamed;
import org.jclouds.json.internal.NamingStrategies.ExtractSerializedName;
import org.jclouds.json.internal.NullHackJsonLiteralAdapter; import org.jclouds.json.internal.NullHackJsonLiteralAdapter;
import org.jclouds.json.internal.OptionalTypeAdapterFactory; import org.jclouds.json.internal.OptionalTypeAdapterFactory;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.primitives.Bytes; import com.google.common.primitives.Bytes;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory; import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.JsonReaderInternalAccess; import com.google.gson.internal.JsonReaderInternalAccess;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
@ -69,8 +79,12 @@ public class GsonModule extends AbstractModule {
@Singleton @Singleton
Gson provideGson(TypeAdapter<JsonBall> jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter, Gson provideGson(TypeAdapter<JsonBall> jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter,
ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings) ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings)
throws ClassNotFoundException, Exception { throws Exception {
GsonBuilder builder = new GsonBuilder();
FieldNamingStrategy serializationPolicy = new AnnotationOrNameFieldNamingStrategy(new ExtractSerializedName(),
new ExtractNamed());
GsonBuilder builder = new GsonBuilder().setFieldNamingStrategy(serializationPolicy);
// simple (type adapters) // simple (type adapters)
builder.registerTypeAdapter(Properties.class, propertiesAdapter.nullSafe()); builder.registerTypeAdapter(Properties.class, propertiesAdapter.nullSafe());
@ -81,6 +95,14 @@ public class GsonModule extends AbstractModule {
builder.registerTypeAdapter(JsonBall.class, jsonAdapter.nullSafe()); builder.registerTypeAdapter(JsonBall.class, jsonAdapter.nullSafe());
builder.registerTypeAdapterFactory(new OptionalTypeAdapterFactory()); builder.registerTypeAdapterFactory(new OptionalTypeAdapterFactory());
AnnotationConstructorNamingStrategy deserializationPolicy =
new AnnotationConstructorNamingStrategy(
ImmutableSet.of(ConstructorProperties.class, Inject.class), ImmutableSet.of(new ExtractNamed()));
builder.registerTypeAdapterFactory(
new DeserializationConstructorAndReflectiveTypeAdapterFactory(new ConstructorConstructor(),
serializationPolicy, Excluder.DEFAULT, deserializationPolicy));
// complicated (serializers/deserializers as they need context to operate) // complicated (serializers/deserializers as they need context to operate)
builder.registerTypeHierarchyAdapter(Enum.class, new EnumTypeAdapterThatReturnsFromValue()); builder.registerTypeHierarchyAdapter(Enum.class, new EnumTypeAdapterThatReturnsFromValue());

View File

@ -0,0 +1,256 @@
/**
* 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.json.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import org.jclouds.json.internal.NamingStrategies.ConstructorFieldNamingStrategy;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
/**
* Creates type adapters for types handled in the following ways:
* <p/>
* <ul>
* <li>Deserialization</li>
* If there's an annotation designating a parameterized constructor, invoke that for fields
* correlating to named parameter annotations. Otherwise, use {@link ConstructorConstructor}, and
* set fields via reflection.
* <li>Serialization</li>
* Serialize based on reflective access to fields, delegating to ReflectiveTypeAdaptor.
* </ul>
* <h3>Example: Using javax inject to select a constructor and corresponding named parameters</h3>
* <p/>
* <pre>
*
* import NamingStrategies.*;
*
* serializationStrategy = new AnnotationOrNameFieldNamingStrategy(
* new ExtractSerializedName(), new ExtractNamed());
*
* deserializationStrategy = new AnnotationConstructorNamingStrategy(
* Collections.singleton(javax.inject.Inject.class),
* Collections.singleton(new ExtractNamed()));
*
* factory = new DeserializationConstructorAndReflectiveTypeAdapterFactory(new ConstructorConstructor(),
* serializationStrategy, Excluder.DEFAULT, deserializationStrategy);
*
* gson = new GsonBuilder(serializationStrategy).registerTypeAdapterFactory(factory).create();
*
* </pre>
* <p/>
* The above would work fine on the following class, which has no gson-specific annotations:
* <p/>
* <pre>
* private static class ImmutableAndVerifiedInCtor {
* final int foo;
* &#064;Named(&quot;_bar&quot;)
* final int bar;
*
* &#064;Inject
* ImmutableAndVerifiedInCtor(@Named(&quot;foo&quot;) int foo, @Named(&quot;_bar&quot;) int bar) {
* if (foo &lt; 0)
* throw new IllegalArgumentException(&quot;negative!&quot;);
* this.foo = foo;
* this.bar = bar;
* }
* }
* </pre>
* <p/>
* <br/>
*
* @author Adrian Cole
* @author Adam Lowe
*/
public final class DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory {
private final ConstructorFieldNamingStrategy constructorFieldNamingPolicy;
private final ReflectiveTypeAdapterFactory delegateFactory;
/**
* @param constructorConstructor passed through to delegate ReflectiveTypeAdapterFactory for serialization
* @param serializationFieldNamingPolicy passed through to delegate ReflectiveTypeAdapterFactory for serialization
* @param excluder passed through to delegate ReflectiveTypeAdapterFactory for serialization
* @param deserializationFieldNamingPolicy
* determines which constructor to use and how to determine field names for
* deserialization
* @see ReflectiveTypeAdapterFactory
*/
public DeserializationConstructorAndReflectiveTypeAdapterFactory(
ConstructorConstructor constructorConstructor,
FieldNamingStrategy serializationFieldNamingPolicy,
Excluder excluder,
ConstructorFieldNamingStrategy deserializationFieldNamingPolicy) {
this.constructorFieldNamingPolicy = checkNotNull(deserializationFieldNamingPolicy, "deserializationFieldNamingPolicy");
this.delegateFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, checkNotNull(serializationFieldNamingPolicy, "fieldNamingPolicy"), checkNotNull(excluder, "excluder"));
}
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
Class<? super T> raw = type.getRawType();
Constructor<? super T> deserializationCtor = constructorFieldNamingPolicy.getDeserializationConstructor(raw);
if (deserializationCtor == null) {
return null; // allow GSON to choose the correct Adapter (can't simply return delegateFactory.create())
} else {
deserializationCtor.setAccessible(true);
return new DeserializeWithParameterizedConstructorSerializeWithDelegate<T>(delegateFactory.create(gson, type), deserializationCtor,
getParameterReaders(gson, type, deserializationCtor));
}
}
private final class DeserializeWithParameterizedConstructorSerializeWithDelegate<T> extends TypeAdapter<T> {
private final Constructor<? super T> parameterizedCtor;
private final Map<String, ParameterReader> parameterReaders;
private final TypeAdapter<T> delegate;
private DeserializeWithParameterizedConstructorSerializeWithDelegate(TypeAdapter<T> delegate,
Constructor<? super T> parameterizedCtor, Map<String, ParameterReader> parameterReaders) {
this.delegate = delegate;
this.parameterizedCtor = parameterizedCtor;
this.parameterReaders = parameterReaders;
}
@Override
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
Class<?>[] paramTypes = parameterizedCtor.getParameterTypes();
Object[] ctorParams = new Object[paramTypes.length];
// TODO determine if we can drop this
for (int i = 0; i < paramTypes.length; i++) {
if (paramTypes[i] == boolean.class) {
ctorParams[i] = Boolean.FALSE;
} else if (paramTypes[i].isPrimitive()) {
ctorParams[i] = 0;
}
}
try {
in.beginObject();
while (in.hasNext()) {
String name = in.nextName();
ParameterReader parameter = parameterReaders.get(name);
if (parameter == null) {
in.skipValue();
} else {
Object value = parameter.read(in);
if (value != null) ctorParams[parameter.index] = value;
}
}
} catch (IllegalStateException e) {
throw new JsonSyntaxException(e);
}
for (int i = 0; i < paramTypes.length; i++) {
if (paramTypes[i].isPrimitive()) {
checkArgument(ctorParams[i] != null, "Primative param[" + i + "] in constructor " + parameterizedCtor
+ " cannot be absent!");
}
}
in.endObject();
return newInstance(ctorParams);
}
/**
* pass to delegate
*/
@Override
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
@SuppressWarnings("unchecked")
private T newInstance(Object[] ctorParams) throws AssertionError {
try {
return (T) parameterizedCtor.newInstance(ctorParams);
} catch (InstantiationException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof RuntimeException)
throw RuntimeException.class.cast(e.getCause());
throw new AssertionError(e);
}
}
}
// logic borrowed from ReflectiveTypeAdapterFactory
static class ParameterReader<T> {
final String name;
final int index;
final TypeAdapter<T> typeAdapter;
ParameterReader(String name, int index, TypeAdapter<T> typeAdapter) {
this.name = name;
this.index = index;
this.typeAdapter = typeAdapter;
}
public Object read(JsonReader reader) throws IOException {
return typeAdapter.read(reader);
}
}
@SuppressWarnings("unchecked")
private Map<String, ParameterReader> getParameterReaders(Gson context, TypeToken<?> declaring, Constructor<?> constructor) {
Map<String, ParameterReader> result = new LinkedHashMap<String, ParameterReader>();
for (int index = 0; index < constructor.getGenericParameterTypes().length; index++) {
Type parameterType = getTypeOfConstructorParameter(declaring, constructor, index);
TypeAdapter<?> adapter = context.getAdapter(TypeToken.get(parameterType));
String parameterName = constructorFieldNamingPolicy.translateName(constructor, index);
checkArgument(parameterName != null, constructor + " parameter " + 0 + " failed to be named by " + constructorFieldNamingPolicy);
ParameterReader parameterReader = new ParameterReader(parameterName, index, adapter);
ParameterReader previous = result.put(parameterReader.name, parameterReader);
checkArgument(previous == null, constructor + " declares multiple JSON parameters named " + parameterReader.name);
}
return result;
}
private Type getTypeOfConstructorParameter(TypeToken<?> declaring, Constructor<?> constructor, int index) {
Type genericParameter = constructor.getGenericParameterTypes()[index];
return $Gson$Types.resolve(declaring.getType(), declaring.getRawType(), genericParameter);
}
}

View File

@ -0,0 +1,226 @@
/**
* 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.json.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;
import javax.inject.Named;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.annotations.SerializedName;
/**
* NamingStrategies used for JSON deserialization using GSON
*
* @author Adrian Cole
* @author Adam Lowe
*/
public class NamingStrategies {
/**
* Specifies how to extract the name from an annotation for use in determining the serialized
* name.
*
* @see com.google.gson.annotations.SerializedName
* @see ExtractSerializedName
*/
public abstract static class NameExtractor<A extends Annotation> {
protected final Class<A> annotationType;
protected NameExtractor(Class<A> annotationType) {
this.annotationType = checkNotNull(annotationType, "annotationType");
}
public abstract String extractName(A in);
public Class<A> annotationType() {
return annotationType;
}
@Override
public String toString() {
return "nameExtractor(" + annotationType.getSimpleName() + ")";
}
@Override
public int hashCode() {
return annotationType.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
return annotationType.equals(NameExtractor.class.cast(obj).annotationType);
}
}
public static class ExtractSerializedName extends NameExtractor<SerializedName> {
public ExtractSerializedName() {
super(SerializedName.class);
}
@Override
public String extractName(SerializedName in) {
return checkNotNull(in, "input annotation").value();
}
}
public static class ExtractNamed extends NameExtractor<Named> {
public ExtractNamed() {
super(Named.class);
}
@Override
public String extractName(Named in) {
return checkNotNull(in, "input annotation").value();
}
}
public static abstract class AnnotationBasedNamingStrategy {
protected final Map<Class<? extends Annotation>, ? extends NameExtractor> annotationToNameExtractor;
private String forToString;
@SuppressWarnings("unchecked")
public AnnotationBasedNamingStrategy(Iterable<? extends NameExtractor> extractors) {
checkNotNull(extractors, "means to extract names by annotations");
this.annotationToNameExtractor = Maps.uniqueIndex(extractors, new Function<NameExtractor, Class<? extends Annotation>>() {
@Override
public Class<? extends Annotation> apply(NameExtractor input) {
return input.annotationType();
}
});
this.forToString = Joiner.on(",").join(Iterables.transform(extractors, new Function<NameExtractor, String>() {
@Override
public String apply(NameExtractor input) {
return input.annotationType().getName();
}
}));
}
@Override
public String toString() {
return "AnnotationBasedNamingStrategy requiring one of " + forToString;
}
}
/**
* Definition of field naming policy for annotation-based field
*/
public static class AnnotationFieldNamingStrategy extends AnnotationBasedNamingStrategy implements FieldNamingStrategy {
public AnnotationFieldNamingStrategy(Iterable<? extends NameExtractor> extractors) {
super(extractors);
checkArgument(extractors.iterator().hasNext(), "you must supply at least one name extractor, for example: "
+ ExtractSerializedName.class.getSimpleName());
}
@SuppressWarnings("unchecked")
@Override
public String translateName(Field f) {
for (Annotation annotation : f.getAnnotations()) {
if (annotationToNameExtractor.containsKey(annotation.annotationType())) {
return annotationToNameExtractor.get(annotation.annotationType()).extractName(annotation);
}
}
return null;
}
}
public static class AnnotationOrNameFieldNamingStrategy extends AnnotationFieldNamingStrategy implements FieldNamingStrategy {
public AnnotationOrNameFieldNamingStrategy(NameExtractor... extractors) {
this(ImmutableSet.copyOf(extractors));
}
public AnnotationOrNameFieldNamingStrategy(Iterable<? extends NameExtractor> extractors) {
super(extractors);
}
@Override
public String translateName(Field f) {
String result = super.translateName(f);
return result == null ? f.getName() : result;
}
}
public static interface ConstructorFieldNamingStrategy {
public String translateName(Constructor<?> c, int index);
public <T> Constructor<? super T> getDeserializationConstructor(Class<?> raw);
}
/**
* Determines field naming from constructor annotations
*/
public static class AnnotationConstructorNamingStrategy extends AnnotationBasedNamingStrategy implements ConstructorFieldNamingStrategy {
private final Set<Class<? extends Annotation>> markers;
public AnnotationConstructorNamingStrategy(Iterable<? extends Class<? extends Annotation>> markers, Iterable<? extends NameExtractor> extractors) {
super(extractors);
this.markers = ImmutableSet.copyOf(checkNotNull(markers, "you must supply at least one annotation to mark deserialization constructors"));
}
@SuppressWarnings("unchecked")
public <T> Constructor<? super T> getDeserializationConstructor(Class<?> raw) {
for (Constructor<?> ctor : raw.getDeclaredConstructors())
for (Class<? extends Annotation> deserializationCtorAnnotation : markers)
if (ctor.isAnnotationPresent(deserializationCtorAnnotation))
return (Constructor<T>) ctor;
return null;
}
@SuppressWarnings("unchecked")
@Override
public String translateName(Constructor<?> c, int index) {
String name = null;
if (markers.contains(ConstructorProperties.class) && c.getAnnotation(ConstructorProperties.class) != null) {
String[] names = c.getAnnotation(ConstructorProperties.class).value();
if (names != null && names.length > index) {
name = names[index];
}
}
for (Annotation annotation : c.getParameterAnnotations()[index]) {
if (annotationToNameExtractor.containsKey(annotation.annotationType())) {
name = annotationToNameExtractor.get(annotation.annotationType()).extractName(annotation);
break;
}
}
return name;
}
}
}

View File

@ -0,0 +1,76 @@
package org.jclouds.collect;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code PaginatedSets}.
*
* @author Adrian Cole
*/
@Test(testName = "PaginatedSetsTest")
public class PaginatedSetsTest {
@SuppressWarnings("unchecked")
@Test
public void testSinglePageResultReturnsSame() {
PaginatedSet<String> initial = PaginatedSet.copyOf(ImmutableSet.of("foo", "bar"));
Function<String, PaginatedSet<String>> markerToNext = createMock(Function.class);
EasyMock.replay(markerToNext);
Assert.assertSame(PaginatedSets.lazyContinue(initial, markerToNext), initial);
EasyMock.verify(markerToNext);
}
@SuppressWarnings("unchecked")
@Test
public void testMultiPage2Pages() {
PaginatedSet<String> initial = PaginatedSet.copyOfWithMarker(ImmutableSet.of("foo", "bar"), "MARKER1");
Function<String, PaginatedSet<String>> markerToNext = createMock(Function.class);
expect(markerToNext.apply("MARKER1")).andReturn(
PaginatedSet.copyOfWithMarker(ImmutableSet.of("boo", "baz"), null));
EasyMock.replay(markerToNext);
Assert.assertEquals(ImmutableSet.copyOf(PaginatedSets.lazyContinue(initial, markerToNext)), ImmutableSet.of(
"foo", "bar", "boo", "baz"));
EasyMock.verify(markerToNext);
}
@SuppressWarnings("unchecked")
@Test
public void testMultiPage3Pages() {
PaginatedSet<String> initial = PaginatedSet.copyOfWithMarker(ImmutableSet.of("foo", "bar"), "MARKER1");
Function<String, PaginatedSet<String>> markerToNext = createMock(Function.class);
expect(markerToNext.apply("MARKER1")).andReturn(
PaginatedSet.copyOfWithMarker(ImmutableSet.of("boo", "baz"), "MARKER2"));
expect(markerToNext.apply("MARKER2")).andReturn(
PaginatedSet.copyOfWithMarker(ImmutableSet.of("ham", "cheeze"), null));
EasyMock.replay(markerToNext);
Assert.assertEquals(ImmutableSet.copyOf(PaginatedSets.lazyContinue(initial, markerToNext)), ImmutableSet.of(
"foo", "bar", "boo", "baz", "ham", "cheeze"));
EasyMock.verify(markerToNext);
}
}

View File

@ -0,0 +1,245 @@
package org.jclouds.json.internal;
/**
* 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.
*/
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import java.beans.ConstructorProperties;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.json.internal.NamingStrategies.AnnotationOrNameFieldNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.ExtractNamed;
import org.jclouds.json.internal.NamingStrategies.ExtractSerializedName;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
import com.google.gson.reflect.TypeToken;
/**
* @author Adrian Cole
* @author Adam Lowe
*/
@Test(testName = "DeserializationConstructorTypeAdapterFactoryTest")
public final class DeserializationConstructorAndReflectiveTypeAdapterFactoryTest {
Gson gson = new Gson();
DeserializationConstructorAndReflectiveTypeAdapterFactory parameterizedCtorFactory = parameterizedCtorFactory();
static DeserializationConstructorAndReflectiveTypeAdapterFactory parameterizedCtorFactory() {
FieldNamingStrategy serializationPolicy = new AnnotationOrNameFieldNamingStrategy(
ImmutableSet.of(new ExtractSerializedName(), new ExtractNamed())
);
NamingStrategies.AnnotationConstructorNamingStrategy deserializationPolicy =
new NamingStrategies.AnnotationConstructorNamingStrategy(
ImmutableSet.of(ConstructorProperties.class, Inject.class),
ImmutableSet.of(new ExtractNamed()));
return new DeserializationConstructorAndReflectiveTypeAdapterFactory(new ConstructorConstructor(),
serializationPolicy, Excluder.DEFAULT, deserializationPolicy);
}
public void testNullWhenPrimitive() {
assertNull(parameterizedCtorFactory.create(gson, TypeToken.get(int.class)));
}
private static class DefaultConstructor {
int foo;
int bar;
private DefaultConstructor() {
}
@Override
public boolean equals(Object obj) {
DefaultConstructor other = DefaultConstructor.class.cast(obj);
if (bar != other.bar)
return false;
if (foo != other.foo)
return false;
return true;
}
}
public void testRejectsIfNoConstuctorMarked() throws IOException {
TypeAdapter<DefaultConstructor> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(DefaultConstructor.class));
assertNull(adapter);
}
private static class WithDeserializationConstructorButWithoutSerializedName {
final int foo;
@Inject
WithDeserializationConstructorButWithoutSerializedName(int foo) {
this.foo = foo;
}
}
public void testSerializedNameRequiredOnAllParameters() {
try {
parameterizedCtorFactory.create(gson, TypeToken
.get(WithDeserializationConstructorButWithoutSerializedName.class));
fail();
} catch (IllegalArgumentException actual) {
assertEquals(actual.getMessage(),
"org.jclouds.json.internal.DeserializationConstructorAndReflectiveTypeAdapterFactoryTest$WithDeserializationConstructorButWithoutSerializedName(int)" +
" parameter 0 failed to be named by AnnotationBasedNamingStrategy requiring one of javax.inject.Named");
}
}
private static class DuplicateSerializedNames {
final int foo;
final int bar;
@Inject
DuplicateSerializedNames(@Named("foo") int foo, @Named("foo") int bar) {
this.foo = foo;
this.bar = bar;
}
}
public void testNoDuplicateSerializedNamesRequiredOnAllParameters() {
try {
parameterizedCtorFactory.create(gson, TypeToken.get(DuplicateSerializedNames.class));
fail();
} catch (IllegalArgumentException actual) {
assertEquals(actual.getMessage(),
"org.jclouds.json.internal.DeserializationConstructorAndReflectiveTypeAdapterFactoryTest$DuplicateSerializedNames(int,int)" +
" declares multiple JSON parameters named foo");
}
}
private static class ValidatedConstructor {
final int foo;
final int bar;
@Inject
ValidatedConstructor(@Named("foo") int foo, @Named("bar") int bar) {
if (foo < 0)
throw new IllegalArgumentException("negative!");
this.foo = foo;
this.bar = bar;
}
@Override
public boolean equals(Object obj) {
ValidatedConstructor other = ValidatedConstructor.class.cast(obj);
if (bar != other.bar)
return false;
if (foo != other.foo)
return false;
return true;
}
}
public void testValidatedConstructor() throws IOException {
TypeAdapter<ValidatedConstructor> adapter = parameterizedCtorFactory.create(gson, TypeToken
.get(ValidatedConstructor.class));
assertEquals(new ValidatedConstructor(0, 1), adapter.fromJson("{\"foo\":0,\"bar\":1}"));
try {
adapter.fromJson("{\"foo\":-1,\"bar\":1}");
fail();
} catch (IllegalArgumentException expected) {
assertEquals("negative!", expected.getMessage());
}
}
private static class GenericParamsCopiedIn {
final List<String> foo;
final Map<String, String> bar;
@Inject
GenericParamsCopiedIn(@Named("foo") List<String> foo, @Named("bar") Map<String, String> bar) {
this.foo = new ArrayList<String>(foo);
this.bar = new HashMap<String, String>(bar);
}
}
public void testGenericParamsCopiedIn() throws IOException {
TypeAdapter<GenericParamsCopiedIn> adapter = parameterizedCtorFactory.create(gson, TypeToken
.get(GenericParamsCopiedIn.class));
List<String> inputFoo = new ArrayList<String>();
inputFoo.add("one");
HashMap<String, String> inputBar = new HashMap<String, String>();
inputBar.put("2", "two");
GenericParamsCopiedIn toTest = adapter.fromJson("{ \"foo\":[\"one\"], \"bar\":{ \"2\":\"two\"}}");
assertEquals(inputFoo, toTest.foo);
assertNotSame(inputFoo, toTest.foo);
assertEquals(inputBar, toTest.bar);
}
private static class RenamedFields {
final int foo;
@Named("_bar")
final int bar;
@ConstructorProperties({"foo", "_bar"})
RenamedFields(int foo, int bar) {
if (foo < 0)
throw new IllegalArgumentException("negative!");
this.foo = foo;
this.bar = bar;
}
@Override
public boolean equals(Object obj) {
RenamedFields other = RenamedFields.class.cast(obj);
if (bar != other.bar)
return false;
if (foo != other.foo)
return false;
return true;
}
}
public void testRenamedFields() throws IOException {
TypeAdapter<RenamedFields> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(RenamedFields.class));
assertEquals(new RenamedFields(0, 1), adapter.fromJson("{\"foo\":0,\"_bar\":1}"));
assertEquals(adapter.toJson(new RenamedFields(0, 1)), "{\"foo\":0,\"_bar\":1}");
}
public void testCanOverrideDefault() throws IOException {
Gson gson = new GsonBuilder().registerTypeAdapterFactory(parameterizedCtorFactory).create();
assertEquals(new RenamedFields(0, 1), gson.fromJson("{\"foo\":0,\"_bar\":1}", RenamedFields.class));
assertEquals(gson.toJson(new RenamedFields(0, 1)), "{\"foo\":0,\"_bar\":1}");
}
}

View File

@ -0,0 +1,203 @@
package org.jclouds.json.internal;
/**
* 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.
*/
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import java.beans.ConstructorProperties;
import java.lang.reflect.Constructor;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.json.internal.NamingStrategies.AnnotationConstructorNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.AnnotationFieldNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.AnnotationOrNameFieldNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.ConstructorFieldNamingStrategy;
import org.jclouds.json.internal.NamingStrategies.ExtractNamed;
import org.jclouds.json.internal.NamingStrategies.ExtractSerializedName;
import org.jclouds.json.internal.NamingStrategies.NameExtractor;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.annotations.SerializedName;
/**
* @author Adam Lowe
*/
@Test(testName = "NamingStrategiesTest")
public final class NamingStrategiesTest {
private static class SimpleTest {
@SerializedName("aardvark")
private String a;
private String b;
@Named("cat")
private String c;
@Named("dog")
private String d;
@ConstructorProperties({"aardvark", "bat", "coyote", "dog"})
private SimpleTest(String aa, String bb, String cc, @Named("dingo") String dd) {
}
@Inject
private SimpleTest(@Named("aa") String aa, @Named("bb") String bb, @Named("cc") String cc, @Named("dd") String dd, boolean nothing) {
}
}
private static class MixedConstructorTest {
@Inject
@ConstructorProperties("thiscanbeoverriddenbyNamed")
private MixedConstructorTest(@Named("aardvark") String aa, @Named("bat") String bb, @Named("cat") String cc, @Named("dog") String dd) {
}
}
public void testExtractSerializedName() throws Exception {
NameExtractor extractor = new ExtractSerializedName();
assertEquals(extractor.extractName(SimpleTest.class.getDeclaredField("a").getAnnotation(SerializedName.class)),
"aardvark");
try {
extractor.extractName(SimpleTest.class.getDeclaredField("b").getAnnotation(SerializedName.class));
fail();
} catch (NullPointerException e) {
}
try {
extractor.extractName(SimpleTest.class.getDeclaredField("c").getAnnotation(SerializedName.class));
fail();
} catch (NullPointerException e) {
}
try {
extractor.extractName(SimpleTest.class.getDeclaredField("d").getAnnotation(SerializedName.class));
fail();
} catch (NullPointerException e) {
}
}
public void testExtractNamed() throws Exception {
NameExtractor extractor = new ExtractNamed();
try {
extractor.extractName(SimpleTest.class.getDeclaredField("a").getAnnotation(Named.class));
} catch (NullPointerException e) {
}
try {
extractor.extractName(SimpleTest.class.getDeclaredField("b").getAnnotation(Named.class));
fail();
} catch (NullPointerException e) {
}
assertEquals(extractor.extractName(SimpleTest.class.getDeclaredField("c").getAnnotation(Named.class)),
"cat");
assertEquals(extractor.extractName(SimpleTest.class.getDeclaredField("d").getAnnotation(Named.class)),
"dog");
}
public void testAnnotationFieldNamingStrategy() throws Exception {
FieldNamingStrategy strategy = new AnnotationFieldNamingStrategy(ImmutableSet.of(new ExtractNamed()));
assertNull(strategy.translateName(SimpleTest.class.getDeclaredField("a")));
assertNull(strategy.translateName(SimpleTest.class.getDeclaredField("b")));
assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField("c")), "cat");
assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField("d")), "dog");
}
public void testAnnotationOrNameFieldNamingStrategy() throws Exception {
FieldNamingStrategy strategy = new AnnotationOrNameFieldNamingStrategy(ImmutableSet.of(new ExtractNamed()));
assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField("a")), "a");
assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField("b")), "b");
assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField("c")), "cat");
assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField("d")), "dog");
}
public void testAnnotationConstructorFieldNamingStrategyCPAndNamed() throws Exception {
ConstructorFieldNamingStrategy strategy = new AnnotationConstructorNamingStrategy(
ImmutableSet.of(ConstructorProperties.class), ImmutableSet.of(new ExtractNamed()));
Constructor<? super SimpleTest> constructor = strategy.getDeserializationConstructor(SimpleTest.class);
assertNotNull(constructor);
assertEquals(constructor.getParameterTypes().length, 4);
assertEquals(strategy.translateName(constructor, 0), "aardvark");
assertEquals(strategy.translateName(constructor, 1), "bat");
assertEquals(strategy.translateName(constructor, 2), "coyote");
// Note: @Named overrides the ConstructorProperties setting
assertEquals(strategy.translateName(constructor, 3), "dingo");
Constructor<? super MixedConstructorTest> mixedCtor = strategy.getDeserializationConstructor(MixedConstructorTest.class);
assertNotNull(mixedCtor);
assertEquals(mixedCtor.getParameterTypes().length, 4);
assertEquals(strategy.translateName(mixedCtor, 0), "aardvark");
assertEquals(strategy.translateName(mixedCtor, 1), "bat");
assertEquals(strategy.translateName(mixedCtor, 2), "cat");
assertEquals(strategy.translateName(mixedCtor, 3), "dog");
}
public void testAnnotationConstructorFieldNamingStrategyCP() throws Exception {
ConstructorFieldNamingStrategy strategy = new AnnotationConstructorNamingStrategy(
ImmutableSet.of(ConstructorProperties.class), ImmutableSet.<NameExtractor>of());
Constructor<? super SimpleTest> constructor = strategy.getDeserializationConstructor(SimpleTest.class);
assertNotNull(constructor);
assertEquals(constructor.getParameterTypes().length, 4);
assertEquals(strategy.translateName(constructor, 0), "aardvark");
assertEquals(strategy.translateName(constructor, 1), "bat");
assertEquals(strategy.translateName(constructor, 2), "coyote");
assertEquals(strategy.translateName(constructor, 3), "dog");
Constructor<? super MixedConstructorTest> mixedCtor = strategy.getDeserializationConstructor(MixedConstructorTest.class);
assertNotNull(mixedCtor);
assertEquals(mixedCtor.getParameterTypes().length, 4);
assertEquals(strategy.translateName(mixedCtor, 0), "thiscanbeoverriddenbyNamed");
assertNull(strategy.translateName(mixedCtor, 1));
assertNull(strategy.translateName(mixedCtor, 2));
assertNull(strategy.translateName(mixedCtor, 3));
}
public void testAnnotationConstructorFieldNamingStrategyInject() throws Exception {
ConstructorFieldNamingStrategy strategy = new AnnotationConstructorNamingStrategy(
ImmutableSet.of(Inject.class), ImmutableSet.of(new ExtractNamed()));
Constructor<? super SimpleTest> constructor = strategy.getDeserializationConstructor(SimpleTest.class);
assertNotNull(constructor);
assertEquals(constructor.getParameterTypes().length, 5);
assertEquals(strategy.translateName(constructor, 0), "aa");
assertEquals(strategy.translateName(constructor, 1), "bb");
assertEquals(strategy.translateName(constructor, 2), "cc");
assertEquals(strategy.translateName(constructor, 3), "dd");
Constructor<? super MixedConstructorTest> mixedCtor = strategy.getDeserializationConstructor(MixedConstructorTest.class);
assertNotNull(mixedCtor);
assertEquals(mixedCtor.getParameterTypes().length, 4);
assertEquals(strategy.translateName(mixedCtor, 0), "aardvark");
assertEquals(strategy.translateName(mixedCtor, 1), "bat");
assertEquals(strategy.translateName(mixedCtor, 2), "cat");
assertEquals(strategy.translateName(mixedCtor, 3), "dog");
}
}

View File

@ -52,7 +52,7 @@
<test.ssh.keyfile /> <test.ssh.keyfile />
<jclouds.osgi.export>org.jclouds.sshj*;version="${project.version}"</jclouds.osgi.export> <jclouds.osgi.export>org.jclouds.sshj*;version="${project.version}"</jclouds.osgi.export>
<jclouds.osgi.import>org.jclouds*;version="${project.version}",*</jclouds.osgi.import> <jclouds.osgi.import>org.jclouds*;version="${project.version}",org.apache.commons.io.input;version="[1.4,3)",*</jclouds.osgi.import>
</properties> </properties>
<dependencies> <dependencies>
@ -97,7 +97,7 @@
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>1.4</version> <version>2.0</version>
</dependency> </dependency>
</dependencies> </dependencies>

108
labs/aws-iam/pom.xml Normal file
View File

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.labs</groupId>
<artifactId>aws-iam</artifactId>
<name>jclouds Amazon Identity and Access Management (IAM) provider</name>
<description>Identity and Access Management (IAM) to Amazon Web Services</description>
<packaging>bundle</packaging>
<properties>
<test.aws-iam.endpoint>https://iam.amazonaws.com</test.aws-iam.endpoint>
<test.aws-iam.api-version>2010-05-08</test.aws-iam.api-version>
<test.aws-iam.build-version></test.aws-iam.build-version>
<test.aws-iam.identity>${test.aws.identity}</test.aws-iam.identity>
<test.aws-iam.credential>${test.aws.credential}</test.aws-iam.credential>
<jclouds.osgi.export>org.jclouds.aws.iam*;version="${project.version}"</jclouds.osgi.export>
<jclouds.osgi.import>org.jclouds*;version="${project.version}",*</jclouds.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.jclouds.labs</groupId>
<artifactId>iam</artifactId>
<version>${project.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jclouds.labs</groupId>
<artifactId>iam</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>integration</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<systemPropertyVariables>
<test.aws-iam.endpoint>${test.aws-iam.endpoint}</test.aws-iam.endpoint>
<test.aws-iam.api-version>${test.aws-iam.api-version}</test.aws-iam.api-version>
<test.aws-iam.build-version>${test.aws-iam.build-version}</test.aws-iam.build-version>
<test.aws-iam.identity>${test.aws-iam.identity}</test.aws-iam.identity>
<test.aws-iam.credential>${test.aws-iam.credential}</test.aws-iam.credential>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,87 @@
/**
* 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.aws.iam;
import java.net.URI;
import java.util.Properties;
import org.jclouds.iam.IAMApiMetadata;
import org.jclouds.providers.ProviderMetadata;
import org.jclouds.providers.internal.BaseProviderMetadata;
/**
* Implementation of @ link org.jclouds.types.ProviderMetadata} for Amazon's IAM
* provider.
*
* @author Adrian Cole
*/
public class AWSIAMProviderMetadata extends BaseProviderMetadata {
/** The serialVersionUID */
private static final long serialVersionUID = 2394954723306943404L;
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return builder().fromProviderMetadata(this);
}
public AWSIAMProviderMetadata() {
super(builder());
}
public AWSIAMProviderMetadata(Builder builder) {
super(builder);
}
public static Properties defaultProperties() {
Properties properties = new Properties();
return properties;
}
public static class Builder extends BaseProviderMetadata.Builder {
protected Builder(){
id("aws-iam")
.name("Amazon IAM")
.endpoint("https://iam.amazonaws.com")
.homepage(URI.create("http://aws.amazon.com/iam"))
.console(URI.create("https://console.aws.amazon.com/iam/home"))
.linkedServices("aws-ec2","aws-elb", "aws-cloudwatch", "aws-s3", "aws-simpledb")
.iso3166Codes("US-VA", "US-CA", "BR-SP", "US-OR", "IE", "SG", "JP-13")
.apiMetadata(new IAMApiMetadata())
.defaultProperties(AWSIAMProviderMetadata.defaultProperties());
}
@Override
public AWSIAMProviderMetadata build() {
return new AWSIAMProviderMetadata(this);
}
@Override
public Builder fromProviderMetadata(ProviderMetadata in) {
super.fromProviderMetadata(in);
return this;
}
}
}

View File

@ -0,0 +1 @@
org.jclouds.aws.iam.AWSIAMProviderMetadata

View File

@ -0,0 +1,35 @@
/**
* 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.aws.iam;
import org.jclouds.iam.IAMClientLiveTest;
import org.testng.annotations.Test;
/**
* Tests behavior of {@code IAMClient}
*
* @author Adrian Cole
*/
@Test(groups = "live", singleThreaded = true, testName = "AWSIAMClientLiveTest")
public class AWSIAMClientLiveTest extends IAMClientLiveTest {
public AWSIAMClientLiveTest() {
provider = "aws-iam";
}
}

View File

@ -0,0 +1,37 @@
/**
* 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.aws.iam;
import org.jclouds.aws.iam.AWSIAMProviderMetadata;
import org.jclouds.iam.IAMApiMetadata;
import org.jclouds.providers.internal.BaseProviderMetadataTest;
import org.testng.annotations.Test;
/**
* The AWSIAMProviderTest tests the org.jclouds.providers.AWSIAMProvider class.
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "AWSIAMProviderTest")
public class AWSIAMProviderTest extends BaseProviderMetadataTest {
public AWSIAMProviderTest() {
super(new AWSIAMProviderMetadata(), new IAMApiMetadata());
}
}

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.aws.iam.features;
import org.jclouds.iam.features.UserClientLiveTest;
import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "live", testName = "AWSUserClientLiveTest")
public class AWSUserClientLiveTest extends UserClientLiveTest {
public AWSUserClientLiveTest() {
provider = "aws-iam";
}
}

View File

@ -23,9 +23,10 @@ import java.util.Map;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.glesys.domain.GleSYSBoolean;
import org.jclouds.glesys.domain.Server; import org.jclouds.glesys.domain.Server;
import org.jclouds.glesys.functions.internal.GleSYSTypeAdapters; import org.jclouds.glesys.functions.internal.GleSYSTypeAdapters;
import org.jclouds.glesys.functions.internal.GlesysDateAdapter; import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.jclouds.json.config.GsonModule.DateAdapter; import org.jclouds.json.config.GsonModule.DateAdapter;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -34,18 +35,20 @@ import com.google.inject.Provides;
/** /**
* @author Adrian Cole * @author Adrian Cole
* @author Adam Lowe
*/ */
public class GleSYSParserModule extends AbstractModule { public class GleSYSParserModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
public Map<Type, Object> provideCustomAdapterBindings() { public Map<Type, Object> provideCustomAdapterBindings() {
return ImmutableMap.<Type, Object> of(Server.State.class, new GleSYSTypeAdapters.ServerStateAdapter()); return ImmutableMap.<Type, Object>of(Server.State.class, new GleSYSTypeAdapters.ServerStateAdapter(),
GleSYSBoolean.class, new GleSYSTypeAdapters.GleSYSBooleanAdapter());
} }
@Override @Override
protected void configure() { protected void configure() {
bind(DateAdapter.class).to(GlesysDateAdapter.class); bind(DateAdapter.class).to(Iso8601DateAdapter.class);
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -20,12 +20,12 @@ package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Set; import java.util.Set;
import com.google.common.base.Joiner;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.gson.annotations.SerializedName;
/** /**
* Sets the allowed arguments for some of the functions in this module such as disksize, cpucores etc. * Sets the allowed arguments for some of the functions in this module such as disksize, cpucores etc.
@ -34,79 +34,104 @@ import com.google.gson.annotations.SerializedName;
* @see <a href="https://customer.glesys.com/api.php?a=doc#server_allowedarguments" /> * @see <a href="https://customer.glesys.com/api.php?a=doc#server_allowedarguments" />
*/ */
public class AllowedArgumentsForCreateServer { public class AllowedArgumentsForCreateServer {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private Set<Integer> diskSizes; return new ConcreteBuilder().fromAllowedArgumentsForCreateServer(this);
private Set<Integer> memorySizes; }
private Set<Integer> cpuCores;
private Set<String> templates;
private Set<Integer> transfers;
private Set<String> dataCenters;
public Builder diskSizes(Integer... sizes) { public static abstract class Builder<T extends Builder<T>> {
return diskSizes(ImmutableSet.<Integer>copyOf(sizes)); protected abstract T self();
protected Set<Integer> diskSizes = ImmutableSet.of();
protected Set<Integer> memorySizes = ImmutableSet.of();
protected Set<Integer> cpuCores = ImmutableSet.of();
protected Set<String> templates = ImmutableSet.of();
protected Set<Integer> transfers = ImmutableSet.of();
protected Set<String> dataCenters = ImmutableSet.of();
/**
* @see AllowedArgumentsForCreateServer#getDiskSizesInGB()
*/
public T diskSizes(Set<Integer> diskSizes) {
this.diskSizes = ImmutableSet.copyOf(checkNotNull(diskSizes, "diskSizesInGB"));
return self();
} }
public Builder diskSizes(Set<Integer> sizes) { public T diskSizes(Integer... in) {
this.diskSizes = sizes; return diskSizes(ImmutableSet.copyOf(in));
return this;
} }
public Builder memorySizes(Integer... sizes) { /**
return memorySizes(ImmutableSet.<Integer>copyOf(sizes)); * @see AllowedArgumentsForCreateServer#getMemorySizesInMB()
*/
public T memorySizes(Set<Integer> memorySizes) {
this.memorySizes = ImmutableSet.copyOf(checkNotNull(memorySizes, "memorySizesInMB"));
return self();
} }
public Builder memorySizes(Set<Integer> sizes) { public T memorySizes(Integer... in) {
this.memorySizes = sizes; return memorySizes(ImmutableSet.copyOf(in));
return this;
} }
public Builder cpuCores(Integer... cpuCores) { /**
this.cpuCores = ImmutableSet.<Integer>copyOf(cpuCores); * @see AllowedArgumentsForCreateServer#getCpuCoreOptions()
return this; */
public T cpuCores(Set<Integer> cpuCores) {
this.cpuCores = ImmutableSet.copyOf(checkNotNull(cpuCores, "cpuCoreOptions"));
return self();
} }
public Builder cpuCores(Set<Integer> cpuCores) { public T cpuCores(Integer... in) {
this.cpuCores = cpuCores; return cpuCores(ImmutableSet.copyOf(in));
return this;
} }
public Builder templates(String... templates) { /**
return templates(ImmutableSet.<String>copyOf(templates)); * @see AllowedArgumentsForCreateServer#getTemplateNames()
*/
public T templates(Set<String> templates) {
this.templates = ImmutableSet.copyOf(checkNotNull(templates, "templateNames"));
return self();
} }
public Builder templates(Set<String> templates) { public T templates(String... in) {
this.templates = templates; return templates(ImmutableSet.copyOf(in));
return this;
} }
public Builder transfers(Integer... transfers) { /**
return transfers(ImmutableSet.<Integer>copyOf(transfers)); * @see AllowedArgumentsForCreateServer#getTransfersInGB()
*/
public T transfers(Set<Integer> transfers) {
this.transfers = ImmutableSet.copyOf(checkNotNull(transfers, "transfersInGB"));
return self();
} }
public Builder transfers(Set<Integer> transfers) { public T transfers(Integer... in) {
this.transfers = transfers; return transfers(ImmutableSet.copyOf(in));
return this;
} }
public Builder dataCenters(String... dataCenters) { /**
return dataCenters(ImmutableSet.<String>copyOf(dataCenters)); * @see AllowedArgumentsForCreateServer#getDataCenters()
*/
public T dataCenters(Set<String> dataCenters) {
this.dataCenters = ImmutableSet.copyOf(checkNotNull(dataCenters, "dataCenters"));
return self();
} }
public Builder dataCenters(Set<String> dataCenters) { public T dataCenters(String... in) {
this.dataCenters = dataCenters; return dataCenters(ImmutableSet.copyOf(in));
return this;
} }
public AllowedArgumentsForCreateServer build() { public AllowedArgumentsForCreateServer build() {
return new AllowedArgumentsForCreateServer(diskSizes, memorySizes, cpuCores, templates, transfers, dataCenters); return new AllowedArgumentsForCreateServer(diskSizes, memorySizes, cpuCores, templates, transfers, dataCenters);
} }
public Builder fromAllowedArguments(AllowedArgumentsForCreateServer in) { public T fromAllowedArgumentsForCreateServer(AllowedArgumentsForCreateServer in) {
return diskSizes(in.getDiskSizesInGB()) return this
.diskSizes(in.getDiskSizesInGB())
.memorySizes(in.getMemorySizesInMB()) .memorySizes(in.getMemorySizesInMB())
.cpuCores(in.getCpuCoreOptions()) .cpuCores(in.getCpuCoreOptions())
.templates(in.getTemplateNames()) .templates(in.getTemplateNames())
@ -115,34 +140,30 @@ public class AllowedArgumentsForCreateServer {
} }
} }
@SerializedName("disksize") private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
private final Set<Integer> diskSizes; @Override
@SerializedName("memorysize") protected ConcreteBuilder self() {
private final Set<Integer> memorySizes; return this;
@SerializedName("cpucores") }
private final Set<Integer> cpuCores; }
@SerializedName("template")
private final Set<String> templates; private final Set<Integer> diskSizesInGB;
@SerializedName("transfer") private final Set<Integer> memorySizesInMB;
private final Set<Integer> transfers; private final Set<Integer> cpuCoreOptions;
@SerializedName("datacenter") private final Set<String> templateNames;
private final Set<Integer> transfersInGB;
private final Set<String> dataCenters; private final Set<String> dataCenters;
public AllowedArgumentsForCreateServer(Set<Integer> diskSizes, Set<Integer> memorySizes, Set<Integer> cpuCores, @ConstructorProperties({
Set<String> templates, Set<Integer> transfers, Set<String> dataCenters) { "disksize", "memorysize", "cpucores", "template", "transfer", "datacenter"
checkNotNull(diskSizes, "diskSizes"); })
checkNotNull(memorySizes, "memorySizes"); protected AllowedArgumentsForCreateServer(Set<Integer> diskSizesInGB, Set<Integer> memorySizesInMB, Set<Integer> cpuCoreOptions, Set<String> templateNames, Set<Integer> transfersInGB, Set<String> dataCenters) {
checkNotNull(cpuCores, "cpuCores"); this.diskSizesInGB = ImmutableSet.copyOf(checkNotNull(diskSizesInGB, "diskSizesInGB"));
checkNotNull(templates, "templates"); this.memorySizesInMB = ImmutableSet.copyOf(checkNotNull(memorySizesInMB, "memorySizesInMB"));
checkNotNull(transfers, "transfers"); this.cpuCoreOptions = ImmutableSet.copyOf(checkNotNull(cpuCoreOptions, "cpuCoreOptions"));
checkNotNull(dataCenters, "dataCenters"); this.templateNames = ImmutableSet.copyOf(checkNotNull(templateNames, "templateNames"));
this.transfersInGB = ImmutableSet.copyOf(checkNotNull(transfersInGB, "transfersInGB"));
this.diskSizes = diskSizes; this.dataCenters = ImmutableSet.copyOf(checkNotNull(dataCenters, "dataCenters"));
this.memorySizes = memorySizes;
this.cpuCores = cpuCores;
this.templates = templates;
this.transfers = transfers;
this.dataCenters = dataCenters;
} }
/** /**
@ -150,22 +171,22 @@ public class AllowedArgumentsForCreateServer {
* @see org.jclouds.glesys.domain.OSTemplate#getMinDiskSize() * @see org.jclouds.glesys.domain.OSTemplate#getMinDiskSize()
*/ */
public Set<Integer> getDiskSizesInGB() { public Set<Integer> getDiskSizesInGB() {
return diskSizes; return this.diskSizesInGB;
} }
/** /**
* @return a list of memory sizes, in MB, that can be used for creating servers on this platform * @return a list of memory sizes, in MB, that can be used for creating servers on this platform
* @see org.jclouds.glesys.domain.OSTemplate#getMinMemSize() * @see org.jclouds.glesys.domain.OSTemplate#getMinMemSize()
*/ */
public Set<Integer> getMemorySizesInMB() { public Set<Integer> getMemorySizesInMB() {
return memorySizes; return this.memorySizesInMB;
} }
/** /**
* @return a list of which core counts can be used for creating servers on this platform * @return a list of which core counts can be used for creating servers on this platform
*/ */
public Set<Integer> getCpuCoreOptions() { public Set<Integer> getCpuCoreOptions() {
return cpuCores; return this.cpuCoreOptions;
} }
/** /**
@ -173,59 +194,50 @@ public class AllowedArgumentsForCreateServer {
* @see org.jclouds.glesys.domain.OSTemplate#getName() * @see org.jclouds.glesys.domain.OSTemplate#getName()
*/ */
public Set<String> getTemplateNames() { public Set<String> getTemplateNames() {
return templates; return this.templateNames;
} }
/** /**
* @return the list of transfer settings available for creating servers on this platform * @return the list of transfer settings available for creating servers on this platform
*/ */
public Set<Integer> getTransfersInGB() { public Set<Integer> getTransfersInGB() {
return transfers; return this.transfersInGB;
} }
/** /**
* @return the list of datacenters available that support creating servers on this platform * @return the list of datacenters available that support creating servers on this platform
*/ */
public Set<String> getDataCenters() { public Set<String> getDataCenters() {
return dataCenters; return this.dataCenters;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof AllowedArgumentsForCreateServer) {
final AllowedArgumentsForCreateServer other = (AllowedArgumentsForCreateServer) object;
return Objects.equal(diskSizes, other.diskSizes)
&& Objects.equal(memorySizes, other.memorySizes)
&& Objects.equal(cpuCores, other.cpuCores)
&& Objects.equal(templates, other.templates)
&& Objects.equal(transfers, other.transfers)
&& Objects.equal(dataCenters, other.dataCenters);
} else {
return false;
}
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(diskSizes, memorySizes, cpuCores, templates, transfers, dataCenters); return Objects.hashCode(diskSizesInGB, memorySizesInMB, cpuCoreOptions, templateNames, transfersInGB, dataCenters);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
AllowedArgumentsForCreateServer that = AllowedArgumentsForCreateServer.class.cast(obj);
return Objects.equal(this.diskSizesInGB, that.diskSizesInGB)
&& Objects.equal(this.memorySizesInMB, that.memorySizesInMB)
&& Objects.equal(this.cpuCoreOptions, that.cpuCoreOptions)
&& Objects.equal(this.templateNames, that.templateNames)
&& Objects.equal(this.transfersInGB, that.transfersInGB)
&& Objects.equal(this.dataCenters, that.dataCenters);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("diskSizesInGB", diskSizesInGB).add("memorySizesInMB", memorySizesInMB)
.add("cpuCoreOptions", cpuCoreOptions).add("templateNames", templateNames)
.add("transfersInGB", transfersInGB).add("dataCenters", dataCenters);
} }
@Override @Override
public String toString() { public String toString() {
checkNotNull(diskSizes, "diskSizes"); return string().toString();
checkNotNull(memorySizes, "memorySizes");
checkNotNull(cpuCores, "cpuCores");
checkNotNull(templates, "templates");
checkNotNull(transfers, "transfers");
checkNotNull(dataCenters, "dataCenters");
Joiner commaJoiner = Joiner.on(", ");
return String.format("[disksize=[%s], memorysize=[%s], cpuCores=[%s], templates=[%s], transfers=[%s], datacenters=[%s]]",
commaJoiner.join(diskSizes), commaJoiner.join(memorySizes), commaJoiner.join(cpuCores), commaJoiner.join(templates),
commaJoiner.join(transfers), commaJoiner.join(dataCenters));
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,8 +18,12 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* Information about an archive * Information about an archive
@ -27,102 +31,143 @@ import com.google.gson.annotations.SerializedName;
* @author Adam Lowe * @author Adam Lowe
* @see <a href= "https://customer.glesys.com/api.php?a=doc#archive_list" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#archive_list" />
*/ */
public class Archive implements Comparable<Archive> { public class Archive {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
return new ConcreteBuilder().fromArchive(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String username; protected String username;
protected String totalSize; protected String totalSize;
protected String freeSize; protected String freeSize;
protected boolean locked; protected boolean locked;
public Builder username(String username) { /**
this.username = username; * @see Archive#getUsername()
return this; */
public T username(String username) {
this.username = checkNotNull(username, "username");
return self();
} }
public Builder totalSize(String totalSize) { /**
this.totalSize = totalSize; * @see Archive#getTotalSize()
return this; */
public T totalSize(String totalSize) {
this.totalSize = checkNotNull(totalSize, "totalSize");
return self();
} }
public Builder freeSize(String freeSize) { /**
this.freeSize = freeSize; * @see Archive#getFreeSize()
return this; */
public T freeSize(String freeSize) {
this.freeSize = checkNotNull(freeSize, "freeSize");
return self();
} }
public Builder locked(boolean locked) { /**
* @see Archive#isLocked()
*/
public T locked(boolean locked) {
this.locked = locked; this.locked = locked;
return this; return self();
} }
public Archive build() { public Archive build() {
return new Archive(username, totalSize, freeSize, locked); return new Archive(username, totalSize, freeSize, new GleSYSBoolean(locked));
} }
public Builder fromArchive(Archive in) { public T fromArchive(Archive in) {
return username(in.getUsername()).totalSize(in.getTotalSize()).freeSize(in.getFreeSize()).locked(in.isLocked()); return this
.username(in.getUsername())
.totalSize(in.getTotalSize())
.freeSize(in.getFreeSize())
.locked(in.isLocked());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
private final String username; private final String username;
@SerializedName("size_total")
private final String totalSize; private final String totalSize;
@SerializedName("size_free")
private final String freeSize; private final String freeSize;
private final boolean locked; private final boolean locked;
/** @return the name (username) of the archive */ @ConstructorProperties({
"username", "sizetotal", "sizefree", "locked"
})
protected Archive(String username, String totalSize, String freeSize, GleSYSBoolean locked) {
this.username = checkNotNull(username, "username");
this.totalSize = checkNotNull(totalSize, "totalSize");
this.freeSize = checkNotNull(freeSize, "freeSize");
this.locked = checkNotNull(locked, "locked").getValue();
}
/**
* @return the name (username) of the archive
*/
public String getUsername() { public String getUsername() {
return username; return this.username;
} }
/** @return the total size of the archive, ex. "10 GB" */ /**
* @return the total size of the archive, ex. "10 GB"
*/
public String getTotalSize() { public String getTotalSize() {
return totalSize; return this.totalSize;
} }
/** @return the free space left of the archive */ /**
* @return the free space left of the archive
*/
public String getFreeSize() { public String getFreeSize() {
return freeSize; return this.freeSize;
} }
/** @return true if the archive is locked */ /**
* @return true if the archive is locked
*/
public boolean isLocked() { public boolean isLocked() {
return locked; return this.locked;
}
public Archive(String username, String totalSize, String freeSize, boolean locked) {
this.username = username;
this.totalSize = totalSize;
this.freeSize = freeSize;
this.locked = locked;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(username); return Objects.hashCode(username, totalSize, freeSize, locked);
}
@Override
public int compareTo(Archive other) {
return username.compareTo(other.getUsername());
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) return true;
return true; if (obj == null || getClass() != obj.getClass()) return false;
} Archive that = Archive.class.cast(obj);
return obj instanceof Archive return Objects.equal(this.username, that.username)
&& Objects.equal(username, ((Archive) obj).username); && Objects.equal(this.totalSize, that.totalSize)
&& Objects.equal(this.freeSize, that.freeSize)
&& Objects.equal(this.locked, that.locked);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("username", username).add("totalSize", totalSize).add("freeSize", freeSize).add("locked", locked);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("[username=%s, totalSize=%s, freeSize=%s, locked=%b]", username, totalSize, freeSize, locked); return string().toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,14 +18,14 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Arrays; import java.beans.ConstructorProperties;
import java.util.List; import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableList;
/** /**
* The allowed arguments for archive manipulation, such as archivesize * The allowed arguments for archive manipulation, such as archivesize
@ -34,53 +34,62 @@ import com.google.gson.annotations.SerializedName;
* @see <a href= "https://customer.glesys.com/api.php?a=doc#archive_allowedarguments" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#archive_allowedarguments" />
*/ */
public class ArchiveAllowedArguments { public class ArchiveAllowedArguments {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private List<Integer> archiveSizes; return new ConcreteBuilder().fromArchiveAllowedArguments(this);
}
public Builder archiveSizes(List<Integer> archiveSizes) { public static abstract class Builder<T extends Builder<T>> {
this.archiveSizes = archiveSizes; protected abstract T self();
return this;
protected List<Integer> archiveSizes = ImmutableList.of();
/**
* @see ArchiveAllowedArguments#getArchiveSizes()
*/
public T archiveSizes(List<Integer> archiveSizes) {
this.archiveSizes = ImmutableList.copyOf(checkNotNull(archiveSizes, "archiveSizes"));
return self();
} }
public Builder archiveSizes(Integer... archiveSizes) { public T archiveSizes(Integer... in) {
return archiveSizes(Arrays.asList(archiveSizes)); return archiveSizes(ImmutableList.copyOf(in));
} }
public ArchiveAllowedArguments build() { public ArchiveAllowedArguments build() {
return new ArchiveAllowedArguments(archiveSizes); return new ArchiveAllowedArguments(archiveSizes);
} }
public Builder fromArchiveAllowedArguments(ArchiveAllowedArguments in) { public T fromArchiveAllowedArguments(ArchiveAllowedArguments in) {
return archiveSizes(in.getArchiveSizes()); return this.archiveSizes(in.getArchiveSizes());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
@SerializedName("archivesize")
private final List<Integer> archiveSizes; private final List<Integer> archiveSizes;
public ArchiveAllowedArguments(List<Integer> archiveSizes) { @ConstructorProperties({
checkArgument(archiveSizes != null, "archiveSizes"); "archivesize"
this.archiveSizes = archiveSizes; })
protected ArchiveAllowedArguments(List<Integer> archiveSizes) {
this.archiveSizes = ImmutableList.copyOf(checkNotNull(archiveSizes, "archiveSizes"));
} }
/** /**
* @return the list of allowed archive sizes, in GB * @return the list of allowed archive sizes, in GB
*/ */
public List<Integer> getArchiveSizes() { public List<Integer> getArchiveSizes() {
return archiveSizes; return this.archiveSizes;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
return object instanceof ArchiveAllowedArguments
&& Objects.equal(archiveSizes, ((ArchiveAllowedArguments) object).archiveSizes);
} }
@Override @Override
@ -88,11 +97,22 @@ public class ArchiveAllowedArguments {
return Objects.hashCode(archiveSizes); return Objects.hashCode(archiveSizes);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ArchiveAllowedArguments that = ArchiveAllowedArguments.class.cast(obj);
return Objects.equal(this.archiveSizes, that.archiveSizes);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("archiveSizes", archiveSizes);
}
@Override @Override
public String toString() { public String toString() {
Joiner commaJoiner = Joiner.on(", "); return string().toString();
return String.format(
"[archiveSizes=[%s]]", commaJoiner.join(archiveSizes));
} }
} }

View File

@ -1,65 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.glesys.domain;
/**
* Detailed information about an archive volume.
*
* @author Adam Lowe
* @see <a href= "https://customer.glesys.com/api.php?a=doc#archive_details" />
*/
public class ArchiveDetails extends Archive {
public static Builder builder() {
return new Builder();
}
public static class Builder extends Archive.Builder {
public ArchiveDetails build() {
return new ArchiveDetails(username, totalSize, freeSize, locked);
}
public Builder fromArchiveDetails(ArchiveDetails in) {
return username(in.getUsername()).totalSize(in.getTotalSize()).freeSize(in.getFreeSize()).locked(in.isLocked());
}
@Override
public Builder username(String username) {
return Builder.class.cast(super.username(username));
}
@Override
public Builder totalSize(String size) {
return Builder.class.cast(super.totalSize(size));
}
@Override
public Builder freeSize(String size) {
return Builder.class.cast(super.freeSize(size));
}
@Override
public Builder locked(boolean locked) {
return Builder.class.cast(super.locked(locked));
}
}
public ArchiveDetails(String username, String totalSize, String freeSize, boolean locked) {
super(username, totalSize, freeSize, locked);
}
}

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,7 +18,12 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* Connection information to connect to a server with VNC. * Connection information to connect to a server with VNC.
@ -27,44 +32,69 @@ import com.google.common.base.Objects;
* @see <a href="https://customer.glesys.com/api.php?a=doc#server_console" /> * @see <a href="https://customer.glesys.com/api.php?a=doc#server_console" />
*/ */
public class Console { public class Console {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private String host; return new ConcreteBuilder().fromConsole(this);
private int port; }
private String protocol;
private String password;
public Builder host(String host) { public static abstract class Builder<T extends Builder<T>> {
this.host = host; protected abstract T self();
return this;
protected String host;
protected int port;
protected String protocol;
protected String password;
/**
* @see Console#getHost()
*/
public T host(String host) {
this.host = checkNotNull(host, "host");
return self();
} }
public Builder port(int port) { /**
* @see Console#getPort()
*/
public T port(int port) {
this.port = port; this.port = port;
return this; return self();
} }
public Builder password(String password) { /**
this.password = password; * @see Console#getProtocol()
return this; */
public T protocol(String protocol) {
this.protocol = checkNotNull(protocol, "protocol");
return self();
} }
public Builder protocol(String protocol) { /**
this.protocol = protocol; * @see Console#getPassword()
return this; */
public T password(String password) {
this.password = checkNotNull(password, "password");
return self();
} }
public Console build() { public Console build() {
return new Console(host, port, protocol, password); return new Console(host, port, protocol, password);
} }
public Builder fromConsole(Console in) { public T fromConsole(Console in) {
return host(in.getHost()).port(in.getPort()).password(in.getPassword()).protocol(in.getProtocol()); return this.host(in.getHost()).port(in.getPort()).protocol(in.getProtocol()).password(in.getPassword());
} }
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
} }
private final String host; private final String host;
@ -72,54 +102,42 @@ public class Console {
private final String protocol; private final String protocol;
private final String password; private final String password;
public Console(String host, int port, String protocol, String password) { @ConstructorProperties({
this.host = host; "host", "port", "protocol", "password"
})
protected Console(String host, int port, String protocol, String password) {
this.host = checkNotNull(host, "host");
this.port = port; this.port = port;
this.protocol = protocol; this.protocol = checkNotNull(protocol, "protocol");
this.password = password; this.password = checkNotNull(password, "password");
} }
/** /**
* @return the host name to use to connect to the server * @return the host name to use to connect to the server
*/ */
public String getHost() { public String getHost() {
return host; return this.host;
} }
/** /**
* @return the port to use to connect to the server * @return the port to use to connect to the server
*/ */
public int getPort() { public int getPort() {
return port; return this.port;
} }
/** /**
* @return the protocol to use to connect to the server * @return the protocol to use to connect to the server
*/ */
public String getProtocol() { public String getProtocol() {
return protocol; return this.protocol;
} }
/** /**
* @return the password to use to connect to the server * @return the password to use to connect to the server
*/ */
public String getPassword() { public String getPassword() {
return password; return this.password;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Console) {
final Console other = (Console) object;
return Objects.equal(host, other.host)
&& Objects.equal(port, other.port)
&& Objects.equal(protocol, other.protocol);
} else {
return false;
}
} }
@Override @Override
@ -127,9 +145,24 @@ public class Console {
return Objects.hashCode(host, port, protocol); return Objects.hashCode(host, port, protocol);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Console that = Console.class.cast(obj);
return Objects.equal(this.host, that.host)
&& Objects.equal(this.port, that.port)
&& Objects.equal(this.protocol, that.protocol);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("host", host).add("port", port).add("protocol", protocol)
.add("password", password);
}
@Override @Override
public String toString() { public String toString() {
return String.format("[host=%s, port=%s, protocol=%s, password=%s]", host, port, protocol, password); return string().toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -20,8 +20,10 @@ package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* The Cost class contains information about the cost of a server * The Cost class contains information about the cost of a server
@ -30,84 +32,94 @@ import com.google.gson.annotations.SerializedName;
* @see ServerDetails * @see ServerDetails
*/ */
public class Cost { public class Cost {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private double amount; return new ConcreteBuilder().fromCost(this);
private String currency; }
private String timePeriod;
public Builder amount(double amount) { public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected double amount;
protected String currency;
protected String timePeriod;
/**
* @see Cost#getAmount()
*/
public T amount(double amount) {
this.amount = amount; this.amount = amount;
return this; return self();
} }
public Builder currency(String currency) { /**
this.currency = currency; * @see Cost#getCurrency()
return this; */
public T currency(String currency) {
this.currency = checkNotNull(currency, "currency");
return self();
} }
public Builder timePeriod(String timePeriod) { /**
this.timePeriod = timePeriod; * @see Cost#getTimePeriod()
return this; */
public T timePeriod(String timePeriod) {
this.timePeriod = checkNotNull(timePeriod, "timePeriod");
return self();
} }
public Cost build() { public Cost build() {
return new Cost(amount, currency, timePeriod); return new Cost(amount, currency, timePeriod);
} }
public Builder fromCost(Cost cost) { public T fromCost(Cost in) {
return amount(cost.getAmount()).currency(cost.getCurrency()).timePeriod(cost.getTimePeriod()); return this.amount(in.getAmount()).currency(in.getCurrency()).timePeriod(in.getTimePeriod());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
private final double amount; private final double amount;
private final String currency; private final String currency;
@SerializedName("timeperiod")
private final String timePeriod; private final String timePeriod;
public Cost(double amount, String currency, String timePeriod) { @ConstructorProperties({
"amount", "currency", "timeperiod"
})
protected Cost(double amount, String currency, String timePeriod) {
this.amount = amount; this.amount = amount;
this.currency = checkNotNull(currency, "currency"); this.currency = checkNotNull(currency, "currency");
this.timePeriod = timePeriod; this.timePeriod = checkNotNull(timePeriod, "timePeriod");
} }
/** /**
* @return the numeric cost in #currency / #timePeriod * @return the numeric cost in #currency / #timePeriod
*/ */
public double getAmount() { public double getAmount() {
return amount; return this.amount;
} }
/** /**
* @return the currency unit, e.g. "EUR" for Euro * @return the currency unit, e.g. "EUR" for Euro
*/ */
public String getCurrency() { public String getCurrency() {
return currency; return this.currency;
} }
/** /**
* @return the time period for which this cost charged, e.g. "month" * @return the time period for which this cost charged, e.g. "month"
*/ */
public String getTimePeriod() { public String getTimePeriod() {
return timePeriod; return this.timePeriod;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Cost) {
Cost other = (Cost) object;
return Objects.equal(amount, other.amount)
&& Objects.equal(currency, other.currency)
&& Objects.equal(timePeriod, other.timePeriod);
} else {
return false;
}
} }
@Override @Override
@ -115,9 +127,23 @@ public class Cost {
return Objects.hashCode(amount, currency, timePeriod); return Objects.hashCode(amount, currency, timePeriod);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Cost that = Cost.class.cast(obj);
return Objects.equal(this.amount, that.amount)
&& Objects.equal(this.currency, that.currency)
&& Objects.equal(this.timePeriod, that.timePeriod);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("amount", amount).add("currency", currency).add("timePeriod", timePeriod);
}
@Override @Override
public String toString() { public String toString() {
return String.format( return string().toString();
"[amount=%f, currency=%s, timePeriod=%s]", amount, currency, timePeriod);
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,10 +18,15 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Date; import java.util.Date;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* Domain data for a Glesys account. * Domain data for a Glesys account.
@ -29,80 +34,253 @@ import com.google.gson.annotations.SerializedName;
* @author Adam Lowe * @author Adam Lowe
* @see <a href= "https://customer.glesys.com/api.php?a=doc#domain_list" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#domain_list" />
*/ */
public class Domain implements Comparable<Domain> { public class Domain {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private String domainName; return new ConcreteBuilder().fromDomain(this);
private Date createTime; }
private int recordCount;
private boolean useGlesysNameServer;
public Builder domainName(String domainName) { public static abstract class Builder<T extends Builder<T>> {
this.domainName = domainName; protected abstract T self();
return this;
protected String domainName;
protected Date createTime;
protected int recordCount;
protected boolean useGlesysNameServer;
protected String primaryNameServer;
protected String responsiblePerson;
protected int ttl;
protected int refresh;
protected int retry;
protected int expire;
protected int minimum;
/**
* @see Domain#getDomainName()
*/
public T domainName(String domainName) {
this.domainName = checkNotNull(domainName, "domainName");
return self();
} }
public Builder createTime(Date createTime) { /**
* @see Domain#getCreateTime()
*/
public T createTime(Date createTime) {
this.createTime = createTime; this.createTime = createTime;
return this; return self();
} }
public Builder recordCount(int recordCount) { /**
* @see Domain#getRecordCount()
*/
public T recordCount(int recordCount) {
this.recordCount = recordCount; this.recordCount = recordCount;
return this; return self();
} }
public Builder useGlesysNameServer(boolean useGlesysNameServer) { /**
* @see Domain#isUseGlesysNameServer()
*/
public T useGlesysNameServer(boolean useGlesysNameServer) {
this.useGlesysNameServer = useGlesysNameServer; this.useGlesysNameServer = useGlesysNameServer;
return this; return self();
}
/**
* @see Domain#getPrimaryNameServer()
*/
public T primaryNameServer(String primaryNameServer) {
this.primaryNameServer = primaryNameServer;
return self();
}
/**
* @see Domain#getResponsiblePerson()
*/
public T responsiblePerson(String responsiblePerson) {
this.responsiblePerson = responsiblePerson;
return self();
}
/**
* @see Domain#getTtl()
*/
public T ttl(int ttl) {
this.ttl = ttl;
return self();
}
/**
* @see Domain#getRefresh()
*/
public T refresh(int refresh) {
this.refresh = refresh;
return self();
}
/**
* @see Domain#getRetry()
*/
public T retry(int retry) {
this.retry = retry;
return self();
}
/**
* @see Domain#getExpire()
*/
public T expire(int expire) {
this.expire = expire;
return self();
}
/**
* @see Domain#getMinimum()
*/
public T minimum(int minimum) {
this.minimum = minimum;
return self();
} }
public Domain build() { public Domain build() {
return new Domain(domainName, createTime, recordCount, useGlesysNameServer); return new Domain(domainName, createTime, recordCount, new GleSYSBoolean(useGlesysNameServer), primaryNameServer, responsiblePerson, ttl, refresh, retry, expire, minimum);
} }
public Builder fromDomain(Domain in) { public T fromDomain(Domain in) {
return new Builder().domainName(in.getDomainName()).createTime(in.getCreateTime()).recordCount(in.getRecordCount()).useGlesysNameServer(in.isGlesysNameServer()); return this.domainName(in.getDomainName())
.createTime(in.getCreateTime())
.recordCount(in.getRecordCount())
.useGlesysNameServer(in.isUseGlesysNameServer())
.primaryNameServer(in.getPrimaryNameServer())
.responsiblePerson(in.getResponsiblePerson())
.ttl(in.getTtl())
.refresh(in.getRefresh())
.retry(in.getRetry())
.expire(in.getExpire());
} }
} }
@SerializedName("domainname") private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
private final String domainName; @Override
@SerializedName("createtime") protected ConcreteBuilder self() {
private final Date createTime; return this;
@SerializedName("recordcount") }
private final int recordCount; }
@SerializedName("usingglesysnameserver")
private final boolean useGlesysNameServer;
public Domain(String domainName, Date createTime, int recordCount, boolean useGlesysNameServer) { private final String domainName;
this.domainName = domainName; private final Date createTime;
private final int recordCount;
private final boolean useGlesysNameServer;
private final String primaryNameServer;
private final String responsiblePerson;
private final int ttl;
private final int refresh;
private final int retry;
private final int expire;
private final int minimum;
@ConstructorProperties({
"domainname", "createtime", "recordcount", "usingglesysnameserver", "primarynameserver", "responsibleperson",
"ttl", "refresh", "retry", "expire", "minimum"
})
protected Domain(String domainName, @Nullable Date createTime, int recordCount, GleSYSBoolean useGlesysNameServer,
@Nullable String primaryNameServer, @Nullable String responsiblePerson,
int ttl, int refresh, int retry, int expire, int minimum) {
this.domainName = checkNotNull(domainName, "domainName");
this.createTime = createTime; this.createTime = createTime;
this.recordCount = recordCount; this.recordCount = recordCount;
this.useGlesysNameServer = useGlesysNameServer; this.useGlesysNameServer = checkNotNull(useGlesysNameServer, "useGlesysNameServer").getValue();
this.primaryNameServer = primaryNameServer;
this.responsiblePerson = responsiblePerson;
this.ttl = ttl;
this.refresh = refresh;
this.retry = retry;
this.expire = expire;
this.minimum = minimum;
} }
/** @return the domain name, ex. "jclouds.org" */ /**
* @return the domain name, ex. "jclouds.org"
*/
public String getDomainName() { public String getDomainName() {
return domainName; return this.domainName;
} }
/** @return the date the domain was registered with GleSYS */ /**
* @return the date the domain was registered with GleSYS
*/
public Date getCreateTime() { public Date getCreateTime() {
return createTime; return this.createTime;
} }
/** @return the number of DNS records for this domain */ /**
* @return the number of DNS records for this domain
*/
public int getRecordCount() { public int getRecordCount() {
return recordCount; return this.recordCount;
} }
/** @return true if a GleSYS nameserver holds the records */ /**
public boolean isGlesysNameServer() { * @return true if a GleSYS nameserver holds the records
return useGlesysNameServer; */
public boolean isUseGlesysNameServer() {
return this.useGlesysNameServer;
}
@Nullable
public String getPrimaryNameServer() {
return primaryNameServer;
}
/**
* The E-mail address of the person responsible for this domain (reformatted with '.' at end).
*/
@Nullable
public String getResponsiblePerson() {
return responsiblePerson;
}
/**
* TTL (time to live). The number of seconds a domain name is cached locally before expiration and return to authoritative nameServers for updates
*/
public int getTtl() {
return ttl;
}
/**
* The number of seconds between update requests from secondary and slave name servers
*/
public int getRefresh() {
return refresh;
}
/**
* The number of seconds the secondary/slave will wait before retrying when the last attempt failed
*/
public int getRetry() {
return retry;
}
/**
* The number of seconds a master or slave will wait before considering the data stale if it cannot reach the primary name server
*/
public int getExpire() {
return expire;
}
/**
* The minimum/default TTL if the domain does not specify ttl
*
* @see #getTtl()
*/
public int getMinimum() {
return minimum;
} }
@Override @Override
@ -111,25 +289,21 @@ public class Domain implements Comparable<Domain> {
} }
@Override @Override
public int compareTo(Domain other) { public boolean equals(Object obj) {
return domainName.compareTo(other.getDomainName()); if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Domain that = Domain.class.cast(obj);
return Objects.equal(this.domainName, that.domainName);
} }
@Override protected ToStringHelper string() {
public boolean equals(Object object) { return Objects.toStringHelper("")
if (this == object) { .add("domainName", domainName).add("createTime", createTime).add("recordCount", recordCount).add("useGlesysNameServer", useGlesysNameServer);
return true;
}
if (object instanceof Domain) {
return Objects.equal(domainName, ((Domain) object).domainName);
} else {
return false;
}
} }
@Override @Override
public String toString() { public String toString() {
return String.format("[domainname=%s, createtime=%s, count=%d, useglesysnameserver=%b]", domainName, createTime, recordCount, useGlesysNameServer); return string().toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,7 +18,14 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* DNS record data. * DNS record data.
@ -26,55 +33,92 @@ import com.google.common.base.Objects;
* @author Adam Lowe * @author Adam Lowe
* @see <a href= "https://customer.glesys.com/api.php?a=doc#domain_list_records" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#domain_list_records" />
*/ */
public class DomainRecord implements Comparable<DomainRecord> { public class DomainRecord {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private String id; return new ConcreteBuilder().fromDomainRecord(this);
private String domainname; }
private String host;
private String type;
private String data;
private int ttl;
public Builder id(String id) { public static abstract class Builder<T extends Builder<T>> {
this.id = id; protected abstract T self();
return this;
protected String id;
protected String domainname;
protected String host;
protected String type;
protected String data;
protected int ttl;
/**
* @see DomainRecord#getId()
*/
public T id(String id) {
this.id = checkNotNull(id, "id");
return self();
} }
public Builder domainname(String domainname) { /**
this.domainname = domainname; * @see DomainRecord#getDomainname()
return this; */
public T domainname(String domainname) {
this.domainname = checkNotNull(domainname, "domainname");
return self();
} }
public Builder host(String host) { /**
this.host = host; * @see DomainRecord#getHost()
return this; */
public T host(String host) {
this.host = checkNotNull(host, "host");
return self();
} }
public Builder type(String type) { /**
this.type = type; * @see DomainRecord#getType()
return this; */
public T type(String type) {
this.type = checkNotNull(type, "type");
return self();
} }
public Builder data(String data) { /**
this.data = data; * @see DomainRecord#getData()
return this; */
public T data(String data) {
this.data = checkNotNull(data, "data");
return self();
} }
public Builder ttl(int ttl) { /**
* @see DomainRecord#getTtl()
*/
public T ttl(int ttl) {
this.ttl = ttl; this.ttl = ttl;
return this; return self();
} }
public DomainRecord build() { public DomainRecord build() {
return new DomainRecord(id, domainname, host, type, data, ttl); return new DomainRecord(id, domainname, host, type, data, ttl);
} }
public Builder fromDomainRecord(DomainRecord in) { public T fromDomainRecord(DomainRecord in) {
return new Builder().id(in.getId()).domainname(in.getDomainName()).host(in.getHost()).type(in.getType()).data(in.getData()).ttl(in.getTtl()); return this.id(in.getId())
.domainname(in.getDomainname())
.host(in.getHost())
.type(in.getType())
.data(in.getData())
.ttl(in.getTtl());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
@ -85,11 +129,14 @@ public class DomainRecord implements Comparable<DomainRecord> {
private final String data; private final String data;
private final int ttl; private final int ttl;
public DomainRecord(String id, String domainname, String host, String type, String data, int ttl) { @ConstructorProperties({
"recordid", "domainname", "host", "type", "data", "ttl"
})
protected DomainRecord(@Nullable String id, String domainname, String host, String type, @Nullable String data, int ttl) {
this.id = id; this.id = id;
this.domainname = domainname; this.domainname = checkNotNull(domainname, "domainname");
this.host = host; this.host = checkNotNull(host, "host");
this.type = type; this.type = checkNotNull(type, "type");
this.data = data; this.data = data;
this.ttl = ttl; this.ttl = ttl;
} }
@ -99,47 +146,43 @@ public class DomainRecord implements Comparable<DomainRecord> {
* @see org.jclouds.glesys.features.DomainClient * @see org.jclouds.glesys.features.DomainClient
*/ */
public String getId() { public String getId() {
return id; return this.id;
} }
/** /**
* @return the zone content of the record * @return the zone content of the record
*/ */
public String getDomainName() { public String getDomainname() {
return domainname; return this.domainname;
} }
/** /**
* @return the host content of the record * @return the host content of the record
*/ */
public String getHost() { public String getHost() {
return host; return this.host;
} }
/** /**
* @return the type of the record, ex. "A" * @return the type of the record, ex. "A"
*/ */
public String getType() { public String getType() {
return type; return this.type;
} }
/** /**
* @return the data content of the record * @return the data content of the record
*/ */
@Nullable
public String getData() { public String getData() {
return data; return this.data;
} }
/** /**
* @return the TTL/Time-to-live for the record * @return the TTL/Time-to-live for the record
*/ */
public int getTtl() { public int getTtl() {
return ttl; return this.ttl;
}
@Override
public int compareTo(DomainRecord other) {
return id.compareTo(other.getId());
} }
@Override @Override
@ -148,21 +191,22 @@ public class DomainRecord implements Comparable<DomainRecord> {
} }
@Override @Override
public boolean equals(Object object) { public boolean equals(Object obj) {
if (this == object) { if (this == obj) return true;
return true; if (obj == null || getClass() != obj.getClass()) return false;
} DomainRecord that = DomainRecord.class.cast(obj);
if (object instanceof DomainRecord) { return Objects.equal(this.id, that.id);
DomainRecord other = (DomainRecord) object; }
return Objects.equal(id, other.id);
} else { protected ToStringHelper string() {
return false; return Objects.toStringHelper("")
} .add("id", id).add("domainname", domainname).add("host", host).add("type", type).add("data", data)
.add("ttl", ttl);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("[id=%s, domainname=%s, host=%s, type=%s, data=%s, ttl=%d]", id, domainname, host, type, data, ttl); return string().toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,10 +18,15 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Date; import java.util.Date;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* Detailed information on an Email Account * Detailed information on an Email Account
@ -29,181 +34,214 @@ import com.google.gson.annotations.SerializedName;
* @author Adam Lowe * @author Adam Lowe
* @see <a href="https://customer.glesys.com/api.php?a=doc#email_list" /> * @see <a href="https://customer.glesys.com/api.php?a=doc#email_list" />
*/ */
public class EmailAccount implements Comparable<EmailAccount> { public class EmailAccount {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private String account; return new ConcreteBuilder().fromEmailAccount(this);
private String quota; }
private String usedQuota;
private int antispamLevel;
private boolean antiVirus;
private boolean autoRespond;
private String autoRespondMessage;
private boolean autoRespondSaveEmail;
private Date created;
private Date modified;
public Builder account(String account) { public static abstract class Builder<T extends Builder<T>> {
this.account = account; protected abstract T self();
return this;
protected String account;
protected EmailQuota quota;
protected int antispamLevel;
protected boolean antiVirus;
protected boolean autoRespond;
protected String autoRespondMessage;
protected boolean autoRespondSaveEmail;
protected Date created;
protected Date modified;
/**
* @see EmailAccount#getAccount()
*/
public T account(String account) {
this.account = checkNotNull(account, "account");
return self();
} }
public Builder quota(String quota) { /**
this.quota = quota; * @see EmailAccount#getQuota()
return this; */
public T quota(EmailQuota quota) {
this.quota = checkNotNull(quota, "quota");
return self();
} }
public Builder usedQuota(String usedQuota) { /**
this.usedQuota = usedQuota; * @see EmailAccount#getAntispamLevel()
return this; */
} public T antispamLevel(int antispamLevel) {
public Builder antispamLevel(int antispamLevel) {
this.antispamLevel = antispamLevel; this.antispamLevel = antispamLevel;
return this; return self();
} }
public Builder antiVirus(boolean antiVirus) { /**
* @see EmailAccount#isAntiVirus()
*/
public T antiVirus(boolean antiVirus) {
this.antiVirus = antiVirus; this.antiVirus = antiVirus;
return this; return self();
} }
public Builder autoRespond(boolean autoRespond) { /**
* @see EmailAccount#isAutoRespond()
*/
public T autoRespond(boolean autoRespond) {
this.autoRespond = autoRespond; this.autoRespond = autoRespond;
return this; return self();
} }
public Builder autoRespondMessage(String autoRespondMessage) { /**
this.autoRespondMessage = autoRespondMessage; * @see EmailAccount#getAutoRespondMessage()
return this; */
public T autoRespondMessage(String autoRespondMessage) {
this.autoRespondMessage = checkNotNull(autoRespondMessage, "autoRespondMessage");
return self();
} }
public Builder autoRespondSaveEmail(boolean autoRespondSaveEmail) { /**
* @see EmailAccount#isAutoRespondSaveEmail()
*/
public T autoRespondSaveEmail(boolean autoRespondSaveEmail) {
this.autoRespondSaveEmail = autoRespondSaveEmail; this.autoRespondSaveEmail = autoRespondSaveEmail;
return this; return self();
} }
public Builder created(Date created) { /**
this.created = created; * @see EmailAccount#getCreated()
return this; */
public T created(Date created) {
this.created = checkNotNull(created, "created");
return self();
} }
public Builder modified(Date modified) { /**
this.modified = modified; * @see EmailAccount#getModified()
return this; */
public T modified(Date modified) {
this.modified = checkNotNull(modified, "modified");
return self();
} }
public EmailAccount build() { public EmailAccount build() {
return new EmailAccount(account, quota, usedQuota, antispamLevel, antiVirus, autoRespond, autoRespondMessage, return new EmailAccount(account, quota, antispamLevel, new GleSYSBoolean(antiVirus), new GleSYSBoolean(autoRespond), autoRespondMessage, new GleSYSBoolean(autoRespondSaveEmail), created, modified);
autoRespondSaveEmail, created, modified);
} }
public Builder fromEmail(EmailAccount in) { public T fromEmailAccount(EmailAccount in) {
return account(in.getAccount()).quota(in.getQuota()).usedQuota(in.getUsedQuota()).antispamLevel(in.getAntispamLevel()). return this.account(in.getAccount())
antiVirus(in.getAntiVirus()).autoRespond(in.getAutoRespond()).autoRespondMessage(in.getAutoRespondMessage()). .quota(in.getQuota())
autoRespondSaveEmail(in.getAutoRespondSaveEmail()).created(in.getCreated()).modified(in.getModified()); .antispamLevel(in.getAntispamLevel())
.antiVirus(in.isAntiVirus())
.autoRespond(in.isAutoRespond())
.autoRespondMessage(in.getAutoRespondMessage())
.autoRespondSaveEmail(in.isAutoRespondSaveEmail())
.created(in.getCreated())
.modified(in.getModified());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
@SerializedName("emailaccount")
private final String account; private final String account;
private final String quota; private final EmailQuota quota;
@SerializedName("usedquota")
private final String usedQuota;
@SerializedName("antispamlevel")
private final int antispamLevel; private final int antispamLevel;
@SerializedName("antivirus")
private final boolean antiVirus; private final boolean antiVirus;
@SerializedName("autorespond")
private final boolean autoRespond; private final boolean autoRespond;
@SerializedName("autorespondmessage")
private final String autoRespondMessage; private final String autoRespondMessage;
@SerializedName("autorespondsaveemail")
private final boolean autoRespondSaveEmail; private final boolean autoRespondSaveEmail;
private final Date created; private final Date created;
private final Date modified; private final Date modified;
public EmailAccount(String account, String quota, String usedQuota, int antispamLevel, boolean antiVirus, boolean autoRespond, String autoRespondMessage, boolean autoRespondSaveEmail, Date created, Date modified) { @ConstructorProperties({
this.account = account; "emailaccount", "quota", "antispamlevel", "antivirus", "autorespond", "autorespondmessage", "autorespondsaveemail", "created", "modified"
this.quota = quota; })
this.usedQuota = usedQuota; protected EmailAccount(String account, EmailQuota quota, int antispamLevel,
GleSYSBoolean antiVirus, GleSYSBoolean autoRespond, @Nullable String autoRespondMessage,
GleSYSBoolean autoRespondSaveEmail, Date created, @Nullable Date modified) {
this.account = checkNotNull(account, "account");
this.quota = checkNotNull(quota, "quota");
this.antispamLevel = antispamLevel; this.antispamLevel = antispamLevel;
this.antiVirus = antiVirus; this.antiVirus = checkNotNull(antiVirus, "antiVirus").getValue();
this.autoRespond = autoRespond; this.autoRespond = checkNotNull(autoRespond, "autoRespond").getValue();
this.autoRespondMessage = autoRespondMessage; this.autoRespondMessage = autoRespondMessage;
this.autoRespondSaveEmail = autoRespondSaveEmail; this.autoRespondSaveEmail = checkNotNull(autoRespondSaveEmail, "autoRespondSaveEmail").getValue();
this.created = created; this.created = checkNotNull(created, "created");
this.modified = modified; this.modified = modified;
} }
/** @return the e-mail address for this e-mail account */ /**
* @return the e-mail address for this e-mail account
*/
public String getAccount() { public String getAccount() {
return account; return this.account;
} }
/** @return the quota for this e-mail account */ /**
public String getQuota() { * @return the quota for this e-mail account
return quota; */
public EmailQuota getQuota() {
return this.quota;
} }
/** @return the amount of quota currently in use */ /**
public String getUsedQuota() { * @return the antispam level of the e-mail account
return usedQuota; */
}
/** @return the antispam level of the e-mail account */
public int getAntispamLevel() { public int getAntispamLevel() {
return antispamLevel; return this.antispamLevel;
} }
/** @return true if antivirus is enabled for this e-mail account */ /**
public boolean getAntiVirus() { * @return true if antivirus is enabled for this e-mail account
return antiVirus; */
public boolean isAntiVirus() {
return this.antiVirus;
} }
/** @return true if auto-respond is enabled for this e-mail account */ /**
public boolean getAutoRespond() { * @return true if auto-respond is enabled for this e-mail account
return autoRespond; */
public boolean isAutoRespond() {
return this.autoRespond;
} }
/**
* @return the auto-respond message for this e-mail account
*/
@Nullable
public String getAutoRespondMessage() { public String getAutoRespondMessage() {
return autoRespondMessage; return this.autoRespondMessage;
} }
/** @return true if saving is enabled for auto-respond e-mails */ /**
public boolean getAutoRespondSaveEmail() { * @return true if saving is enabled for auto-respond e-mails
return autoRespondSaveEmail; */
public boolean isAutoRespondSaveEmail() {
return this.autoRespondSaveEmail;
} }
/** @return when this account was created */ /**
* @return when this account was created
*/
public Date getCreated() { public Date getCreated() {
return created; return this.created;
} }
/** @return when this account was last modified */ /**
* @return when this account was last modified
*/
@Nullable
public Date getModified() { public Date getModified() {
return modified; return this.modified;
}
@Override
public int compareTo(EmailAccount other) {
return account.compareTo(other.getAccount());
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof EmailAccount) {
EmailAccount other = (EmailAccount) object;
return Objects.equal(account, other.account);
} else {
return false;
}
} }
@Override @Override
@ -211,12 +249,22 @@ public class EmailAccount implements Comparable<EmailAccount> {
return Objects.hashCode(account); return Objects.hashCode(account);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EmailAccount that = EmailAccount.class.cast(obj);
return Objects.equal(this.account, that.account);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("account", account).add("quota", quota).add("antispamLevel", antispamLevel).add("antiVirus", antiVirus).add("autoRespond", autoRespond).add("autoRespondMessage", autoRespondMessage).add("autoRespondSaveEmail", autoRespondSaveEmail).add("created", created).add("modified", modified);
}
@Override @Override
public String toString() { public String toString() {
return String.format("account=%s, quota=%s, usedquota=%s, antispamLevel=%d, " + return string().toString();
"antiVirus=%b, autoRespond=%b, autoRespondMessage=%s, autoRespondSaveEmail=%b, " +
"created=%s, modified=%s", account, quota, usedQuota, antispamLevel, antiVirus, autoRespond, autoRespondMessage,
autoRespondSaveEmail, created.toString(), modified.toString());
} }
} }

View File

@ -0,0 +1,130 @@
/*
* 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.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Detailed information on an Email Account
*
* @author Adam Lowe
* @see <a href="https://customer.glesys.com/api.php?a=doc#email_list" />
*/
public class EmailAlias {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromEmailAlias(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String alias;
protected String forwardTo;
/**
* @see org.jclouds.glesys.domain.EmailAlias#getAlias()
*/
public T alias(String alias) {
this.alias = checkNotNull(alias, "alias");
return self();
}
/**
* @see EmailAlias#getForwardTo()
*/
public T forwardTo(String forwardTo) {
this.forwardTo = checkNotNull(forwardTo, "forwardTo");
return self();
}
public EmailAlias build() {
return new EmailAlias(alias, forwardTo);
}
public T fromEmailAlias(EmailAlias in) {
return this.alias(in.getAlias()).forwardTo(in.getForwardTo());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String alias;
private final String forwardTo;
@ConstructorProperties({
"emailalias", "goto"
})
protected EmailAlias(String alias, String forwardTo) {
this.alias = checkNotNull(alias, "alias");
this.forwardTo = checkNotNull(forwardTo, "forwardTo");
}
/**
* @return the e-mail address being forwarded
*/
public String getAlias() {
return this.alias;
}
/**
* @return the e-mail address this address forwards to
*/
public String getForwardTo() {
return this.forwardTo;
}
@Override
public int hashCode() {
return Objects.hashCode(alias);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EmailAlias that = EmailAlias.class.cast(obj);
return Objects.equal(this.alias, that.alias);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("alias", alias).add("forwardTo", forwardTo);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,11 +18,14 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Set; import java.util.Set;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.google.common.base.Joiner;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
/** /**
@ -34,53 +37,80 @@ import com.google.common.collect.ImmutableSet;
//TODO: find a better name for this class //TODO: find a better name for this class
@Beta @Beta
public class EmailOverview { public class EmailOverview {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private EmailOverviewSummary summary; return new ConcreteBuilder().fromEmailOverview(this);
private Set<EmailOverviewDomain> domains; }
public Builder summary(EmailOverviewSummary summary) { public static abstract class Builder<T extends Builder<T>> {
this.summary = summary; protected abstract T self();
return this;
protected EmailOverviewSummary summary;
protected Set<EmailOverviewDomain> domains = ImmutableSet.of();
/**
* @see EmailOverview#getSummary()
*/
public T summary(EmailOverviewSummary summary) {
this.summary = checkNotNull(summary, "summary");
return self();
} }
public Builder domains(Set<EmailOverviewDomain> domains) { /**
this.domains = domains; * @see EmailOverview#getDomains()
return this; */
public T domains(Set<EmailOverviewDomain> domains) {
this.domains = ImmutableSet.copyOf(checkNotNull(domains, "domains"));
return self();
} }
public Builder domains(EmailOverviewDomain... domains) { public T domains(EmailOverviewDomain... in) {
return domains(ImmutableSet.copyOf(domains)); return domains(ImmutableSet.copyOf(in));
} }
public EmailOverview build() { public EmailOverview build() {
return new EmailOverview(summary, domains); return new EmailOverview(summary, domains);
} }
public Builder fromEmailOverview(EmailOverview in) { public T fromEmailOverview(EmailOverview in) {
return summary(in.getSummary()).domains(in.getDomains()); return this.summary(in.getSummary()).domains(in.getDomains());
} }
} }
private EmailOverviewSummary summary; private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
private Set<EmailOverviewDomain> domains; @Override
protected ConcreteBuilder self() {
public EmailOverview(EmailOverviewSummary summary, Set<EmailOverviewDomain> domains) { return this;
this.summary = summary; }
this.domains = domains;
} }
/** @return summary information about the account */ private final EmailOverviewSummary summary;
private final Set<EmailOverviewDomain> domains;
@ConstructorProperties({
"summary", "domains"
})
protected EmailOverview(EmailOverviewSummary summary, Set<EmailOverviewDomain> domains) {
this.summary = checkNotNull(summary, "summary");
this.domains = ImmutableSet.copyOf(checkNotNull(domains, "domains"));
}
/**
* @return summary information about the account
*/
public EmailOverviewSummary getSummary() { public EmailOverviewSummary getSummary() {
return summary; return this.summary;
} }
/** @return the set of detailed information about the e-mail addresses and aliases for each domain */ /**
* @return the set of detailed information about the e-mail addresses and aliases for each domain
*/
public Set<EmailOverviewDomain> getDomains() { public Set<EmailOverviewDomain> getDomains() {
return domains == null ? ImmutableSet.<EmailOverviewDomain>of() : domains; return this.domains;
} }
@Override @Override
@ -89,23 +119,22 @@ public class EmailOverview {
} }
@Override @Override
public boolean equals(Object object) { public boolean equals(Object obj) {
if (object == this) { if (this == obj) return true;
return true; if (obj == null || getClass() != obj.getClass()) return false;
} EmailOverview that = EmailOverview.class.cast(obj);
if (object instanceof EmailOverview) { return Objects.equal(this.summary, that.summary)
EmailOverview other = (EmailOverview) object; && Objects.equal(this.domains, that.domains);
return Objects.equal(summary, other.summary) }
&& Objects.equal(domains, other.domains);
} else { protected ToStringHelper string() {
return false; return Objects.toStringHelper("")
} .add("summary", summary).add("domains", domains);
} }
@Override @Override
public String toString() { public String toString() {
Joiner commaJoiner = Joiner.on(", "); return string().toString();
return String.format("summary=%s, domains=[%s]", summary, commaJoiner.join(getDomains()));
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,8 +18,13 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* Detailed information about e-mail settings for a single domain * Detailed information about e-mail settings for a single domain
@ -27,39 +32,61 @@ import com.google.common.base.Objects;
* @author Adam Lowe * @author Adam Lowe
* @see <a href="https://customer.glesys.com/api.php?a=doc#email_overview" /> * @see <a href="https://customer.glesys.com/api.php?a=doc#email_overview" />
*/ */
//TODO: find a better name for this class
@Beta @Beta
public class EmailOverviewDomain { public class EmailOverviewDomain {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private String domain; return new ConcreteBuilder().fromEmailOverviewDomain(this);
private int accounts; }
private int aliases;
public Builder domain(String domain) { public static abstract class Builder<T extends Builder<T>> {
this.domain = domain; protected abstract T self();
return this;
protected String domain;
protected int accounts;
protected int aliases;
/**
* @see EmailOverviewDomain#getDomain()
*/
public T domain(String domain) {
this.domain = checkNotNull(domain, "domain");
return self();
} }
public Builder accounts(int accounts) { /**
* @see EmailOverviewDomain#getAccounts()
*/
public T accounts(int accounts) {
this.accounts = accounts; this.accounts = accounts;
return this; return self();
} }
public Builder aliases(int aliases) { /**
* @see EmailOverviewDomain#getAliases()
*/
public T aliases(int aliases) {
this.aliases = aliases; this.aliases = aliases;
return this; return self();
} }
public EmailOverviewDomain build() { public EmailOverviewDomain build() {
return new EmailOverviewDomain(domain, accounts, aliases); return new EmailOverviewDomain(domain, accounts, aliases);
} }
public Builder fromEmailOverview(EmailOverviewDomain in) { public T fromEmailOverviewDomain(EmailOverviewDomain in) {
return domain(domain).accounts(in.getAccounts()).aliases(in.getAliases()); return this.domain(in.getDomain()).accounts(in.getAccounts()).aliases(in.getAliases());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
@ -67,25 +94,28 @@ public class EmailOverviewDomain {
private final int accounts; private final int accounts;
private final int aliases; private final int aliases;
public EmailOverviewDomain(String domain, int accounts, int aliases) { @ConstructorProperties({
this.domain = domain; "domainname", "accounts", "aliases"
})
protected EmailOverviewDomain(String domain, int accounts, int aliases) {
this.domain = checkNotNull(domain, "domain");
this.accounts = accounts; this.accounts = accounts;
this.aliases = aliases; this.aliases = aliases;
} }
/** @return the domain name */ /** @return the domain name */
public String getDomain() { public String getDomain() {
return domain; return this.domain;
} }
/** @return the number of e-mail accounts in the domain */ /** @return the number of e-mail accounts in the domain */
public int getAccounts() { public int getAccounts() {
return accounts; return this.accounts;
} }
/** @return the number of e-mail aliases in the domain */ /** @return the number of e-mail aliases in the domain */
public int getAliases() { public int getAliases() {
return aliases; return this.aliases;
} }
@Override @Override
@ -94,21 +124,20 @@ public class EmailOverviewDomain {
} }
@Override @Override
public boolean equals(Object object) { public boolean equals(Object obj) {
if (object == this) { if (this == obj) return true;
return true; if (obj == null || getClass() != obj.getClass()) return false;
} EmailOverviewDomain that = EmailOverviewDomain.class.cast(obj);
if (object instanceof EmailOverviewDomain) { return Objects.equal(this.domain, that.domain);
EmailOverviewDomain other = (EmailOverviewDomain) object; }
return Objects.equal(domain, other.domain);
} else { protected ToStringHelper string() {
return false; return Objects.toStringHelper("").add("domain", domain).add("accounts", accounts).add("aliases", aliases);
}
} }
@Override @Override
public String toString() { public String toString() {
return String.format("domain=%s, accounts=%d, aliases=%d", domain, accounts, aliases); return string().toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,9 +18,11 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import java.beans.ConstructorProperties;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* Summary information of e-mail settings and limits for a GleSYS account * Summary information of e-mail settings and limits for a GleSYS account
@ -31,77 +33,115 @@ import com.google.gson.annotations.SerializedName;
//TODO: find a better name for this class //TODO: find a better name for this class
@Beta @Beta
public class EmailOverviewSummary { public class EmailOverviewSummary {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private int accounts; return new ConcreteBuilder().fromEmailOverviewSummary(this);
private int maxAccounts; }
private int aliases;
private int maxAliases;
public Builder accounts(int accounts) { public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected int accounts;
protected int maxAccounts;
protected int aliases;
protected int maxAliases;
/**
* @see EmailOverviewSummary#getAccounts()
*/
public T accounts(int accounts) {
this.accounts = accounts; this.accounts = accounts;
return this; return self();
} }
public Builder maxAccounts(int maxAccounts) { /**
* @see EmailOverviewSummary#getMaxAccounts()
*/
public T maxAccounts(int maxAccounts) {
this.maxAccounts = maxAccounts; this.maxAccounts = maxAccounts;
return this; return self();
} }
public Builder aliases(int aliases) { /**
* @see EmailOverviewSummary#getAliases()
*/
public T aliases(int aliases) {
this.aliases = aliases; this.aliases = aliases;
return this; return self();
} }
public Builder maxAliases(int maxAliases) { /**
* @see EmailOverviewSummary#getMaxAliases()
*/
public T maxAliases(int maxAliases) {
this.maxAliases = maxAliases; this.maxAliases = maxAliases;
return this; return self();
} }
public EmailOverviewSummary build() { public EmailOverviewSummary build() {
return new EmailOverviewSummary(accounts, maxAccounts, aliases, maxAliases); return new EmailOverviewSummary(accounts, maxAccounts, aliases, maxAliases);
} }
public Builder fromEmailOverview(EmailOverviewSummary in) { public T fromEmailOverviewSummary(EmailOverviewSummary in) {
return accounts(in.getAccounts()).maxAccounts(in.getMaxAccounts()).aliases(in.getAliases()).maxAliases(in.getMaxAliases()); return this.accounts(in.getAccounts())
.maxAccounts(in.getMaxAccounts())
.aliases(in.getAliases())
.maxAliases(in.getMaxAliases());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
private final int accounts; private final int accounts;
@SerializedName("maxaccounts")
private final int maxAccounts; private final int maxAccounts;
private final int aliases; private final int aliases;
@SerializedName("maxaliases")
private final int maxAliases; private final int maxAliases;
public EmailOverviewSummary(int accounts, int maxAccounts, int aliases, int maxAliases) { @ConstructorProperties({
"accounts", "maxaccounts", "aliases", "maxaliases"
})
protected EmailOverviewSummary(int accounts, int maxAccounts, int aliases, int maxAliases) {
this.accounts = accounts; this.accounts = accounts;
this.maxAccounts = maxAccounts; this.maxAccounts = maxAccounts;
this.aliases = aliases; this.aliases = aliases;
this.maxAliases = maxAliases; this.maxAliases = maxAliases;
} }
/** @return the number of e-mail accounts */ /**
* @return the number of e-mail accounts
*/
public int getAccounts() { public int getAccounts() {
return accounts; return this.accounts;
} }
/** @return the maximum number of e-mail accounts */ /**
* @return the maximum number of e-mail accounts
*/
public int getMaxAccounts() { public int getMaxAccounts() {
return maxAccounts; return this.maxAccounts;
} }
/** @return the number of e-mail aliases */ /**
* @return the number of e-mail aliases
*/
public int getAliases() { public int getAliases() {
return aliases; return this.aliases;
} }
/** @return the maximum number of e-mail aliases */ /**
* @return the maximum number of e-mail aliases
*/
public int getMaxAliases() { public int getMaxAliases() {
return maxAliases; return this.maxAliases;
} }
@Override @Override
@ -110,24 +150,24 @@ public class EmailOverviewSummary {
} }
@Override @Override
public boolean equals(Object object) { public boolean equals(Object obj) {
if (object == this) { if (this == obj) return true;
return true; if (obj == null || getClass() != obj.getClass()) return false;
} EmailOverviewSummary that = EmailOverviewSummary.class.cast(obj);
if (object instanceof EmailOverviewSummary) { return Objects.equal(this.accounts, that.accounts)
EmailOverviewSummary other = (EmailOverviewSummary) object; && Objects.equal(this.maxAccounts, that.maxAccounts)
return Objects.equal(accounts, other.accounts) && Objects.equal(this.aliases, that.aliases)
&& Objects.equal(maxAccounts, other.maxAccounts) && Objects.equal(this.maxAliases, that.maxAliases);
&& Objects.equal(aliases, other.aliases) }
&& Objects.equal(maxAliases, other.maxAliases);
} else { protected ToStringHelper string() {
return false; return Objects.toStringHelper("")
} .add("accounts", accounts).add("maxAccounts", maxAccounts).add("aliases", aliases).add("maxAliases", maxAliases);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("accounts=%d, maxAccounts=%d, aliases=%d, maxAliases=%d", accounts, maxAccounts, aliases, maxAliases); return string().toString();
} }
} }

View File

@ -0,0 +1,130 @@
/*
* 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.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Information on an Email Account Quota size
*
* @author Adam Lowe
* @see <a href="https://customer.glesys.com/api.php?a=doc#email_list" />
*/
public class EmailQuota {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromEmailAccount(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected int max;
protected String unit;
/**
* @see EmailQuota#getMax()
*/
public T max(int max) {
this.max = max;
return self();
}
/**
* @see EmailQuota#getUnit()
*/
public T unit(String unit) {
this.unit = checkNotNull(unit, "unit");
return self();
}
public EmailQuota build() {
return new EmailQuota(max, unit);
}
public T fromEmailAccount(EmailQuota in) {
return this.max(in.getMax()).unit(in.getUnit());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final int max;
private final String unit;
@ConstructorProperties({
"max", "unit"
})
protected EmailQuota(int max, String unit) {
this.max = max;
this.unit = unit;
}
/**
* @return the maximum size of the mailbox (in units)
* @see #getUnit
*/
public int getMax() {
return this.max;
}
/**
* @return the quota for this e-mail account
*/
public String getUnit() {
return this.unit;
}
@Override
public int hashCode() {
return Objects.hashCode(max, unit);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EmailQuota that = EmailQuota.class.cast(obj);
return Objects.equal(this.max, that.max) && Objects.equal(this.unit, that.unit);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("max", max).add("unit", unit);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -0,0 +1,19 @@
package org.jclouds.glesys.domain;
/**
* Wrapping booleans for the time being (gson won't allow TypeAdapter&lt;Boolean&gt;)
*/
public class GleSYSBoolean {
public static final GleSYSBoolean TRUE = new GleSYSBoolean(true);
public static final GleSYSBoolean FALSE = new GleSYSBoolean(false);
private boolean value;
public GleSYSBoolean(boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
}

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -16,107 +16,145 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* Represents an ip address used by a server. * Represents an ip address used by a server.
* *
* @author Adam Lowe * @author Adam Lowe
* @see ServerCreated * @see Server
* @see ServerDetails * @see ServerDetails
*/ */
public class Ip { public class Ip {
public static Builder builder() { public static Builder<?> builder() {
return new Builder(); return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
return new ConcreteBuilder().fromIp(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String ip; protected String ip;
protected int version; protected int version;
protected double cost; protected double cost;
protected String currency;
protected Builder version(int version) { /**
this.version = version; * @see Ip#getIp()
return this; */
public T ip(String ip) {
this.ip = checkNotNull(ip, "ip");
return self();
} }
public Builder version4() { /**
* @see Ip#getVersion()
*/
protected T version(int version) {
this.version = version;
return self();
}
/**
* @see Ip#getVersion()
*/
public T version4() {
return version(4); return version(4);
} }
public Builder version6() { /**
* @see Ip#getVersion()
*/
public T version6() {
return version(6); return version(6);
} }
public Builder ip(String ip) { /**
this.ip = ip; * @see Ip#getCost()
return this; */
public T cost(double cost) {
this.cost = cost;
return self();
} }
public Builder cost(double cost) { /**
this.cost = cost; * @see Ip#getCurrency()
return this; */
public T currency(String currency) {
this.currency = currency;
return self();
} }
public Ip build() { public Ip build() {
return new Ip(ip, version, cost); return new Ip(ip, version, cost, currency);
} }
public Builder fromIpCreated(Ip from) { public T fromIp(Ip in) {
return ip(from.getIp()).version(from.getVersion()).cost(from.getCost()); return this.ip(in.getIp()).version(in.getVersion()).cost(in.getCost());
} }
} }
@SerializedName("ipaddress") private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
protected final String ip; @Override
protected final int version; protected ConcreteBuilder self() {
protected final double cost; return this;
}
}
public Ip(String ip, int version, double cost) { private final String ip;
this.ip = ip; private final int version;
private final double cost;
private final String currency;
@ConstructorProperties({
"ipaddress", "version", "cost", "currency"
})
protected Ip(String ip, int version, double cost, String currency) {
this.ip = checkNotNull(ip, "ip");
this.version = version; this.version = version;
this.cost = cost; this.cost = cost;
this.currency = checkNotNull(currency, "currency");
} }
/** /**
* @return the IP version, ex. 4 * @return the IP version, ex. 4
*/ */
public int getVersion() { public String getIp() {
return version; return this.ip;
} }
/** /**
* @return the ip address of the new server * @return the ip address of the new server
*/ */
public String getIp() { public int getVersion() {
return ip; return this.version;
} }
/** /**
* @return the cost of the ip address allocated to the new server * @return the cost of the ip address allocated to the new server
* @see #getCurrency()
*/ */
public double getCost() { public double getCost() {
return cost; return this.cost;
} }
@Override /**
public boolean equals(Object object) { * @return the currency of the cost
if (this == object) { * @see #getCost()
return true; */
} public String getCurrency() {
if (object instanceof Ip) { return currency;
final Ip other = (Ip) object;
return Objects.equal(ip, other.ip)
&& Objects.equal(version, other.version)
&& Objects.equal(cost, other.cost);
} else {
return false;
}
} }
@Override @Override
@ -125,8 +163,24 @@ public class Ip {
} }
@Override @Override
public String toString() { public boolean equals(Object obj) {
return String.format("[ip=%s, version=%d, cost=%f]", if (this == obj) return true;
ip, version, cost); if (obj == null || getClass() != obj.getClass()) return false;
Ip that = Ip.class.cast(obj);
return Objects.equal(this.ip, that.ip)
&& Objects.equal(this.version, that.version)
&& Objects.equal(this.cost, that.cost)
&& Objects.equal(this.currency, that.currency);
} }
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("ip", ip).add("version", version).add("cost", cost).add("currency", currency);
}
@Override
public String toString() {
return string().toString();
}
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -16,187 +16,311 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import java.util.Arrays; import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.List; import java.util.List;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableList;
/** /**
* Represents detailed information about an IP address. * Represents detailed information about an IP address.
*/ */
public class IpDetails { public class IpDetails {
public static Builder builder() { public static Builder<?> builder() {
return new Builder(); return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
return new ConcreteBuilder().fromIpDetails(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String datacenter; protected String datacenter;
protected String ipversion; protected int ipversion;
protected String ptr; protected String ptr;
protected String platform; protected String platform;
protected String address; protected String address;
protected String netmask; protected String netmask;
protected String broadcast; protected String broadcast;
protected String gateway; protected String gateway;
protected List<String> nameservers; protected List<String> nameServers = ImmutableList.of();
protected String serverId;
protected Cost cost;
protected boolean reserved;
public Builder datacenter(String datacenter) { /**
this.datacenter = datacenter; * @see IpDetails#getDatacenter()
return this; */
public T datacenter(String datacenter) {
this.datacenter = checkNotNull(datacenter, "datacenter");
return self();
} }
public Builder ipversion(String ipversion) { protected T version(int ipversion) {
this.ipversion = ipversion; this.ipversion = ipversion;
return this; return self();
} }
public Builder ptr(String ptr) { /*
this.ptr = ptr; * @see IpDetails#getVersion()
return this; */
public T version4() {
return version(4);
} }
public Builder platform(String platform) { /*
this.platform = platform; * @see IpDetails#getVersion()
return this; */
public T version6() {
return version(6);
}
/**
* @see IpDetails#getPtr()
*/
public T ptr(String ptr) {
this.ptr = checkNotNull(ptr, "ptr");
return self();
}
/**
* @see IpDetails#getPlatform()
*/
public T platform(String platform) {
this.platform = checkNotNull(platform, "platform");
return self();
}
/**
* @see IpDetails#getAddress()
*/
public T address(String address) {
this.address = address;
return self();
}
/**
* @see IpDetails#getNetmask()
*/
public T netmask(String netmask) {
this.netmask = netmask;
return self();
}
/**
* @see IpDetails#getBroadcast()
*/
public T broadcast(String broadcast) {
this.broadcast = broadcast;
return self();
}
/**
* @see IpDetails#getGateway()
*/
public T gateway(String gateway) {
this.gateway = gateway;
return self();
}
/**
* @see IpDetails#getNameServers()
*/
public T nameServers(List<String> nameservers) {
this.nameServers = ImmutableList.copyOf(checkNotNull(nameservers, "nameServers"));
return self();
}
public T nameServers(String... in) {
return nameServers(ImmutableList.copyOf(in));
}
/**
* @see IpDetails#getServerId()
*/
public T serverId(String serverId) {
this.serverId = serverId;
return self();
}
/**
* @see IpDetails#getCost()
*/
public T cost(Cost cost) {
this.cost = cost;
return self();
}
/**
* @see IpDetails#isReserved()
*/
public T reserved(boolean reserved) {
this.reserved = reserved;
return self();
} }
public IpDetails build() { public IpDetails build() {
return new IpDetails(datacenter, ipversion, ptr, platform, return new IpDetails(datacenter, ipversion, ptr, platform, address, netmask, broadcast, gateway, nameServers,
address, netmask, broadcast, gateway, nameservers); serverId, cost, new GleSYSBoolean(reserved));
} }
public Builder address(String address) { public T fromIpDetails(IpDetails in) {
this.address = address; return this.datacenter(in.getDatacenter())
return this; .version(in.getVersion())
.ptr(in.getPtr())
.platform(in.getPlatform())
.address(in.getAddress())
.netmask(in.getNetmask())
.broadcast(in.getBroadcast())
.gateway(in.getGateway())
.nameServers(in.getNameServers())
.serverId(in.getServerId())
.cost(in.getCost())
.reserved(in.isReserved());
} }
}
public Builder netmask(String netmask) { private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
this.netmask = netmask; @Override
return this; protected ConcreteBuilder self() {
}
public Builder broadcast(String broadcast) {
this.broadcast = broadcast;
return this;
}
public Builder gateway(String gateway) {
this.gateway = gateway;
return this;
}
public Builder nameServers(String... nameServers) {
this.nameservers = Arrays.asList(nameServers);
return this; return this;
} }
} }
protected String datacenter; private final String datacenter;
protected String ipversion; private final int version;
@SerializedName("PTR") private final String ptr;
protected String ptr; private final String platform;
protected String platform; private final String address;
protected String address; private final String netmask;
protected String netmask; private final String broadcast;
protected String broadcast; private final String gateway;
protected String gateway; private final List<String> nameServers;
protected List<String> nameservers; private final String serverId;
private final Cost cost;
private final boolean reserved;
public IpDetails(String datacenter, String ipversion, String ptr, String platform, @ConstructorProperties({
@Nullable String address, @Nullable String netmask, "datacenter", "ipversion", "ptr", "platform", "ipaddress", "netmask", "broadcast", "gateway", "nameservers",
@Nullable String broadcast, @Nullable String gateway, "serverid", "cost", "reserved"
@Nullable List<String> nameservers) { })
this.datacenter = datacenter; protected IpDetails(String datacenter, int version, String ptr, String platform, String address,
this.ipversion = ipversion; @Nullable String netmask, @Nullable String broadcast, @Nullable String gateway,
this.ptr = ptr; List<String> nameServers, @Nullable String serverId, Cost cost, GleSYSBoolean reserved) {
this.platform = platform; this.datacenter = checkNotNull(datacenter, "datacenter");
this.version = checkNotNull(version, "version");
this.ptr = checkNotNull(ptr, "ptr");
this.platform = checkNotNull(platform, "platform");
this.address = address; this.address = address;
this.netmask = netmask; this.netmask = netmask;
this.broadcast = broadcast; this.broadcast = broadcast;
this.gateway = gateway; this.gateway = gateway;
this.nameservers = nameservers; this.nameServers = ImmutableList.copyOf(nameServers);
this.serverId = serverId;
this.cost = checkNotNull(cost, "cost");
this.reserved = checkNotNull(reserved, "reserved").getValue();
} }
public String getDatacenter() { public String getDatacenter() {
return datacenter; return this.datacenter;
} }
public String getIpversion() { /**
return ipversion; * @return the IP version, ex. 4
*/
public int getVersion() {
return this.version;
} }
public String getPtr() { public String getPtr() {
return ptr; return this.ptr;
} }
public String getPlatform() { public String getPlatform() {
return platform; return this.platform;
} }
public String getAddress() { public String getAddress() {
return address; return this.address;
} }
@Nullable
public String getNetmask() { public String getNetmask() {
return netmask; return this.netmask;
} }
@Nullable
public String getBroadcast() { public String getBroadcast() {
return broadcast; return this.broadcast;
} }
@Nullable
public String getGateway() { public String getGateway() {
return gateway; return this.gateway;
} }
public List<String> getNameServers() { public List<String> getNameServers() {
return nameservers; return this.nameServers;
} }
@Override @Nullable
public boolean equals(Object o) { public String getServerId() {
if (this == o) return true; return serverId;
if (o == null || getClass() != o.getClass()) return false; }
IpDetails ipDetails = (IpDetails) o; public Cost getCost() {
return cost;
}
if (address != null ? !address.equals(ipDetails.address) : ipDetails.address != null) return false; public boolean isReserved() {
if (broadcast != null ? !broadcast.equals(ipDetails.broadcast) : ipDetails.broadcast != null) return false; return reserved;
if (datacenter != null ? !datacenter.equals(ipDetails.datacenter) : ipDetails.datacenter != null) return false;
if (gateway != null ? !gateway.equals(ipDetails.gateway) : ipDetails.gateway != null) return false;
if (ipversion != null ? !ipversion.equals(ipDetails.ipversion) : ipDetails.ipversion != null) return false;
if (netmask != null ? !netmask.equals(ipDetails.netmask) : ipDetails.netmask != null) return false;
if (platform != null ? !platform.equals(ipDetails.platform) : ipDetails.platform != null) return false;
if (ptr != null ? !ptr.equals(ipDetails.ptr) : ipDetails.ptr != null) return false;
if (nameservers != null ? !nameservers.equals(ipDetails.nameservers) : ipDetails.nameservers != null)
return false;
return true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = datacenter != null ? datacenter.hashCode() : 0; return Objects.hashCode(datacenter, version, ptr, platform, address, netmask, broadcast, gateway, nameServers,
result = 31 * result + (ipversion != null ? ipversion.hashCode() : 0); serverId, cost, reserved);
result = 31 * result + (ptr != null ? ptr.hashCode() : 0); }
result = 31 * result + (platform != null ? platform.hashCode() : 0);
result = 31 * result + (address != null ? address.hashCode() : 0); @Override
result = 31 * result + (netmask != null ? netmask.hashCode() : 0); public boolean equals(Object obj) {
result = 31 * result + (broadcast != null ? broadcast.hashCode() : 0); if (this == obj) return true;
result = 31 * result + (gateway != null ? gateway.hashCode() : 0); if (obj == null || getClass() != obj.getClass()) return false;
return result; IpDetails that = IpDetails.class.cast(obj);
return Objects.equal(this.datacenter, that.datacenter)
&& Objects.equal(this.version, that.version)
&& Objects.equal(this.ptr, that.ptr)
&& Objects.equal(this.platform, that.platform)
&& Objects.equal(this.address, that.address)
&& Objects.equal(this.netmask, that.netmask)
&& Objects.equal(this.broadcast, that.broadcast)
&& Objects.equal(this.gateway, that.gateway)
&& Objects.equal(this.nameServers, that.nameServers)
&& Objects.equal(this.serverId, that.serverId)
&& Objects.equal(this.cost, that.cost)
&& Objects.equal(this.reserved, that.reserved);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("datacenter", datacenter).add("ipversion", version).add("ptr", ptr).add("platform", platform)
.add("address", address).add("netmask", netmask).add("broadcast", broadcast).add("gateway", gateway)
.add("nameServers", nameServers).add("serverId", serverId).add("cost", cost).add("reserved", reserved);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("IpDetails[datacenter=%s, ipversion=%s, platform=%s, PTR=%s, " + return string().toString();
"address=%s, netmask=%s, broadcast=%s, gateway=%s",
datacenter, ipversion, platform, ptr, address, netmask, broadcast, gateway);
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,9 +18,12 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.collect.Ordering; import com.google.common.base.Objects.ToStringHelper;
import com.google.gson.annotations.SerializedName;
/** /**
* Operating system template * Operating system template
@ -28,73 +31,106 @@ import com.google.gson.annotations.SerializedName;
* @author Adam Lowe * @author Adam Lowe
* @see <a href= "https://customer.glesys.com/api.php?a=doc#server_templates" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#server_templates" />
*/ */
public class OSTemplate implements Comparable<OSTemplate>{ public class OSTemplate {
public static Builder builder() { public static Builder<?> builder() {
return new Builder(); return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private String name; return new ConcreteBuilder().fromOSTemplate(this);
private int minDiskSize; }
private int minMemSize;
private String os;
private String platform;
public Builder name(String name) { public static abstract class Builder<T extends Builder<T>> {
this.name = name; protected abstract T self();
return this;
protected String name;
protected int minDiskSize;
protected int minMemSize;
protected String os;
protected String platform;
/**
* @see OSTemplate#getName()
*/
public T name(String name) {
this.name = checkNotNull(name, "name");
return self();
} }
public Builder minDiskSize(int minDiskSize) { /**
* @see OSTemplate#getMinDiskSize()
*/
public T minDiskSize(int minDiskSize) {
this.minDiskSize = minDiskSize; this.minDiskSize = minDiskSize;
return this; return self();
} }
public Builder minMemSize(int minMemSize) { /**
* @see OSTemplate#getMinMemSize()
*/
public T minMemSize(int minMemSize) {
this.minMemSize = minMemSize; this.minMemSize = minMemSize;
return this; return self();
} }
public Builder os(String os) { /**
this.os = os; * @see OSTemplate#getOs()
return this; */
public T os(String os) {
this.os = checkNotNull(os, "os");
return self();
} }
public Builder platform(String platform) { /**
this.platform = platform; * @see OSTemplate#getPlatform()
return this; */
public T platform(String platform) {
this.platform = checkNotNull(platform, "platform");
return self();
} }
public OSTemplate build() { public OSTemplate build() {
return new OSTemplate(name, minDiskSize, minMemSize, os, platform); return new OSTemplate(name, minDiskSize, minMemSize, os, platform);
} }
public Builder fromTemplate(OSTemplate in) { public T fromOSTemplate(OSTemplate in) {
return name(in.getName()).minDiskSize(in.getMinDiskSize()).minMemSize(in.getMinMemSize()).os(in.getOs()).platform(in.getPlatform()); return this.name(in.getName())
.minDiskSize(in.getMinDiskSize())
.minMemSize(in.getMinMemSize())
.os(in.getOs())
.platform(in.getPlatform());
} }
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
} }
private final String name; private final String name;
@SerializedName("minimumdisksize")
private final int minDiskSize; private final int minDiskSize;
@SerializedName("minimummemorysize")
private final int minMemSize; private final int minMemSize;
@SerializedName("operatingsystem")
private final String os; private final String os;
private final String platform; private final String platform;
public OSTemplate(String name, int minDiskSize, int minMemSize, String os, String platform) { @ConstructorProperties({
this.name = name; "name", "minimumdisksize", "minimummemorysize", "operatingsystem", "platform"
})
protected OSTemplate(String name, int minDiskSize, int minMemSize, String os, String platform) {
this.name = checkNotNull(name, "name");
this.minDiskSize = minDiskSize; this.minDiskSize = minDiskSize;
this.minMemSize = minMemSize; this.minMemSize = minMemSize;
this.os = os; this.os = checkNotNull(os, "os");
this.platform = platform; this.platform = checkNotNull(platform, "platform");
} }
/**
*/
public String getName() { public String getName() {
return name; return this.name;
} }
/** /**
@ -102,7 +138,7 @@ public class OSTemplate implements Comparable<OSTemplate>{
* @see org.jclouds.glesys.domain.AllowedArgumentsForCreateServer#getDiskSizesInGB() * @see org.jclouds.glesys.domain.AllowedArgumentsForCreateServer#getDiskSizesInGB()
*/ */
public int getMinDiskSize() { public int getMinDiskSize() {
return minDiskSize; return this.minDiskSize;
} }
/** /**
@ -110,35 +146,21 @@ public class OSTemplate implements Comparable<OSTemplate>{
* @see org.jclouds.glesys.domain.AllowedArgumentsForCreateServer#getMemorySizesInMB() * @see org.jclouds.glesys.domain.AllowedArgumentsForCreateServer#getMemorySizesInMB()
*/ */
public int getMinMemSize() { public int getMinMemSize() {
return minMemSize; return this.minMemSize;
} }
/** /**
* @return the name of the operating system type ex. "linux" * @return the name of the operating system type ex. "linux"
*/ */
public String getOs() { public String getOs() {
return os; return this.os;
} }
/** /**
* @return the name of the platform this template is available in, ex. "Xen" * @return the name of the platform this template is available in, ex. "Xen"
*/ */
public String getPlatform() { public String getPlatform() {
return platform; return this.platform;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof OSTemplate) {
final OSTemplate other = (OSTemplate) object;
return Objects.equal(name, other.name)
&& Objects.equal(platform, other.platform);
} else {
return false;
}
} }
@Override @Override
@ -147,13 +169,22 @@ public class OSTemplate implements Comparable<OSTemplate>{
} }
@Override @Override
public String toString() { public boolean equals(Object obj) {
return String.format("[name=%s, min_disk_size=%d, min_mem_size=%d, os=%s, platform=%s]", if (this == obj) return true;
name, minDiskSize, minMemSize, os, platform); if (obj == null || getClass() != obj.getClass()) return false;
OSTemplate that = OSTemplate.class.cast(obj);
return Objects.equal(this.name, that.name)
&& Objects.equal(this.platform, that.platform);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("name", name).add("minDiskSize", minDiskSize).add("minMemSize", minMemSize).add("os", os).add("platform", platform);
} }
@Override @Override
public int compareTo(OSTemplate arg0) { public String toString() {
return Ordering.usingToString().compare(this, arg0); return string().toString();
} }
} }

View File

@ -0,0 +1,149 @@
/*
* 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.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Detailed information on usage
*
* @author Adam Lowe
* @see ServerStatus
*/
public class ResourceStatus {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromResourceUsage(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected double usage;
protected double max;
protected String unit;
/**
* @see ResourceStatus#getUsage()
*/
public T usage(double usage) {
this.usage = usage;
return self();
}
/**
* @see ResourceStatus#getMax()
*/
public T max(double max) {
this.max = max;
return self();
}
/**
* @see ResourceStatus#getUnit()
*/
public T unit(String unit) {
this.unit = checkNotNull(unit, "unit");
return self();
}
public ResourceStatus build() {
return new ResourceStatus(usage, max, unit);
}
public T fromResourceUsage(ResourceStatus in) {
return this.usage(in.getUsage()).max(in.getMax()).unit(in.getUnit());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final double usage;
private final double max;
private final String unit;
@ConstructorProperties({
"usage", "max", "unit"
})
protected ResourceStatus(double usage, double max, String unit) {
this.usage = usage;
this.max = max;
this.unit = checkNotNull(unit, "unit");
}
/**
* @return the usage in #unit
*/
public double getUsage() {
return this.usage;
}
/**
* @return the max usage in #unit
*/
public double getMax() {
return this.max;
}
/**
* @return the unit used
*/
public String getUnit() {
return this.unit;
}
@Override
public int hashCode() {
return Objects.hashCode(usage, max, unit);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ResourceStatus that = ResourceStatus.class.cast(obj);
return Objects.equal(this.usage, that.usage)
&& Objects.equal(this.max, that.max)
&& Objects.equal(this.unit, that.unit);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("usage", usage).add("max", max).add("unit", unit);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,103 +18,120 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Set;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableSet;
/** /**
* Detailed information on usage * Detailed information on usage
* *
* @author Adam Lowe * @author Adam Lowe
* @see ServerStatus * @see ResourceUsageInfo
* @see ResourceUsageValue
*/ */
public class ResourceUsage { public class ResourceUsage {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private double usage; return new ConcreteBuilder().fromResourceUsages(this);
private double max; }
private String unit;
public Builder usage(double usage) { public static abstract class Builder<T extends Builder<T>> {
this.usage = usage; protected abstract T self();
return this;
protected ResourceUsageInfo info;
protected Set<ResourceUsageValue> values = ImmutableSet.of();
/**
* @see ResourceUsage#getInfo()
*/
public T info(ResourceUsageInfo info) {
this.info = checkNotNull(info, "info");
return self();
} }
public Builder max(double max) { /**
this.max = max; * @see ResourceUsage#getValues()
return this; */
public T values(Set<ResourceUsageValue> values) {
this.values = ImmutableSet.copyOf(checkNotNull(values, "values"));
return self();
} }
public Builder unit(String unit) { /**
this.unit = unit; * @see ResourceUsage#getValues()
return this; */
public T values(ResourceUsageValue... in) {
return values(ImmutableSet.copyOf(in));
} }
public ResourceUsage build() { public ResourceUsage build() {
return new ResourceUsage(usage, max, unit); return new ResourceUsage(info, values);
} }
public Builder fromCpu(ResourceUsage in) { public T fromResourceUsages(ResourceUsage in) {
return usage(in.getUsage()).max(in.getMax()).unit(in.getUnit()); return this
.info(in.getInfo())
.values(in.getValues());
} }
} }
private final double usage; private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
private final double max; @Override
private final String unit; protected ConcreteBuilder self() {
return this;
public ResourceUsage(double usage, double max, String unit) {
this.usage = usage;
this.max = max;
this.unit = unit;
}
/**
* @return the usage in #unit
*/
public double getUsage() {
return usage;
}
/**
* @return the max usage in #unit
*/
public double getMax() {
return max;
}
/**
* @return the unit used
*/
public String getUnit() {
return unit;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof ResourceUsage) {
ResourceUsage other = (ResourceUsage) object;
return Objects.equal(usage, other.usage)
&& Objects.equal(max, other.max)
&& Objects.equal(unit, other.unit);
} else {
return false;
} }
} }
private final ResourceUsageInfo info;
private final Set<ResourceUsageValue> values;
@ConstructorProperties({
"info", "values"
})
protected ResourceUsage(ResourceUsageInfo info, Set<ResourceUsageValue> values) {
this.info = checkNotNull(info, "info");
this.values = ImmutableSet.copyOf(checkNotNull(values, "values"));
}
public ResourceUsageInfo getInfo() {
return this.info;
}
public Set<ResourceUsageValue> getValues() {
return this.values;
}
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(usage, max, unit); return Objects.hashCode(info, values);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ResourceUsage that = ResourceUsage.class.cast(obj);
return Objects.equal(this.info, that.info)
&& Objects.equal(this.values, that.values);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("info", info).add("values", values);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("[usage=%f, max=%f, unit=%s]", return string().toString();
usage, max, unit);
} }
} }

View File

@ -0,0 +1,144 @@
/*
* 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.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Detailed information on usage
*
* @author Adam Lowe
* @see ServerStatus
*/
public class ResourceUsageInfo {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromResourceUsageInfo(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String resource;
protected String resolution;
protected String unit;
/**
* @see ResourceUsageInfo#getResource()
*/
public T resource(String resource) {
this.resource = checkNotNull(resource, "resource");
return self();
}
/**
* @see ResourceUsageInfo#getResolution()
*/
public T resolution(String resolution) {
this.resolution = checkNotNull(resolution, "resolution");
return self();
}
/**
* @see ResourceUsageInfo#getUnit()
*/
public T unit(String unit) {
this.unit = checkNotNull(unit, "unit");
return self();
}
public ResourceUsageInfo build() {
return new ResourceUsageInfo(resource, resolution, unit);
}
public T fromResourceUsageInfo(ResourceUsageInfo in) {
return this
.resource(in.getResource())
.resolution(in.getResolution())
.unit(in.getUnit());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String resource;
private final String resolution;
private final String unit;
@ConstructorProperties({
"type", "resolution", "unit"
})
protected ResourceUsageInfo(String resource, String resolution, String unit) {
this.resource = checkNotNull(resource, "resource");
this.resolution = checkNotNull(resolution, "resolution");
this.unit = checkNotNull(unit, "unit");
}
public String getResource() {
return this.resource;
}
public String getResolution() {
return this.resolution;
}
public String getUnit() {
return this.unit;
}
@Override
public int hashCode() {
return Objects.hashCode(resource, resolution, unit);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ResourceUsageInfo that = ResourceUsageInfo.class.cast(obj);
return Objects.equal(this.resource, that.resource)
&& Objects.equal(this.resolution, that.resolution)
&& Objects.equal(this.unit, that.unit);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("resource", resource).add("resolution", resolution).add("unit", unit);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -0,0 +1,128 @@
/*
* 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.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Date;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Detailed information on usage
*
* @author Adam Lowe
* @see org.jclouds.glesys.domain.ServerStatus
*/
public class ResourceUsageValue {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromResourceUsage(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected double value;
protected Date timestamp;
/**
* @see ResourceUsageValue#getValue()
*/
public T value(double value) {
this.value = value;
return self();
}
/**
* @see ResourceUsageValue#getTimestamp()
*/
public T timestamp(Date timestamp) {
this.timestamp = checkNotNull(timestamp, "timestamp");
return self();
}
public ResourceUsageValue build() {
return new ResourceUsageValue(value, timestamp);
}
public T fromResourceUsage(ResourceUsageValue in) {
return this
.value(in.getValue())
.timestamp(in.getTimestamp());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final double value;
private final Date timestamp;
@ConstructorProperties({
"value", "timestamp"
})
protected ResourceUsageValue(double value, Date timestamp) {
this.value = value;
this.timestamp = checkNotNull(timestamp, "timestamp");
}
public double getValue() {
return this.value;
}
public Date getTimestamp() {
return this.timestamp;
}
@Override
public int hashCode() {
return Objects.hashCode(value, timestamp);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ResourceUsageValue that = ResourceUsageValue.class.cast(obj);
return Objects.equal(this.value, that.value)
&& Objects.equal(this.timestamp, that.timestamp);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("value", value).add("timestamp", timestamp);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -20,9 +20,11 @@ package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName; import com.google.common.base.Objects.ToStringHelper;
/** /**
* Listing of a server. * Listing of a server.
@ -30,8 +32,10 @@ import com.google.gson.annotations.SerializedName;
* @author Adrian Cole * @author Adrian Cole
* @see <a href= "https://customer.glesys.com/api.php?a=doc#server_list" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#server_list" />
*/ */
public class Server implements Comparable<Server> { public class Server {
/**
*/
public static enum State { public static enum State {
RUNNING, LOCKED, STOPPED, UNRECOGNIZED; RUNNING, LOCKED, STOPPED, UNRECOGNIZED;
@ -54,52 +58,79 @@ public class Server implements Comparable<Server> {
} }
} }
public static Builder builder() { public static Builder<?> builder() {
return new Builder(); return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
return new ConcreteBuilder().fromServer(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String id; protected String id;
protected String hostname; protected String hostname;
protected String datacenter; protected String datacenter;
protected String platform; protected String platform;
public Builder id(String id) { /**
this.id = id; * @see Server#getId()
return this; */
public T id(String id) {
this.id = checkNotNull(id, "id");
return self();
} }
public Builder hostname(String hostname) { /**
this.hostname = hostname; * @see Server#getHostname()
return this; */
public T hostname(String hostname) {
this.hostname = checkNotNull(hostname, "hostname");
return self();
} }
public Builder datacenter(String datacenter) { /**
this.datacenter = datacenter; * @see Server#getDatacenter()
return this; */
public T datacenter(String datacenter) {
this.datacenter = checkNotNull(datacenter, "datacenter");
return self();
} }
public Builder platform(String platform) { /**
this.platform = platform; * @see Server#getPlatform()
return this; */
public T platform(String platform) {
this.platform = checkNotNull(platform, "platform");
return self();
} }
public Server build() { public Server build() {
return new Server(id, hostname, datacenter, platform); return new Server(id, hostname, datacenter, platform);
} }
public Builder fromServer(Server in) { public T fromServer(Server in) {
return datacenter(in.getDatacenter()).platform(in.getPlatform()).hostname(in.getHostname()).id(in.getId()); return this.id(in.getId()).hostname(in.getHostname()).datacenter(in.getDatacenter()).platform(in.getPlatform());
} }
} }
@SerializedName("serverid") private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
protected final String id; @Override
protected final String hostname; protected ConcreteBuilder self() {
protected final String datacenter; return this;
protected final String platform; }
}
public Server(String id, String hostname, String datacenter, String platform) { private final String id;
private final String hostname;
private final String datacenter;
private final String platform;
@ConstructorProperties({
"serverid", "hostname", "datacenter", "platform"
})
protected Server(String id, String hostname, String datacenter, String platform) {
this.id = checkNotNull(id, "id"); this.id = checkNotNull(id, "id");
this.hostname = checkNotNull(hostname, "hostname"); this.hostname = checkNotNull(hostname, "hostname");
this.datacenter = checkNotNull(datacenter, "datacenter"); this.datacenter = checkNotNull(datacenter, "datacenter");
@ -110,45 +141,28 @@ public class Server implements Comparable<Server> {
* @return the generated id of the server * @return the generated id of the server
*/ */
public String getId() { public String getId() {
return id; return this.id;
} }
/** /**
* @return the hostname of the server * @return the hostname of the server
*/ */
public String getHostname() { public String getHostname() {
return hostname; return this.hostname;
} }
/** /**
* @return platform running the server (ex. {@code OpenVZ}) * @return platform running the server (ex. {@code OpenVZ})
*/ */
public String getPlatform() { public String getDatacenter() {
return platform; return this.datacenter;
} }
/** /**
* @return the datacenter the server exists in (ex. {@code Falkenberg}) * @return the datacenter the server exists in (ex. {@code Falkenberg})
*/ */
public String getDatacenter() { public String getPlatform() {
return datacenter; return this.platform;
}
@Override
public int compareTo(Server other) {
return id.compareTo(other.getId());
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Server) {
return Objects.equal(id, ((Server) object).id);
} else {
return false;
}
} }
@Override @Override
@ -156,9 +170,22 @@ public class Server implements Comparable<Server> {
return Objects.hashCode(id); return Objects.hashCode(id);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Server that = Server.class.cast(obj);
return Objects.equal(this.id, that.id);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("id", id).add("hostname", hostname).add("datacenter", datacenter)
.add("platform", platform);
}
@Override @Override
public String toString() { public String toString() {
return String.format("[id=%s, hostname=%s, datacenter=%s, platform=%s]", id, hostname, datacenter, platform); return string().toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -20,10 +20,13 @@ package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Set; import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.gson.annotations.SerializedName;
/** /**
* Detailed information about a server such as cpuCores, hardware configuration * Detailed information about a server such as cpuCores, hardware configuration
@ -33,208 +36,223 @@ import com.google.gson.annotations.SerializedName;
* @see <a href= "https://customer.glesys.com/api.php?a=doc#server_details" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#server_details" />
*/ */
public class ServerDetails extends Server { public class ServerDetails extends Server {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder extends Server.Builder { public Builder<?> toBuilder() {
private Server.State state; return new ConcreteBuilder().fromServerDetails(this);
private String description; }
private String templateName;
private int cpuCores;
private int memorySizeMB;
private int diskSizeGB;
private int transferGB;
private Cost cost;
private Set<Ip> ips = ImmutableSet.of();
public Builder state(Server.State state) { public static abstract class Builder<T extends Builder<T>> extends Server.Builder<T> {
this.state = state; protected Server.State state;
return this; protected String description;
protected String templateName;
protected int cpuCores;
protected int memorySizeMB;
protected int diskSizeGB;
protected int transferGB;
protected Cost cost;
protected Set<Ip> ips = ImmutableSet.of();
/**
* @see ServerDetails#getState()
*/
public T state(Server.State state) {
this.state = checkNotNull(state, "state");
return self();
} }
public Builder description(String description) { /**
this.description = description; * @see ServerDetails#getDescription()
return this; */
public T description(String description) {
this.description = checkNotNull(description, "description");
return self();
} }
public Builder templateName(String templateName) { /**
this.templateName = templateName; * @see ServerDetails#getTemplateName()
return this; */
public T templateName(String templateName) {
this.templateName = checkNotNull(templateName, "templateName");
return self();
} }
public Builder cpuCores(int cpuCores) { /**
* @see ServerDetails#getCpuCores()
*/
public T cpuCores(int cpuCores) {
this.cpuCores = cpuCores; this.cpuCores = cpuCores;
return this; return self();
} }
public Builder memorySizeMB(int memorySizeMB) { /**
* @see ServerDetails#getMemorySizeMB()
*/
public T memorySizeMB(int memorySizeMB) {
this.memorySizeMB = memorySizeMB; this.memorySizeMB = memorySizeMB;
return this; return self();
} }
public Builder diskSizeGB(int diskSizeGB) { /**
* @see ServerDetails#getDiskSizeGB()
*/
public T diskSizeGB(int diskSizeGB) {
this.diskSizeGB = diskSizeGB; this.diskSizeGB = diskSizeGB;
return this; return self();
} }
public Builder transferGB(int transferGB) { /**
* @see ServerDetails#getTransferGB()
*/
public T transferGB(int transferGB) {
this.transferGB = transferGB; this.transferGB = transferGB;
return this; return self();
} }
public Builder cost(Cost cost) { /**
this.cost = cost; * @see ServerDetails#getCost()
return this; */
public T cost(Cost cost) {
this.cost = checkNotNull(cost, "cost");
return self();
} }
public Builder ips(Ip... ips) { /**
return ips(ImmutableSet.copyOf(ips)); * @see ServerDetails#getIps()
*/
public T ips(Set<Ip> ips) {
this.ips = ImmutableSet.copyOf(checkNotNull(ips, "ips"));
return self();
} }
public Builder ips(Iterable<Ip> ips) { public T ips(Ip... in) {
this.ips = ImmutableSet.copyOf(ips); return ips(ImmutableSet.copyOf(in));
return this;
} }
public ServerDetails build() { public ServerDetails build() {
return new ServerDetails(id, hostname, datacenter, platform, state, templateName, description, cpuCores, return new ServerDetails(id, hostname, datacenter, platform, state, description, templateName, cpuCores, memorySizeMB, diskSizeGB, transferGB, cost, ips);
memorySizeMB, diskSizeGB, transferGB, cost, ips);
} }
public Builder fromServerDetails(ServerDetails in) { public T fromServerDetails(ServerDetails in) {
return fromServer(in).templateName(in.getTemplateName()).state(in.getState()).memorySizeMB(in.getMemorySizeMB()) return super.fromServer(in)
.diskSizeGB(in.getDiskSizeGB()).cpuCores(in.getCpuCores()).cost(in.getCost()) .state(in.getState())
.transferGB(in.getTransferGB()).description(in.getDescription()).ips(in.getIps()); .description(in.getDescription())
.templateName(in.getTemplateName())
.cpuCores(in.getCpuCores())
.memorySizeMB(in.getMemorySizeMB())
.diskSizeGB(in.getDiskSizeGB())
.transferGB(in.getTransferGB())
.cost(in.getCost())
.ips(in.getIps());
} }
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override @Override
public Builder id(String id) { protected ConcreteBuilder self() {
return Builder.class.cast(super.id(id)); return this;
}
@Override
public Builder hostname(String hostname) {
return Builder.class.cast(super.hostname(hostname));
}
@Override
public Builder datacenter(String datacenter) {
return Builder.class.cast(super.datacenter(datacenter));
}
@Override
public Builder platform(String platform) {
return Builder.class.cast(super.platform(platform));
}
@Override
public Builder fromServer(Server in) {
return Builder.class.cast(super.fromServer(in));
} }
} }
private final Server.State state; private final Server.State state;
private final String description; private final String description;
@SerializedName("templatename")
private final String templateName; private final String templateName;
@SerializedName("cpucores")
private final int cpuCores; private final int cpuCores;
@SerializedName("memorysize")
private final int memorySizeMB; private final int memorySizeMB;
@SerializedName("disksize")
private final int diskSizeGB; private final int diskSizeGB;
@SerializedName("transfer")
private final int transferGB; private final int transferGB;
private final Cost cost; private final Cost cost;
@SerializedName("iplist")
private final Set<Ip> ips; private final Set<Ip> ips;
public ServerDetails(String id, String hostname, String datacenter, String platform, Server.State state, @ConstructorProperties({
String templateName, String description, int cpuCores, int memorySizeMB, int diskSizeGB, int transferGB, "serverid", "hostname", "datacenter", "platform", "state", "description", "templatename", "cpucores",
Cost cost, Set<Ip> ips) { "memorysize", "disksize", "transfer", "cost", "iplist"
})
protected ServerDetails(String id, String hostname, String datacenter, String platform, @Nullable Server.State state,
@Nullable String description, String templateName, int cpuCores, int memorySizeMB,
int diskSizeGB, int transferGB, Cost cost, @Nullable Set<Ip> ips) {
super(id, hostname, datacenter, platform); super(id, hostname, datacenter, platform);
this.state = state; this.state = state;
this.templateName = checkNotNull(templateName, "template");
this.description = description; this.description = description;
this.templateName = checkNotNull(templateName, "templateName");
this.cpuCores = cpuCores; this.cpuCores = cpuCores;
this.memorySizeMB = memorySizeMB; this.memorySizeMB = memorySizeMB;
this.diskSizeGB = diskSizeGB; this.diskSizeGB = diskSizeGB;
this.transferGB = transferGB; this.transferGB = transferGB;
this.cost = checkNotNull(cost, "cost"); this.cost = checkNotNull(cost, "cost");
this.ips = ImmutableSet.<Ip> copyOf(ips); this.ips = ips == null ? ImmutableSet.<Ip>of() : ImmutableSet.copyOf(checkNotNull(ips, "ips"));
} }
/** /**
* @return the state of the server (e.g. "running") * @return the state of the server (e.g. "running")
*/ */
public Server.State getState() { public Server.State getState() {
return state; return this.state;
} }
/** /**
* @return the user-specified description of the server * @return the user-specified description of the server
*/ */
public String getDescription() { public String getDescription() {
return description; return this.description;
}
/**
* @return number of cores on the server
*/
public int getCpuCores() {
return cpuCores;
}
/**
* @return the disk of the server in GB
*/
public int getDiskSizeGB() {
return diskSizeGB;
}
/**
* @return the memory of the server in MB
*/
public int getMemorySizeMB() {
return memorySizeMB;
}
/**
* @return the transfer of the server
*/
public int getTransferGB() {
return transferGB;
}
/**
* @return details of the cost of the server
*/
public Cost getCost() {
return cost;
}
/**
* @return the ip addresses assigned to the server
*/
public Set<Ip> getIps() {
return ips;
} }
/** /**
* @return the name of the template used to create the server * @return the name of the template used to create the server
*/ */
public String getTemplateName() { public String getTemplateName() {
return templateName; return this.templateName;
} }
@Override /**
public String toString() { * @return number of cores on the server
return String */
.format( public int getCpuCores() {
"[id=%s, hostname=%s, datacenter=%s, platform=%s, templateName=%s, state=%s, description=%s, cpuCores=%d, memorySizeMB=%d, diskSizeGB=%d, transferGB=%d, cost=%s, ips=%s]", return this.cpuCores;
id, hostname, datacenter, platform, templateName, state, description, cpuCores, memorySizeMB, }
diskSizeGB, transferGB, cost, ips);
/**
* @return the memory of the server in MB
*/
public int getMemorySizeMB() {
return this.memorySizeMB;
}
/**
* @return the disk of the server in GB
*/
public int getDiskSizeGB() {
return this.diskSizeGB;
}
/**
* @return the transfer of the server
*/
public int getTransferGB() {
return this.transferGB;
}
/**
* @return details of the cost of the server
*/
public Cost getCost() {
return this.cost;
}
/**
* @return the ip addresses assigned to the server
*/
public Set<Ip> getIps() {
return this.ips;
}
protected ToStringHelper string() {
return super.string().add("state", state).add("description", description).add("templateName", templateName)
.add("cpuCores", cpuCores).add("memorySizeMB", memorySizeMB).add("diskSizeGB", diskSizeGB)
.add("transferGB", transferGB).add("cost", cost).add("ips", ips);
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,7 +18,10 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* Detailed information about an OpenVZ server's limits * Detailed information about an OpenVZ server's limits
@ -27,45 +30,82 @@ import com.google.common.base.Objects;
* @see <a href= "https://customer.glesys.com/api.php?a=doc#server_limits" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#server_limits" />
*/ */
public class ServerLimit { public class ServerLimit {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private int held; return new ConcreteBuilder().fromServerLimit(this);
private int maxHeld; }
private int barrier;
private int limit;
private int failCount;
public Builder held(int held) { public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected long held;
protected long maxHeld;
protected long barrier;
protected long limit;
protected long failCount;
/**
* @see ServerLimit#getHeld()
*/
public T held(long held) {
this.held = held; this.held = held;
return this; return self();
} }
public Builder maxHeld(int maxHeld) { /**
* @see ServerLimit#getMaxHeld()
*/
public T maxHeld(long maxHeld) {
this.maxHeld = maxHeld; this.maxHeld = maxHeld;
return this; return self();
} }
public Builder barrier(int barrier) { /**
* @see ServerLimit#getBarrier()
*/
public T barrier(long barrier) {
this.barrier = barrier; this.barrier = barrier;
return this; return self();
} }
public Builder limit(int limit) { /**
* @see ServerLimit#getLimit()
*/
public T limit(long limit) {
this.limit = limit; this.limit = limit;
return this; return self();
} }
public Builder failCount(int failCount) { /**
* @see ServerLimit#getFailCount()
*/
public T failCount(long failCount) {
this.failCount = failCount; this.failCount = failCount;
return this; return self();
} }
public ServerLimit build() { public ServerLimit build() {
return new ServerLimit(held, maxHeld, barrier, limit, failCount); return new ServerLimit(held, maxHeld, barrier, limit, failCount);
} }
public T fromServerLimit(ServerLimit in) {
return this.held(in.getHeld())
.maxHeld(in.getMaxHeld())
.barrier(in.getBarrier())
.limit(in.getLimit())
.failCount(in.getFailCount());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
} }
private final long held; private final long held;
@ -74,7 +114,10 @@ public class ServerLimit {
private final long limit; private final long limit;
private final long failCount; private final long failCount;
public ServerLimit(long held, long maxHeld, long barrier, long limit, long failCount) { @ConstructorProperties({
"held", "maxHeld", "barrier", "limit", "failCount"
})
protected ServerLimit(long held, long maxHeld, long barrier, long limit, long failCount) {
this.held = held; this.held = held;
this.maxHeld = maxHeld; this.maxHeld = maxHeld;
this.barrier = barrier; this.barrier = barrier;
@ -83,40 +126,23 @@ public class ServerLimit {
} }
public long getHeld() { public long getHeld() {
return held; return this.held;
} }
public long getMaxHeld() { public long getMaxHeld() {
return maxHeld; return this.maxHeld;
} }
public long getBarrier() { public long getBarrier() {
return barrier; return this.barrier;
} }
public long getLimit() { public long getLimit() {
return limit; return this.limit;
} }
public long getFailCount() { public long getFailCount() {
return failCount; return this.failCount;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof ServerLimit) {
final ServerLimit other = (ServerLimit) object;
return Objects.equal(held, other.held)
&& Objects.equal(maxHeld, other.maxHeld)
&& Objects.equal(barrier, other.barrier)
&& Objects.equal(limit, other.limit)
&& Objects.equal(failCount, other.failCount);
} else {
return false;
}
} }
@Override @Override
@ -125,7 +151,25 @@ public class ServerLimit {
} }
@Override @Override
public String toString() { public boolean equals(Object obj) {
return String.format("[held=%d, maxHeld=%d, barrier=%d, limit=%d, failCount=%d]", held, maxHeld, barrier, limit, failCount); if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ServerLimit that = ServerLimit.class.cast(obj);
return Objects.equal(this.held, that.held)
&& Objects.equal(this.maxHeld, that.maxHeld)
&& Objects.equal(this.barrier, that.barrier)
&& Objects.equal(this.limit, that.limit)
&& Objects.equal(this.failCount, that.failCount);
} }
protected ToStringHelper string() {
return Objects.toStringHelper("").add("held", held).add("maxHeld", maxHeld).add("barrier", barrier)
.add("limit", limit).add("failCount", failCount);
}
@Override
public String toString() {
return string().toString();
}
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,92 +18,129 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Objects.equal;
import static com.google.common.base.Objects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* * Class ServerSpec
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class ServerSpec { public class ServerSpec {
public static Builder builder() { public static Builder<?> builder() {
return new Builder(); return new ConcreteBuilder();
} }
public Builder toBuilder() { public Builder<?> toBuilder() {
return Builder.fromServerSpecification(this); return new ConcreteBuilder().fromServerSpec(this);
} }
public static class Builder { public static abstract class Builder<T extends Builder<T>> {
protected String datacenter; protected abstract T self();
protected String platform; protected String platform;
protected String templateName; protected String datacenter;
protected int diskSizeGB;
protected int memorySizeMB; protected int memorySizeMB;
protected int diskSizeGB;
protected String templateName;
protected int cpuCores; protected int cpuCores;
protected int transferGB; protected int transferGB;
public Builder datacenter(String datacenter) { /**
this.datacenter = datacenter; * @see ServerSpec#getPlatform()
return this; */
public T platform(String platform) {
this.platform = checkNotNull(platform, "platform");
return self();
} }
public Builder platform(String platform) { /**
this.platform = platform; * @see ServerSpec#getDatacenter()
return this; */
public T datacenter(String datacenter) {
this.datacenter = checkNotNull(datacenter, "datacenter");
return self();
} }
public Builder templateName(String templateName) { /**
this.templateName = templateName; * @see ServerSpec#getMemorySizeMB()
return this; */
} public T memorySizeMB(int memorySizeMB) {
public Builder diskSizeGB(int diskSizeGB) {
this.diskSizeGB = diskSizeGB;
return this;
}
public Builder memorySizeMB(int memorySizeMB) {
this.memorySizeMB = memorySizeMB; this.memorySizeMB = memorySizeMB;
return this; return self();
} }
public Builder cpuCores(int cpuCores) { /**
* @see ServerSpec#getDiskSizeGB()
*/
public T diskSizeGB(int diskSizeGB) {
this.diskSizeGB = diskSizeGB;
return self();
}
/**
* @see ServerSpec#getTemplateName()
*/
public T templateName(String templateName) {
this.templateName = checkNotNull(templateName, "templateName");
return self();
}
/**
* @see ServerSpec#getCpuCores()
*/
public T cpuCores(int cpuCores) {
this.cpuCores = cpuCores; this.cpuCores = cpuCores;
return this; return self();
} }
public Builder transferGB(int transferGB) { /**
* @see ServerSpec#getTransferGB()
*/
public T transferGB(int transferGB) {
this.transferGB = transferGB; this.transferGB = transferGB;
return this; return self();
} }
public ServerSpec build() { public ServerSpec build() {
return new ServerSpec(platform, datacenter, memorySizeMB, diskSizeGB, templateName, cpuCores, transferGB); return new ServerSpec(platform, datacenter, memorySizeMB, diskSizeGB, templateName, cpuCores, transferGB);
} }
public static Builder fromServerSpecification(ServerSpec in) { public T fromServerSpec(ServerSpec in) {
return new Builder().platform(in.getPlatform()).datacenter(in.getDatacenter()) return this.platform(in.getPlatform())
.memorySizeMB(in.getMemorySizeMB()).diskSizeGB(in.getDiskSizeGB()).templateName(in.getTemplateName()) .datacenter(in.getDatacenter())
.cpuCores(in.getCpuCores()).transferGB(in.getTransferGB()); .memorySizeMB(in.getMemorySizeMB())
.diskSizeGB(in.getDiskSizeGB())
.templateName(in.getTemplateName())
.cpuCores(in.getCpuCores())
.transferGB(in.getTransferGB());
} }
} }
protected final String platform; private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
protected final String datacenter; @Override
protected final int memorySizeMB; protected ConcreteBuilder self() {
protected final int diskSizeGB; return this;
protected final String templateName; }
protected final int cpuCores; }
protected final int transferGB;
protected ServerSpec(String platform, String datacenter, int memorySizeMB, int diskSizeGB, String templateName, private final String platform;
int cpuCores, int transferGB) { private final String datacenter;
private final int memorySizeMB;
private final int diskSizeGB;
private final String templateName;
private final int cpuCores;
private final int transferGB;
@ConstructorProperties({
"platform", "datacenter", "memorySizeMB", "diskSizeGB", "templateName", "cpuCores", "transferGB"
})
protected ServerSpec(String platform, String datacenter, int memorySizeMB, int diskSizeGB, String templateName, int cpuCores, int transferGB) {
this.platform = checkNotNull(platform, "platform"); this.platform = checkNotNull(platform, "platform");
this.datacenter = checkNotNull(datacenter, "datacenter"); this.datacenter = checkNotNull(datacenter, "datacenter");
this.memorySizeMB = memorySizeMB; this.memorySizeMB = memorySizeMB;
@ -116,66 +153,50 @@ public class ServerSpec {
/** /**
* @return the data center to create the new server in * @return the data center to create the new server in
*/ */
public String getDatacenter() { public String getPlatform() {
return datacenter; return this.platform;
} }
/** /**
* @return the platform to use (i.e. "Xen" or "OpenVZ") * @return the platform to use (i.e. "Xen" or "OpenVZ")
*/ */
public String getPlatform() { public String getDatacenter() {
return platform; return this.datacenter;
} }
/** /**
* @return the os template to use to create the new server * @return the os template to use to create the new server
*/ */
public String getTemplateName() { public int getMemorySizeMB() {
return templateName; return this.memorySizeMB;
} }
/** /**
* @return the amount of disk space, in GB, to allocate * @return the amount of disk space, in GB, to allocate
*/ */
public int getDiskSizeGB() { public int getDiskSizeGB() {
return diskSizeGB; return this.diskSizeGB;
} }
/** /**
* @return the memory, in MB, to allocate * @return the memory, in MB, to allocate
*/ */
public int getMemorySizeMB() { public String getTemplateName() {
return memorySizeMB; return this.templateName;
} }
/** /**
* @return the number of CPU cores to allocate * @return the number of CPU cores to allocate
*/ */
public int getCpuCores() { public int getCpuCores() {
return cpuCores; return this.cpuCores;
} }
/** /**
* @return bandwidth of in GB * @return bandwidth of in GB
*/ */
public int getTransferGB() { public int getTransferGB() {
return transferGB; return this.transferGB;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof ServerSpec) {
final ServerSpec that = ServerSpec.class.cast(object);
return equal(platform, that.platform) && equal(datacenter, that.datacenter)
&& equal(memorySizeMB, that.memorySizeMB) && equal(diskSizeGB, that.diskSizeGB)
&& equal(templateName, that.templateName) && equal(cpuCores, that.cpuCores)
&& equal(transferGB, that.transferGB);
} else {
return false;
}
} }
@Override @Override
@ -183,10 +204,28 @@ public class ServerSpec {
return Objects.hashCode(platform, datacenter, memorySizeMB, diskSizeGB, templateName, cpuCores, transferGB); return Objects.hashCode(platform, datacenter, memorySizeMB, diskSizeGB, templateName, cpuCores, transferGB);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ServerSpec that = ServerSpec.class.cast(obj);
return Objects.equal(this.platform, that.platform)
&& Objects.equal(this.datacenter, that.datacenter)
&& Objects.equal(this.memorySizeMB, that.memorySizeMB)
&& Objects.equal(this.diskSizeGB, that.diskSizeGB)
&& Objects.equal(this.templateName, that.templateName)
&& Objects.equal(this.cpuCores, that.cpuCores)
&& Objects.equal(this.transferGB, that.transferGB);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("platform", platform).add("datacenter", datacenter)
.add("memorySizeMB", memorySizeMB).add("diskSizeGB", diskSizeGB).add("templateName", templateName)
.add("cpuCores", cpuCores).add("transferGB", transferGB);
}
@Override @Override
public String toString() { public String toString() {
return toStringHelper("").add("platform", platform).add("datacenter", datacenter) return string().toString();
.add("templateName", templateName).add("cpuCores", cpuCores).add("memorySizeMB", memorySizeMB)
.add("diskSizeGB", diskSizeGB).add("transferGB", transferGB).toString();
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,7 +18,14 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* Detailed information server status including hardware usage (cpu, memory and disk), bandwidth and up-time. * Detailed information server status including hardware usage (cpu, memory and disk), bandwidth and up-time.
@ -26,62 +33,93 @@ import com.google.common.base.Objects;
* @author Adam Lowe * @author Adam Lowe
* @see <a href= "https://customer.glesys.com/api.php?a=doc#server_status" /> * @see <a href= "https://customer.glesys.com/api.php?a=doc#server_status" />
*/ */
public class ServerStatus { public class ServerStatus {
public static Builder builder() { public static Builder<?> builder() {
return new Builder(); return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private Server.State state; return new ConcreteBuilder().fromServerStatus(this);
private ResourceUsage cpu; }
private ResourceUsage memory;
private ResourceUsage disk;
private ServerUptime uptime;
public Builder state(Server.State state) { public static abstract class Builder<T extends Builder<T>> {
this.state = state; protected abstract T self();
return this;
protected Server.State state;
protected ResourceStatus cpu;
protected ResourceStatus memory;
protected ResourceStatus disk;
protected ServerUptime uptime;
/**
* @see ServerStatus#getState()
*/
public T state(Server.State state) {
this.state = checkNotNull(state, "state");
return self();
} }
public Builder cpu(ResourceUsage cpu) { /**
this.cpu = cpu; * @see ServerStatus#getCpu()
return this; */
public T cpu(ResourceStatus cpu) {
this.cpu = checkNotNull(cpu, "cpu");
return self();
} }
public Builder memory(ResourceUsage memory) { /**
this.memory = memory; * @see ServerStatus#getMemory()
return this; */
public T memory(ResourceStatus memory) {
this.memory = checkNotNull(memory, "memory");
return self();
} }
public Builder disk(ResourceUsage disk) { /**
this.disk = disk; * @see ServerStatus#getDisk()
return this; */
public T disk(ResourceStatus disk) {
this.disk = checkNotNull(disk, "disk");
return self();
} }
public Builder uptime(ServerUptime uptime) { /**
this.uptime = uptime; * @see ServerStatus#getUptime()
return this; */
public T uptime(ServerUptime uptime) {
this.uptime = checkNotNull(uptime, "uptime");
return self();
} }
public ServerStatus build() { public ServerStatus build() {
return new ServerStatus(state, cpu, memory, disk, uptime); return new ServerStatus(state, cpu, memory, disk, uptime);
} }
public Builder fromServerStatus(ServerStatus in) { public T fromServerStatus(ServerStatus in) {
return state(in.getState()).cpu(in.getCpu()).memory(in.getMemory()).disk(in.getDisk()).uptime(in.getUptime()); return this.state(in.getState()).cpu(in.getCpu()).memory(in.getMemory()).disk(in.getDisk()).uptime(in.getUptime());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
private final Server.State state; private final Server.State state;
private final ResourceUsage cpu; private final ResourceStatus cpu;
private final ResourceUsage memory; private final ResourceStatus memory;
private final ResourceUsage disk; private final ResourceStatus disk;
private final ServerUptime uptime; private final ServerUptime uptime;
public ServerStatus(Server.State state, ResourceUsage cpu, ResourceUsage memory, ResourceUsage disk, ServerUptime uptime) { @ConstructorProperties({
this.state = state; "state", "cpu", "memory", "disk", "uptime"
})
protected ServerStatus(Server.State state, @Nullable ResourceStatus cpu, @Nullable ResourceStatus memory,
@Nullable ResourceStatus disk, @Nullable ServerUptime uptime) {
this.state = checkNotNull(state, "state");
this.cpu = cpu; this.cpu = cpu;
this.memory = memory; this.memory = memory;
this.disk = disk; this.disk = disk;
@ -91,53 +129,41 @@ public class ServerStatus {
/** /**
* @return the state of the server (e.g. "running") * @return the state of the server (e.g. "running")
*/ */
@Nullable
public Server.State getState() { public Server.State getState() {
return state; return this.state;
} }
/** /**
* @return CPU usage information * @return CPU usage information
*/ */
public ResourceUsage getCpu() { @Nullable
return cpu; public ResourceStatus getCpu() {
return this.cpu;
} }
/** /**
* @return details of memory usage and limits * @return details of memory usage and limits
*/ */
public ResourceUsage getMemory() { @Nullable
return memory; public ResourceStatus getMemory() {
return this.memory;
} }
/** /**
* @return details of disk usage and limits * @return details of disk usage and limits
*/ */
public ResourceUsage getDisk() { @Nullable
return disk; public ResourceStatus getDisk() {
return this.disk;
} }
/** /**
* @return the uptime of the server * @return the uptime of the server
*/ */
@Nullable
public ServerUptime getUptime() { public ServerUptime getUptime() {
return uptime; return this.uptime;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof ServerStatus) {
final ServerStatus other = (ServerStatus) object;
return Objects.equal(state, other.state)
&& Objects.equal(cpu, other.cpu)
&& Objects.equal(memory, other.memory)
&& Objects.equal(disk, other.disk)
&& Objects.equal(uptime, other.uptime);
} else {
return false;
}
} }
@Override @Override
@ -145,10 +171,26 @@ public class ServerStatus {
return Objects.hashCode(state, cpu, memory, disk, uptime); return Objects.hashCode(state, cpu, memory, disk, uptime);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ServerStatus that = ServerStatus.class.cast(obj);
return Objects.equal(this.state, that.state)
&& Objects.equal(this.cpu, that.cpu)
&& Objects.equal(this.memory, that.memory)
&& Objects.equal(this.disk, that.disk)
&& Objects.equal(this.uptime, that.uptime);
}
protected ToStringHelper string() {
return Objects.toStringHelper("")
.add("state", state).add("cpu", cpu).add("memory", memory).add("disk", disk).add("uptime", uptime);
}
@Override @Override
public String toString() { public String toString() {
return String.format("[state=%s, cpu=%s, memory=%s, disk=%s, uptime=%s]", return string().toString();
state, cpu, memory, disk, uptime);
} }
} }

View File

@ -1,4 +1,4 @@
/** /*
* Licensed to jclouds, Inc. (jclouds) under one or more * Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
@ -18,7 +18,12 @@
*/ */
package org.jclouds.glesys.domain; package org.jclouds.glesys.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/** /**
* Represents an 'uptime' duration of server in a Glesys cloud * Represents an 'uptime' duration of server in a Glesys cloud
@ -27,64 +32,76 @@ import com.google.common.base.Objects;
* @see ServerStatus * @see ServerStatus
*/ */
public class ServerUptime { public class ServerUptime {
public static Builder builder() {
return new Builder(); public static Builder<?> builder() {
return new ConcreteBuilder();
} }
public static class Builder { public Builder<?> toBuilder() {
private long current; return new ConcreteBuilder().fromServerUptime(this);
private String unit; }
public Builder current(long current) { public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected long current;
protected String unit;
/**
* @see ServerUptime#getCurrent()
*/
public T current(long current) {
this.current = current; this.current = current;
return this; return self();
} }
public Builder unit(String unit) { /**
this.unit = unit; * @see ServerUptime#getUnit()
return this; */
public T unit(String unit) {
this.unit = checkNotNull(unit, "unit");
return self();
} }
public ServerUptime build() { public ServerUptime build() {
return new ServerUptime(current, unit); return new ServerUptime(current, unit);
} }
public Builder fromServerUptime(ServerUptime from) { public T fromServerUptime(ServerUptime in) {
return current(from.getCurrent()).unit(from.getUnit()); return this.current(in.getCurrent()).unit(in.getUnit());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
} }
} }
private final long current; private final long current;
private final String unit; private final String unit;
public ServerUptime(long current, String unit) { @ConstructorProperties({
"current", "unit"
})
protected ServerUptime(long current, String unit) {
this.current = current; this.current = current;
this.unit = unit; this.unit = checkNotNull(unit, "unit");
} }
/** /**
* @return the time the server has been up in #unit * @return the time the server has been up in #getUnit()
*/ */
public long getCurrent() { public long getCurrent() {
return current; return this.current;
} }
/** /**
* @return the unit used for #time * @return the unit used for #getCurrent()
*/ */
public String getUnit() { public String getUnit() {
return unit; return this.unit;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
return object instanceof ServerUptime
&& Objects.equal(current, ((ServerUptime) object).getCurrent())
&& Objects.equal(unit, ((ServerUptime) object).getUnit());
} }
@Override @Override
@ -92,9 +109,21 @@ public class ServerUptime {
return Objects.hashCode(current, unit); return Objects.hashCode(current, unit);
} }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ServerUptime that = ServerUptime.class.cast(obj);
return Objects.equal(this.current, that.current) && Objects.equal(this.unit, that.unit);
}
protected ToStringHelper string() {
return Objects.toStringHelper("").add("current", current).add("unit", unit);
}
@Override @Override
public String toString() { public String toString() {
return String.format("[current=%d unit=%s]", current, unit); return string().toString();
} }
} }

View File

@ -29,7 +29,6 @@ import javax.ws.rs.core.MediaType;
import org.jclouds.glesys.domain.Archive; import org.jclouds.glesys.domain.Archive;
import org.jclouds.glesys.domain.ArchiveAllowedArguments; import org.jclouds.glesys.domain.ArchiveAllowedArguments;
import org.jclouds.glesys.domain.ArchiveDetails;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
@ -61,21 +60,23 @@ public interface ArchiveAsyncClient {
ListenableFuture<Set<Archive>> listArchives(); ListenableFuture<Set<Archive>> listArchives();
/** /**
* @see ArchiveClient#getArchiveDetails * @see ArchiveClient#getArchive
*/ */
@POST @POST
@Path("/archive/details/format/json") @Path("/archive/details/format/json")
@SelectJson("details") @SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<ArchiveDetails> getArchiveDetails(@FormParam("username") String username); ListenableFuture<Archive> getArchive(@FormParam("username") String username);
/** /**
* @see ArchiveClient#createArchive * @see ArchiveClient#createArchive
*/ */
@POST @POST
@Path("/archive/create/format/json") @Path("/archive/create/format/json")
ListenableFuture<Void> createArchive(@FormParam("username") String username, @FormParam("password") String password, @SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Archive> createArchive(@FormParam("username") String username, @FormParam("password") String password,
@FormParam("size")int size); @FormParam("size")int size);
/** /**
@ -90,13 +91,17 @@ public interface ArchiveAsyncClient {
*/ */
@POST @POST
@Path("/archive/resize/format/json") @Path("/archive/resize/format/json")
ListenableFuture<Void> resizeArchive(@FormParam("username") String username, @FormParam("size") int size); @SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Archive> resizeArchive(@FormParam("username") String username, @FormParam("size") int size);
/** /**
* @see ArchiveClient#changeArchivePassword * @see ArchiveClient#changeArchivePassword
*/ */
@POST @POST
@Path("/archive/changepassword/format/json") @Path("/archive/changepassword/format/json")
ListenableFuture<Void> changeArchivePassword(@FormParam("username") String username, @FormParam("password") String password); @SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Archive> changeArchivePassword(@FormParam("username") String username, @FormParam("password") String password);
/** /**
* @see org.jclouds.glesys.features.ArchiveClient#getArchiveAllowedArguments * @see org.jclouds.glesys.features.ArchiveClient#getArchiveAllowedArguments

View File

@ -24,7 +24,6 @@ import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.glesys.domain.Archive; import org.jclouds.glesys.domain.Archive;
import org.jclouds.glesys.domain.ArchiveAllowedArguments; import org.jclouds.glesys.domain.ArchiveAllowedArguments;
import org.jclouds.glesys.domain.ArchiveDetails;
/** /**
* Provides synchronous access to Archive requests. * Provides synchronous access to Archive requests.
@ -48,7 +47,7 @@ public interface ArchiveClient {
* @param username the username associated with the archive * @param username the username associated with the archive
* @return the archive information or null if not found * @return the archive information or null if not found
*/ */
ArchiveDetails getArchiveDetails(String username); Archive getArchive(String username);
/** /**
* Create a new backup volume. * Create a new backup volume.
@ -58,7 +57,7 @@ public interface ArchiveClient {
* @param password the new password * @param password the new password
* @param size the new size required in GB * @param size the new size required in GB
*/ */
void createArchive(String username, String password, int size); Archive createArchive(String username, String password, int size);
/** /**
* Delete an archive volume. All files on the volume * Delete an archive volume. All files on the volume
@ -75,7 +74,7 @@ public interface ArchiveClient {
* @param username the username associated with the archive * @param username the username associated with the archive
* @param size the new size required, see #getArchiveAllowedArguments for valid values * @param size the new size required, see #getArchiveAllowedArguments for valid values
*/ */
void resizeArchive(String username, int size); Archive resizeArchive(String username, int size);
/** /**
* Change the password for an archive user. * Change the password for an archive user.
@ -83,7 +82,7 @@ public interface ArchiveClient {
* @param username the archive username * @param username the archive username
* @param password the new password * @param password the new password
*/ */
void changeArchivePassword(String username, String password); Archive changeArchivePassword(String username, String password);
/** /**
* Lists the allowed arguments for some of the functions in this module such as archive size. * Lists the allowed arguments for some of the functions in this module such as archive size.

View File

@ -37,6 +37,7 @@ import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SelectJson;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -61,19 +62,33 @@ public interface DomainAsyncClient {
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<Domain>> listDomains(); ListenableFuture<Set<Domain>> listDomains();
/**
* @see org.jclouds.glesys.features.DomainClient#getDomain
*/
@POST
@Path("/domain/details/format/json")
@SelectJson("domain")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Domain> getDomain(@FormParam("domainname") String name);
/** /**
* @see DomainClient#addDomain * @see DomainClient#addDomain
*/ */
@POST @POST
@Path("/domain/add/format/json") @Path("/domain/add/format/json")
ListenableFuture<Void> addDomain(@FormParam("domainname") String name, AddDomainOptions... options); @SelectJson("domain")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Domain> addDomain(@FormParam("domainname") String name, AddDomainOptions... options);
/** /**
* @see DomainClient#editDomain * @see DomainClient#editDomain
*/ */
@POST @POST
@Path("/domain/edit/format/json") @Path("/domain/edit/format/json")
ListenableFuture<Void> editDomain(@FormParam("domainname") String domain, DomainOptions... options); @SelectJson("domain")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Domain> editDomain(@FormParam("domainname") String domain, DomainOptions... options);
/** /**
@ -97,7 +112,9 @@ public interface DomainAsyncClient {
*/ */
@POST @POST
@Path("/domain/addrecord/format/json") @Path("/domain/addrecord/format/json")
ListenableFuture<Void> addRecord(@FormParam("domainname") String domain, @FormParam("host") String host, @SelectJson("record")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<DomainRecord> addRecord(@FormParam("domainname") String domain, @FormParam("host") String host,
@FormParam("type") String type, @FormParam("data") String data, @FormParam("type") String type, @FormParam("data") String data,
AddRecordOptions... options); AddRecordOptions... options);
@ -106,7 +123,9 @@ public interface DomainAsyncClient {
*/ */
@POST @POST
@Path("/domain/updaterecord/format/json") @Path("/domain/updaterecord/format/json")
ListenableFuture<Void> editRecord(@FormParam("recordid") String record_id, EditRecordOptions... options); @SelectJson("record")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<DomainRecord> editRecord(@FormParam("recordid") String record_id, EditRecordOptions... options);
/** /**
* @see DomainClient#deleteRecord * @see DomainClient#deleteRecord

View File

@ -41,27 +41,36 @@ import org.jclouds.glesys.options.EditRecordOptions;
public interface DomainClient { public interface DomainClient {
/** /**
* Get a list of all invoices for this account. * Get a list of all domains for this account.
* *
* @return an account's associated invoice objects. * @return an account's associated domain objects.
*/ */
Set<Domain> listDomains(); Set<Domain> listDomains();
/** /**
* Add a domain to the Glesys dns-system * Get a specific domain.
* *
* @param domain the name of the domain to add. * @return the requested domain object.
* @param options optional parameters
*/ */
void addDomain(String domain, AddDomainOptions... options); Domain getDomain(String domain);
/** /**
* Add a domain to the Glesys dns-system * Add a domain to the Glesys dns-system
* *
* @param domain the name of the domain to add. * @param domain the name of the domain to add.
* @param options optional parameters * @param options optional parameters
* @return information about the added domain
*/ */
void editDomain(String domain, DomainOptions... options); Domain addDomain(String domain, AddDomainOptions... options);
/**
* Edit a domain to the Glesys dns-system
*
* @param domain the name of the domain to add.
* @param options optional parameters
* @return information about the modified domain
*/
Domain editDomain(String domain, DomainOptions... options);
/** /**
* Remove a domain to the Glesys dns-system * Remove a domain to the Glesys dns-system
@ -80,13 +89,10 @@ public interface DomainClient {
/** /**
* Add a DNS Record * Add a DNS Record
* *
* @param domain the domain to add the record to * @param domain the domain to add the record to
* @param host
* @param type
* @param data
* @param options optional settings for the record * @param options optional settings for the record
*/ */
void addRecord(String domain, String host, String type, String data, AddRecordOptions... options); DomainRecord addRecord(String domain, String host, String type, String data, AddRecordOptions... options);
/** /**
* Modify a specific DNS Record * Modify a specific DNS Record
@ -95,7 +101,7 @@ public interface DomainClient {
* @param options the settings to change * @param options the settings to change
* @see #listRecords to retrieve the necessary ids * @see #listRecords to retrieve the necessary ids
*/ */
void editRecord(String recordId, EditRecordOptions... options); DomainRecord editRecord(String recordId, EditRecordOptions... options);
/** /**
* Delete a DNS record * Delete a DNS record

View File

@ -27,6 +27,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAccount;
import org.jclouds.glesys.domain.EmailAlias;
import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.domain.EmailOverview;
import org.jclouds.glesys.options.CreateAccountOptions; import org.jclouds.glesys.options.CreateAccountOptions;
import org.jclouds.glesys.options.EditAccountOptions; import org.jclouds.glesys.options.EditAccountOptions;
@ -55,7 +56,7 @@ public interface EmailAsyncClient {
*/ */
@POST @POST
@Path("/email/overview/format/json") @Path("/email/overview/format/json")
@SelectJson("response") @SelectJson("overview")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<EmailOverview> getEmailOverview(); ListenableFuture<EmailOverview> getEmailOverview();
@ -68,41 +69,59 @@ public interface EmailAsyncClient {
@SelectJson("emailaccounts") @SelectJson("emailaccounts")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<EmailAccount>> listAccounts(@FormParam("domain") String domain); ListenableFuture<Set<EmailAccount>> listAccounts(@FormParam("domainname") String domain);
/**
* @see org.jclouds.glesys.features.EmailClient#listAccounts
*/
@POST
@Path("/email/list/format/json")
@SelectJson("emailaliases")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<EmailAlias>> listAliases(@FormParam("domainname") String domain);
/** /**
* @see org.jclouds.glesys.features.EmailClient#createAccount * @see org.jclouds.glesys.features.EmailClient#createAccount
*/ */
@POST @POST
@Consumes(MediaType.APPLICATION_JSON)
@SelectJson("emailaccount")
@Path("/email/createaccount/format/json") @Path("/email/createaccount/format/json")
ListenableFuture<Void> createAccount(@FormParam("emailaccount") String accountAddress, @FormParam("password") String password, CreateAccountOptions... options); ListenableFuture<EmailAccount> createAccount(@FormParam("emailaccount") String accountAddress, @FormParam("password") String password, CreateAccountOptions... options);
/** /**
* @see org.jclouds.glesys.features.EmailClient#createAlias * @see org.jclouds.glesys.features.EmailClient#createAlias
*/ */
@POST @POST
@Consumes(MediaType.APPLICATION_JSON)
@SelectJson("alias")
@Path("/email/createalias/format/json") @Path("/email/createalias/format/json")
ListenableFuture<Void> createAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress); ListenableFuture<EmailAlias> createAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress);
/** /**
* @see org.jclouds.glesys.features.EmailClient#editAccount * @see org.jclouds.glesys.features.EmailClient#editAccount
*/ */
@POST @POST
@Consumes(MediaType.APPLICATION_JSON)
@SelectJson("emailaccount")
@Path("/email/editaccount/format/json") @Path("/email/editaccount/format/json")
ListenableFuture<Void> editAccount(@FormParam("emailaccount") String accountAddress, EditAccountOptions... options); ListenableFuture<EmailAccount> editAccount(@FormParam("emailaccount") String accountAddress, EditAccountOptions... options);
/** /**
* @see org.jclouds.glesys.features.EmailClient#editAlias * @see org.jclouds.glesys.features.EmailClient#editAlias
*/ */
@POST @POST
@Consumes(MediaType.APPLICATION_JSON)
@SelectJson("alias")
@Path("/email/editalias/format/json") @Path("/email/editalias/format/json")
ListenableFuture<Void> editAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress); ListenableFuture<EmailAlias> editAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress);
/** /**
* @see org.jclouds.glesys.features.EmailClient#delete * @see org.jclouds.glesys.features.EmailClient#delete
*/ */
@POST @POST
@Path("/email/delete/format/json") @Path("/email/delete/format/json")
ListenableFuture<Void> delete(@FormParam("email") String accountAddress); ListenableFuture<Boolean> delete(@FormParam("email") String accountAddress);
} }

View File

@ -23,6 +23,7 @@ import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAccount;
import org.jclouds.glesys.domain.EmailAlias;
import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.domain.EmailOverview;
import org.jclouds.glesys.options.CreateAccountOptions; import org.jclouds.glesys.options.CreateAccountOptions;
import org.jclouds.glesys.options.EditAccountOptions; import org.jclouds.glesys.options.EditAccountOptions;
@ -52,6 +53,13 @@ public interface EmailClient {
*/ */
Set<EmailAccount> listAccounts(String domain); Set<EmailAccount> listAccounts(String domain);
/**
* Get the set of details about e-mail aliases
*
* @return the relevant set of details
*/
Set<EmailAlias> listAliases(String domain);
/** /**
* Create a new e-mail account * Create a new e-mail account
* *
@ -60,7 +68,7 @@ public interface EmailClient {
* @param options optional parameters * @param options optional parameters
* @see DomainClient#addDomain * @see DomainClient#addDomain
*/ */
void createAccount(String accountAddress, String password, CreateAccountOptions... options); EmailAccount createAccount(String accountAddress, String password, CreateAccountOptions... options);
/** /**
* Create an e-mail alias for an e-mail account * Create an e-mail alias for an e-mail account
@ -69,7 +77,7 @@ public interface EmailClient {
* @param toEmailAddress the existing e-mail account address the alias should forward to * @param toEmailAddress the existing e-mail account address the alias should forward to
* @see DomainClient#addDomain * @see DomainClient#addDomain
*/ */
void createAlias(String aliasAddress, String toEmailAddress); EmailAlias createAlias(String aliasAddress, String toEmailAddress);
/** /**
* Adjust an e-mail account's settings * Adjust an e-mail account's settings
@ -77,7 +85,7 @@ public interface EmailClient {
* @param accountAddress the existing e-mail account address * @param accountAddress the existing e-mail account address
* @param options optional parameters * @param options optional parameters
*/ */
void editAccount(String accountAddress, EditAccountOptions... options); EmailAccount editAccount(String accountAddress, EditAccountOptions... options);
/** /**
* Adjust (re-target) an e-mail alias * Adjust (re-target) an e-mail alias
@ -85,13 +93,13 @@ public interface EmailClient {
* @param aliasAddress the existing alias e-mail address * @param aliasAddress the existing alias e-mail address
* @param toEmailAddress the existing e-mail account address the alias should forward to * @param toEmailAddress the existing e-mail account address the alias should forward to
*/ */
void editAlias(String aliasAddress, String toEmailAddress); EmailAlias editAlias(String aliasAddress, String toEmailAddress);
/** /**
* Delete an e-mail account or alias * Delete an e-mail account or alias
* *
* @param accountAddress the existing alias e-mail account or alias address * @param accountAddress the existing alias e-mail account or alias address
*/ */
void delete(String accountAddress); boolean delete(String accountAddress);
} }

View File

@ -29,8 +29,10 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.glesys.domain.IpDetails; import org.jclouds.glesys.domain.IpDetails;
import org.jclouds.glesys.options.ListIpOptions;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.FormParams;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SelectJson;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
@ -42,70 +44,111 @@ import com.google.common.util.concurrent.ListenableFuture;
* Provides asynchronous access to IP Addresses via their REST API. * Provides asynchronous access to IP Addresses via their REST API.
* <p/> * <p/>
* *
* @author Adrian Cole, Mattias Holmqvist * @author Adrian Cole, Mattias Holmqvist, Adam Lowe
* * @see IpClient
* @see ServerClient
* @see <a href="https://customer.glesys.com/api.php" /> * @see <a href="https://customer.glesys.com/api.php" />
*/ */
@RequestFilters(BasicAuthentication.class) @RequestFilters(BasicAuthentication.class)
public interface IpAsyncClient { public interface IpAsyncClient {
/**
* @see IpClient#take
*/
@POST
@Path("/ip/take/format/json")
ListenableFuture<Void> take(@FormParam("ipaddress") String ipAddress);
/**
* @see IpClient#release
*/
@POST
@Path("/ip/release/format/json")
ListenableFuture<Void> release(@FormParam("ipaddress") String ipAddress);
/**
* @see IpClient#add
*/
@POST
@Path("/ip/add/format/json")
ListenableFuture<Void> addIpToServer(@FormParam("ipaddress") String ipAddress,
@FormParam("serverid") String serverId);
/**
* @see IpClient#remove
*
* TODO: add optional release_ip parameter
*/
@POST
@Path("/ip/remove/format/json")
ListenableFuture<Void> removeIpFromServer(@FormParam("ipaddress") String ipAddress,
@FormParam("serverid") String serverId);
/** /**
* @see IpClient#listFree * @see IpClient#listFree
*/ */
@GET @GET
@Path("/ip/listfree/ipversion/{ipversion}/datacenter/{datacenter}/platform/{platform}/format/json") @Path("/ip/listfree/ipversion/{ipversion}/datacenter/{datacenter}/platform/{platform}/format/json")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@SelectJson("iplist") @SelectJson("ipaddresses")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<String>> listFree(@PathParam("ipversion") String ipversion, ListenableFuture<Set<String>> listFree(@PathParam("ipversion") int ipversion,
@PathParam("datacenter") String datacenter, @PathParam("datacenter") String datacenter,
@PathParam("platform") String platform); @PathParam("platform") String platform);
/** /**
* @see IpClient#getIpDetails * @see IpClient#take
*/
@POST
@Path("/ip/take/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> take(@FormParam("ipaddress") String ipAddress);
/**
* @see IpClient#release
*/
@POST
@Path("/ip/release/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> release(@FormParam("ipaddress") String ipAddress);
/**
* @see IpClient#listIps
*/
@GET
@Path("/ip/listown/format/json")
@Consumes(MediaType.APPLICATION_JSON)
@SelectJson("iplist")
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<IpDetails>> listIps(ListIpOptions... options);
/**
* @see IpClient#getIp
*/ */
@GET @GET
@Path("/ip/details/ipaddress/{ipaddress}/format/json") @Path("/ip/details/ipaddress/{ipaddress}/format/json")
@Consumes(MediaType.APPLICATION_JSON)
@SelectJson("details") @SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<IpDetails> getIpDetails(@PathParam("ipaddress") String ipAddress); ListenableFuture<IpDetails> getIp(@PathParam("ipaddress") String ipAddress);
/**
* @see IpClient#addIpToServer
*/
@POST
@Path("/ip/add/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> addIpToServer(@FormParam("ipaddress") String ipAddress,
@FormParam("serverid") String serverId);
/**
* @see IpClient#removeIpFromServer
*/
@POST
@Path("/ip/remove/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> removeIpFromServer(@FormParam("ipaddress") String ipAddress,
@FormParam("serverid") String serverId);
/**
* @see IpClient#removeIpFromServer
*/
@POST
@FormParams(keys = "release", values = "true")
@Path("/ip/remove/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> removeIpFromServerAndRelease(@FormParam("ipaddress") String ipAddress,
@FormParam("serverid") String serverId);
/**
* @see IpClient#setPtr
*/
@POST
@Path("/ip/setptr/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> setPtr(@FormParam("ipaddress") String ipAddress,
@FormParam("data") String ptr);
/**
* @see IpClient#resetPtr
*/
@POST
@Path("/ip/resetptr/format/json")
@SelectJson("details")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<IpDetails> resetPtr(@FormParam("ipaddress") String ipAddress);
} }

View File

@ -23,72 +23,100 @@ import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.glesys.domain.IpDetails; import org.jclouds.glesys.domain.IpDetails;
import org.jclouds.glesys.options.ListIpOptions;
/** /**
* Provides synchronous access to IP Addresses. * Provides synchronous access to IP Addresses.
* <p/> * <p/>
* *
* @author Adrian Cole, Mattias Holmqvist * @author Adrian Cole, Mattias Holmqvist, Adam Lowe
* @see IpAsyncClient * @see IpAsyncClient
* @see <a href="https://customer.glesys.com/api.php" /> * @see <a href="https://customer.glesys.com/api.php" />
*/ */
@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) @Timeout(duration = 30, timeUnit = TimeUnit.SECONDS)
public interface IpClient { public interface IpClient {
/**
* Get a set of all IP addresses that are available and not used on any account or server.
*
* @param ipVersion 4 or 6, for IPV4 or IPV6, respectively
* @param datacenter the datacenter
* @param platform the platform
* @return a set of free IP addresses
*/
Set<String> listFree(int ipVersion, String datacenter, String platform);
/** /**
* Take a free IP address and add it to this account. You can list free IP addresses with the function listFree(). * Take a free IP address and add it to this account. You can list free IP addresses with the function listFree().
* Once your free IP on this account you can add it to a server with the add() function. * Once your free IP on this account you can add it to a server with the add() function.
* *
* @param ipAddress * @param ipAddress the IP address to be add to this account (reserve)
*/ */
void take(String ipAddress); IpDetails take(String ipAddress);
/** /**
* Return an unused IP address to the pool of free ips. If the IP address is allocated to a server, * Return an unused IP address to the pool of free ips. If the IP address is allocated to a server,
* it must first be removed by calling remove(ipAddress) before it can be released. * it must first be removed by calling remove(ipAddress) before it can be released.
* *
* @param ipAddress the IP address to be released * @param ipAddress the IP address to be released
*/ */
void release(String ipAddress); IpDetails release(String ipAddress);
/** /**
* Add an IP address to an server. The IP has to be free, but reserved to this account. You are able to list such addresses * Get IP addresses associated with your account (reserved, assigned to servers, etc)
* with listOwn() and reserve an address for this account by using take(). To find free ips you can use ip/listfree *
* ip to an Xen-server you have to configure the server yourself, unless the ip was added during the c * @param options options to filter the results (by IPV4/6, serverId, etc)
* server (server/create). You can get detailed information such as gateway and netmask using the ip * @return the set of IP addresses
* */
* @param ipAddress the IP address to remove Set<IpDetails> listIps(ListIpOptions... options);
* @param serverId the server to add the IP address to
*/
void addIpToServer(String ipAddress, String serverId);
/** /**
* Remove an IP address from a server. This does not release it back to GleSYS pool of free ips. The address will be * Get details about the given IP address such as gateway and netmask. Different details are available
* kept on the account so that you can use it for other servers or the same server at a later time. To completely remove * on different platforms.
* the IP address from this account, use the function release(). *
* * @param ipAddress the ip address
* @param ipAddress the IP address to remove * @return details about the given IP address
* @param serverId the server to remove the IP address from */
*/ IpDetails getIp(String ipAddress);
void removeIpFromServer(String ipAddress, String serverId);
/** /**
* Get a set of all IP addresses that are available and not used on any account or server. * Add an IP address to an server. The IP has to be free, but reserved to this account. You are able to list such addresses
* * with listOwn() and reserve an address for this account by using take(). To find free ips you can use ip/listfree
* @param ipversion "4" or "6", for IPV4 or IPV6, respectively * ip to an Xen-server you have to configure the server yourself, unless the ip was added during the c
* @param datacenter the datacenter * server (server/create). You can get detailed information such as gateway and netmask using the ip
* @param platform the platform *
* @return a set of free IP addresses * @param ipAddress the IP address to remove
*/ * @param serverId the server to add the IP address to
Set<String> listFree(String ipversion, String datacenter, String platform); */
IpDetails addIpToServer(String ipAddress, String serverId);
/** /**
* Get details about the given IP address such as gateway and netmask. Different details are available * Remove an IP address from a server. This does not release it back to GleSYS pool of free ips. The address will be
* on different platforms. * kept on the account so that you can use it for other servers or the same server at a later time. To completely remove
* * the IP address from this account, use removeIpFromServerAndRelease to do so
* @param ipAddress the ip address *
* @return details about the given IP address * @param ipAddress the IP address to remove
*/ * @param serverId the server to remove the IP address from
IpDetails getIpDetails(String ipAddress); * @see #removeIpFromServerAndRelease
*/
IpDetails removeIpFromServer(String ipAddress, String serverId);
/**
* Remove an IP address from a server and release it back to GleSYS pool of free ips.
*
* @param ipAddress the IP address to remove
* @param serverId the server to remove the IP address from
* @see #removeIpFromServer
*/
IpDetails removeIpFromServerAndRelease(String ipAddress, String serverId);
/**
* Sets PTR data for an IP. Use ip/listown or ip/details to get current PTR data
*/
IpDetails setPtr(String ipAddress, String ptr);
/**
* Resets PTR data for an IP back to the default value
*/
IpDetails resetPtr(String ipAddress);
} }

View File

@ -32,6 +32,7 @@ import javax.ws.rs.core.MediaType;
import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer; import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;
import org.jclouds.glesys.domain.Console; import org.jclouds.glesys.domain.Console;
import org.jclouds.glesys.domain.OSTemplate; import org.jclouds.glesys.domain.OSTemplate;
import org.jclouds.glesys.domain.ResourceUsage;
import org.jclouds.glesys.domain.Server; import org.jclouds.glesys.domain.Server;
import org.jclouds.glesys.domain.ServerDetails; import org.jclouds.glesys.domain.ServerDetails;
import org.jclouds.glesys.domain.ServerLimit; import org.jclouds.glesys.domain.ServerLimit;
@ -225,15 +226,19 @@ public interface ServerAsyncClient {
* @see ServerClient#resetPassword * @see ServerClient#resetPassword
*/ */
@POST @POST
@Path("/server/destroy/format/json") @Path("/server/resetpassword/format/json")
ListenableFuture<Void> resetPassword(@FormParam("serverid") String id, @FormParam("newpassword") String password); @SelectJson("server")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<ServerDetails> resetPassword(@FormParam("serverid") String id, @FormParam("rootpassword") String password);
/** /**
* @see ServerClient#resourceUsage * @see ServerClient#getResourceUsage
*/ */
@POST @POST
@Path("/server/resourceusage/format/json") @Path("/server/resourceusage/format/json")
void resourceUsage(@FormParam("serverid") String id, @FormParam("resource") String resource, @SelectJson("usage")
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<ResourceUsage> getResourceUsage(@FormParam("serverid") String id, @FormParam("resource") String resource,
@FormParam("resolution") String resolution); @FormParam("resolution") String resolution);
} }

View File

@ -26,6 +26,7 @@ import org.jclouds.concurrent.Timeout;
import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer; import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;
import org.jclouds.glesys.domain.Console; import org.jclouds.glesys.domain.Console;
import org.jclouds.glesys.domain.OSTemplate; import org.jclouds.glesys.domain.OSTemplate;
import org.jclouds.glesys.domain.ResourceUsage;
import org.jclouds.glesys.domain.Server; import org.jclouds.glesys.domain.Server;
import org.jclouds.glesys.domain.ServerDetails; import org.jclouds.glesys.domain.ServerDetails;
import org.jclouds.glesys.domain.ServerLimit; import org.jclouds.glesys.domain.ServerLimit;
@ -63,8 +64,7 @@ public interface ServerClient {
* configuration (cpu, memory and disk), ip addresses, cost, transfer, os and * configuration (cpu, memory and disk), ip addresses, cost, transfer, os and
* more. * more.
* *
* @param id * @param id id of the server
* id of the server
* @return server or null if not found * @return server or null if not found
*/ */
ServerDetails getServerDetails(String id); ServerDetails getServerDetails(String id);
@ -73,10 +73,8 @@ public interface ServerClient {
* Get detailed information about a server status including up-time and * Get detailed information about a server status including up-time and
* hardware usage (cpu, disk, memory and bandwidth) * hardware usage (cpu, disk, memory and bandwidth)
* *
* @param id * @param id id of the server
* id of the server * @param options optional parameters
* @param options
* optional parameters
* @return the status of the server or null if not found * @return the status of the server or null if not found
*/ */
ServerStatus getServerStatus(String id, ServerStatusOptions... options); ServerStatus getServerStatus(String id, ServerStatusOptions... options);
@ -85,8 +83,7 @@ public interface ServerClient {
* Get detailed information about a server's limits (for OpenVZ only). * Get detailed information about a server's limits (for OpenVZ only).
* <p/> * <p/>
* *
* @param id * @param id id of the server
* id of the server
* @return the requested information about the server or null if not found * @return the requested information about the server or null if not found
*/ */
Map<String, ServerLimit> getServerLimits(String id); Map<String, ServerLimit> getServerLimits(String id);
@ -94,8 +91,7 @@ public interface ServerClient {
/** /**
* Get information about how to connect to a server via VNC * Get information about how to connect to a server via VNC
* *
* @param id * @param id id of the server
* id of the server
* @return the requested information about the server or null if not found * @return the requested information about the server or null if not found
*/ */
Console getConsole(String id); Console getConsole(String id);
@ -117,54 +113,45 @@ public interface ServerClient {
/** /**
* Reset the fail count for a server limit (for OpenVZ only). * Reset the fail count for a server limit (for OpenVZ only).
* *
* @param id * @param id id of the server
* id of the server * @param type the type of limit to reset
* @param type
* the type of limit to reset
*/ */
Map<String, ServerLimit> resetServerLimit(String id, String type); Map<String, ServerLimit> resetServerLimit(String id, String type);
/** /**
* Reboot a server * Reboot a server
* *
* @param id * @param id id of the server
* id of the server
*/ */
ServerDetails rebootServer(String id); ServerDetails rebootServer(String id);
/** /**
* Start a server * Start a server
* *
* @param id * @param id id of the server
* id of the server
*/ */
ServerDetails startServer(String id); ServerDetails startServer(String id);
/** /**
* Stop a server * Stop a server
* *
* @param id * @param id id of the server
* id of the server
*/ */
void stopServer(String id); ServerDetails stopServer(String id);
/** /**
* hard stop a server * hard stop a server
* *
* @param id * @param id id of the server
* id of the server
*/ */
void hardStopServer(String id); ServerDetails hardStopServer(String id);
/** /**
* Create a new server * Create a new server
* *
* @param hostname * @param hostname the host name of the new server
* the host name of the new server * @param rootPassword the root password to use
* @param rootPassword * @param options optional settings ex. description
* the root password to use
* @param options
* optional settings ex. description
*/ */
@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS)
ServerDetails createServerWithHostnameAndRootPassword(ServerSpec serverSpec, String hostname, String rootPassword, ServerDetails createServerWithHostnameAndRootPassword(ServerSpec serverSpec, String hostname, String rootPassword,
@ -173,22 +160,17 @@ public interface ServerClient {
/** /**
* Edit the configuration of a server * Edit the configuration of a server
* *
* @param serverid * @param serverid the serverId of the server to edit
* the serverId of the server to edit * @param options the settings to change
* @param options
* the settings to change
*/ */
ServerDetails editServer(String serverid, EditServerOptions... options); ServerDetails editServer(String serverid, EditServerOptions... options);
/** /**
* Clone a server * Clone a server
* *
* @param serverid * @param serverid the serverId of the server to clone
* the serverId of the server to clone * @param hostname the new host name of the cloned server
* @param hostname * @param options the settings to change
* the new host name of the cloned server
* @param options
* the settings to change
*/ */
@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS)
ServerDetails cloneServer(String serverid, String hostname, CloneServerOptions... options); ServerDetails cloneServer(String serverid, String hostname, CloneServerOptions... options);
@ -196,34 +178,28 @@ public interface ServerClient {
/** /**
* Destroy a server * Destroy a server
* *
* @param id * @param id the id of the server
* the id of the server * @param keepIp if DestroyServerOptions.keepIp(true) the servers ip will be retained for use in your GleSYS account
* @param keepIp
* if DestroyServerOptions.keepIp(true) the servers ip will be
* retained for use in your GleSYS account
*/ */
ServerDetails destroyServer(String id, DestroyServerOptions keepIp); ServerDetails destroyServer(String id, DestroyServerOptions keepIp);
/** /**
* Reset the root password of a server * Reset the root password of a server
* *
* @param id * @param id the id of the server
* the id of the server * @param password the new password to use
* @param password
* the new password to use
*/ */
void resetPassword(String id, String password); ServerDetails resetPassword(String id, String password);
/** /**
* Return resource usage over time for server * Return resource usage over time for server
* *
* @param id * @param id the id of the server
* the id of the server * @param resource the name of the resource to retrieve usage information for (e.g. "cpuusage")
* @param resource * @param resolution the time-period to extract data for (one of "minute", "hour" or "day)
* the name of the resource to retrieve usage information for
*/ */
@Beta @Beta
// TODO: better name // TODO: better name
void resourceUsage(String id, String resource, String resolution); ResourceUsage getResourceUsage(String id, String resource, String resolution);
} }

View File

@ -20,10 +20,13 @@ package org.jclouds.glesys.functions.internal;
import java.io.IOException; import java.io.IOException;
import org.jclouds.glesys.domain.GleSYSBoolean;
import org.jclouds.glesys.domain.Server; import org.jclouds.glesys.domain.Server;
import com.google.common.base.Objects;
import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
/** /**
@ -43,4 +46,24 @@ public class GleSYSTypeAdapters {
} }
} }
public static class GleSYSBooleanAdapter extends TypeAdapter<GleSYSBoolean> {
@Override
public void write(JsonWriter writer, GleSYSBoolean value) throws IOException {
writer.value(value.getValue() ? "yes" : "no");
}
@Override
public GleSYSBoolean read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.BOOLEAN) {
return new GleSYSBoolean(in.nextBoolean());
} else if (in.peek() == JsonToken.NULL) {
return GleSYSBoolean.FALSE;
} else {
return new GleSYSBoolean(Objects.equal(in.nextString(), "yes"));
}
}
}
} }

View File

@ -1,78 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.glesys.functions.internal;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.inject.Singleton;
import org.jclouds.date.DateService;
import org.jclouds.json.config.GsonModule;
import com.google.common.base.Throwables;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.inject.Inject;
/**
* Parser for Glesys Date formats
*
* @deprecated this should be replaced by standard ISO8601 parser in the next week or so
*
* @author Adam Lowe
*/
@Singleton
public class GlesysDateAdapter extends GsonModule.DateAdapter {
private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final DateService standardDateService;
@Inject
public GlesysDateAdapter(DateService service) {
this.standardDateService = service;
}
public void write(JsonWriter writer, Date value) throws IOException {
try {
writer.value(standardDateService.iso8601SecondsDateFormat(value));
} catch (Exception ex) {
synchronized (dateFormat) {
writer.value(dateFormat.format(value));
}
}
}
public Date read(JsonReader reader) throws IOException {
String toParse = reader.nextString();
try {
return standardDateService.iso8601SecondsDateParse(toParse);
} catch (Exception ex) {
try {
synchronized (dateFormat) {
return dateFormat.parse(toParse);
}
} catch (ParseException e) {
throw Throwables.propagate(e);
}
}
}
}

View File

@ -85,7 +85,7 @@ public class AddDomainOptions extends DomainOptions {
* Ensure only NS and SOA records will be created by default, when this option is not used a number of default records will be created on the domain. * Ensure only NS and SOA records will be created by default, when this option is not used a number of default records will be created on the domain.
*/ */
public DomainOptions minimalRecords() { public DomainOptions minimalRecords() {
formParameters.put("createrecords", "0"); formParameters.put("createrecords", Boolean.FALSE.toString());
return this; return this;
} }

View File

@ -70,19 +70,19 @@ public class CreateAccountOptions extends BaseHttpRequestOptions {
/** Enable or disable virus checking */ /** Enable or disable virus checking */
public CreateAccountOptions antiVirus(boolean antiVirus) { public CreateAccountOptions antiVirus(boolean antiVirus) {
formParameters.put("antivirus", Integer.toString(antiVirus ? 1 : 0)); formParameters.put("antivirus", Boolean.toString(antiVirus));
return this; return this;
} }
/** Enable or disable auto-respond */ /** Enable or disable auto-respond */
public CreateAccountOptions autorespond(boolean autorespond) { public CreateAccountOptions autorespond(boolean autorespond) {
formParameters.put("autorespond", Integer.toString(autorespond ? 1 : 0)); formParameters.put("autorespond", Boolean.toString(autorespond));
return this; return this;
} }
/** Enable or disable saving of auto-respond e-mails */ /** Enable or disable saving of auto-respond e-mails */
public CreateAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) { public CreateAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) {
formParameters.put("autorespondsaveemail", Integer.toString(autorespondSaveEmail ? 1 : 0)); formParameters.put("autorespondsaveemail", Boolean.toString(autorespondSaveEmail));
return this; return this;
} }

View File

@ -47,7 +47,7 @@ public class DestroyServerOptions extends BaseHttpRequestOptions {
* @param keepIp if true, keep the ip address * @param keepIp if true, keep the ip address
*/ */
public DestroyServerOptions keepIp(boolean keepIp) { public DestroyServerOptions keepIp(boolean keepIp) {
formParameters.put("keepip", Integer.toString(keepIp ? 1 : 0)); formParameters.put("keepip", Boolean.toString(keepIp));
return this; return this;
} }
} }

View File

@ -0,0 +1,106 @@
/**
* 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.glesys.options;
import org.jclouds.http.options.BaseHttpRequestOptions;
/**
* @author Adam Lowe
*/
public class ListIpOptions extends BaseHttpRequestOptions {
public static class Builder {
/**
* @see org.jclouds.glesys.options.ListIpOptions#used
*/
public static ListIpOptions used(boolean used) {
return new ListIpOptions().used(used);
}
/**
* @see org.jclouds.glesys.options.ListIpOptions#serverId
*/
public static ListIpOptions serverId(String serverId) {
return new ListIpOptions().serverId(serverId);
}
/**
* @see org.jclouds.glesys.options.ListIpOptions#ipVersion
*/
public static ListIpOptions ipVersion(int ipVersion) {
return new ListIpOptions().ipVersion(ipVersion);
}
/**
* @see org.jclouds.glesys.options.ListIpOptions#datacenter
*/
public static ListIpOptions datacenter(String datacenter) {
return new ListIpOptions().datacenter(datacenter);
}
/**
* @see org.jclouds.glesys.options.ListIpOptions#platform
*/
public static ListIpOptions platform(String platform) {
return new ListIpOptions().platform(platform);
}
}
/**
* Retrieve only IPs that are in use
*/
public ListIpOptions used(boolean used) {
formParameters.put("used", Boolean.toString(used));
return this;
}
/**
* Retrieve only IP assigned to the specified server
*/
public ListIpOptions serverId(String serverId) {
formParameters.put("serverid", serverId);
return this;
}
/**
* Retrieve only IPs of the requested version
*/
public ListIpOptions ipVersion(int ipVersion) {
formParameters.put("ipversion", Integer.toString(ipVersion));
return this;
}
/**
* Retrieve only IPs served in the specified datacenter
*/
public ListIpOptions datacenter(String datacenter) {
formParameters.put("datacenter", datacenter);
return this;
}
/**
* Retrieve only IPs served on the specified platform
*/
public ListIpOptions platform(String platform) {
formParameters.put("platform", platform);
return this;
}
}

View File

@ -21,8 +21,9 @@ package org.jclouds.glesys;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import org.jclouds.glesys.internal.BaseGleSYSAsyncClientTest;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.providers.ProviderMetadata;
import org.jclouds.rest.internal.BaseAsyncClientTest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -37,11 +38,15 @@ import com.google.inject.TypeLiteral;
// NOTE:without testName, this will not call @Before* and fail w/NPE during // NOTE:without testName, this will not call @Before* and fail w/NPE during
// surefire // surefire
@Test(groups = "unit", testName = "GleSYSAsyncClientTest") @Test(groups = "unit", testName = "GleSYSAsyncClientTest")
public class GleSYSAsyncClientTest extends BaseGleSYSAsyncClientTest<GleSYSAsyncClient> { public class GleSYSAsyncClientTest extends BaseAsyncClientTest<GleSYSAsyncClient> {
private GleSYSAsyncClient asyncClient; private GleSYSAsyncClient asyncClient;
private GleSYSClient syncClient; private GleSYSClient syncClient;
@Override
public ProviderMetadata createProviderMetadata() {
return new GleSYSProviderMetadata();
}
public void testSync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException { public void testSync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException {
assert syncClient.getServerClient() != null; assert syncClient.getServerClient() != null;
assert syncClient.getIpClient() != null; assert syncClient.getIpClient() != null;

View File

@ -20,10 +20,12 @@ package org.jclouds.glesys.compute.functions;
import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; import static org.jclouds.io.Payloads.newUrlEncodedFormPayload;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.net.URI; import java.net.URI;
import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
@ -73,22 +75,25 @@ public class ServerDetailsToNodeMetadataTest extends BaseGleSYSComputeServiceExp
).getInstance(ServerDetailsToNodeMetadata.class); ).getInstance(ServerDetailsToNodeMetadata.class);
NodeMetadata actual = toTest.apply(ServerClientExpectTest.expectedServerDetails());
assertNotNull(actual);
assertEquals( assertEquals(
toTest.apply(ServerClientExpectTest.expectedServerDetails()), actual.toString(),
new NodeMetadataBuilder() new NodeMetadataBuilder()
.ids("xm3276891") .ids("vz1840356")
.name("glesys-s-6dd") .name("test-email-jclouds")
.hostname("glesys-s-6dd") .hostname("test-email-jclouds")
.group("glesys-s") .group("glesys-s")
.imageId("Ubuntu 11.04 x64") .imageId("Ubuntu 10.04 LTS 32-bit")
.operatingSystem( .operatingSystem(
OperatingSystem.builder().name("Ubuntu 11.04 x64").family(OsFamily.UBUNTU).version("11.04") OperatingSystem.builder().name("Ubuntu 10.04 LTS 32-bit").family(OsFamily.UBUNTU).version("10.04")
.is64Bit(true).description("Ubuntu 11.04 x64").build()) .is64Bit(false).description("Ubuntu 10.04 LTS 32-bit").build())
.publicAddresses(ImmutableSet.of("109.74.10.45")) .publicAddresses(ImmutableSet.of("31.192.231.254"))
.hardware( .hardware(
new HardwareBuilder().ids("xm3276891").ram(512) new HardwareBuilder().ids("vz1840356").ram(512)
.processors(ImmutableList.of(new Processor(1, 1.0))) .processors(ImmutableList.of(new Processor(1, 1.0)))
.volumes(ImmutableList.<Volume> of(new VolumeImpl(5f, true, true))).hypervisor("Xen") .volumes(ImmutableList.<Volume> of(new VolumeImpl(5f, true, true))).hypervisor("OpenVZ")
.build()).status(Status.RUNNING).build()); .build()).status(Status.RUNNING).build().toString());
} }
} }

View File

@ -26,15 +26,13 @@ import static org.testng.Assert.assertTrue;
import java.net.URI; import java.net.URI;
import java.util.List; import java.util.List;
import org.jclouds.glesys.GleSYSClient;
import org.jclouds.glesys.domain.Archive; import org.jclouds.glesys.domain.Archive;
import org.jclouds.glesys.domain.ArchiveAllowedArguments; import org.jclouds.glesys.domain.ArchiveAllowedArguments;
import org.jclouds.glesys.domain.ArchiveDetails; import org.jclouds.glesys.internal.BaseGleSYSClientExpectTest;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.rest.internal.BaseRestClientExpectTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -46,10 +44,7 @@ import com.google.common.collect.ImmutableMultimap;
* @author Adam Lowe * @author Adam Lowe
*/ */
@Test(groups = "unit", testName = "ArchiveClientExpectTest") @Test(groups = "unit", testName = "ArchiveClientExpectTest")
public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClient> { public class ArchiveClientExpectTest extends BaseGleSYSClientExpectTest {
public ArchiveClientExpectTest() {
provider = "glesys";
}
public void testListArchivesWhenReponseIs2xx() throws Exception { public void testListArchivesWhenReponseIs2xx() throws Exception {
ArchiveClient client = requestSendsResponse( ArchiveClient client = requestSendsResponse(
@ -61,8 +56,8 @@ public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClie
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_list.json")).build()) HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_list.json")).build())
.getArchiveClient(); .getArchiveClient();
List<Archive> expected = ImmutableList.<Archive>of( List<Archive> expected = ImmutableList.of(
Archive.builder().username("xxxxx_test1").freeSize("20 GB").totalSize("20 GB").locked(false).build()); Archive.builder().username("xxxxx_test1").freeSize("20 GB").totalSize("30 GB").locked(false).build());
assertEquals(client.listArchives(), expected); assertEquals(client.listArchives(), expected);
} }
@ -88,9 +83,12 @@ public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClie
ImmutableMultimap.<String, String>builder().put("username", "xxxxxx_test1").build())).build(), ImmutableMultimap.<String, String>builder().put("username", "xxxxxx_test1").build())).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()) HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build())
.getArchiveClient(); .getArchiveClient();
ArchiveDetails expected = ArchiveDetails.builder().username("xxxxxx_test1").freeSize("30 GB").totalSize("30 GB").locked(false).build();
assertEquals(client.getArchiveDetails("xxxxxx_test1"), expected); assertEquals(client.getArchive("xxxxxx_test1"), detailsInArchiveDetails());
}
private Archive detailsInArchiveDetails() {
return Archive.builder().username("xxxxxx_test1").freeSize("30 GB").totalSize("30 GB").locked(false).build();
} }
public void testArchiveDetailsWhenResponseIs4xxReturnsNull() { public void testArchiveDetailsWhenResponseIs4xxReturnsNull() {
@ -103,20 +101,21 @@ public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClie
ImmutableMultimap.<String, String>builder().put("username", "xxxxxx_test1").build())).build(), ImmutableMultimap.<String, String>builder().put("username", "xxxxxx_test1").build())).build(),
HttpResponse.builder().statusCode(404).build()) HttpResponse.builder().statusCode(404).build())
.getArchiveClient(); .getArchiveClient();
assertNull(client.getArchiveDetails("xxxxxx_test1")); assertNull(client.getArchive("xxxxxx_test1"));
} }
public void testCreateArchiveWhenResponseIs2xx() throws Exception { public void testCreateArchiveWhenResponseIs2xx() throws Exception {
ArchiveClient client = requestSendsResponse( ArchiveClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/archive/create/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/archive/create/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("username", "xxxxxx_test1") .put("username", "xxxxxx_test1")
.put("size", "5") .put("size", "5")
.put("password", "somepass").build())).build(), .put("password", "somepass").build())).build(),
HttpResponse.builder().statusCode(200).build()).getArchiveClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()).getArchiveClient();
client.createArchive("xxxxxx_test1", "somepass", 5); assertEquals(client.createArchive("xxxxxx_test1", "somepass", 5), detailsInArchiveDetails());
} }
public void testDeleteArchiveWhenResponseIs2xx() throws Exception { public void testDeleteArchiveWhenResponseIs2xx() throws Exception {
@ -146,22 +145,24 @@ public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClie
public void testResizeArchiveWhenResponseIs2xx() throws Exception { public void testResizeArchiveWhenResponseIs2xx() throws Exception {
ArchiveClient client = requestSendsResponse( ArchiveClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/archive/resize/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/archive/resize/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("username", "username1") .put("username", "username1")
.put("size", "5").build())).build(), .put("size", "5").build())).build(),
HttpResponse.builder().statusCode(200).build()).getArchiveClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()).getArchiveClient();
client.resizeArchive("username1", 5); assertEquals(client.resizeArchive("username1", 5), detailsInArchiveDetails());
} }
@Test(expectedExceptions = {ResourceNotFoundException.class}) @Test(expectedExceptions = {ResourceNotFoundException.class})
public void testResizeArchiveWhenResponseIs4xxThrows() throws Exception { public void testResizeArchiveWhenResponseIs4xxThrows() throws Exception {
ArchiveClient client = requestSendsResponse( ArchiveClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/archive/resize/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/archive/resize/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("username", "username1") .put("username", "username1")
.put("size", "5").build())).build(), .put("size", "5").build())).build(),
@ -174,14 +175,15 @@ public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClie
ArchiveClient client = requestSendsResponse( ArchiveClient client = requestSendsResponse(
HttpRequest.builder().method("POST") HttpRequest.builder().method("POST")
.endpoint(URI.create("https://api.glesys.com/archive/changepassword/format/json")) .endpoint(URI.create("https://api.glesys.com/archive/changepassword/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("username", "username") .put("username", "username")
.put("password", "newpass").build())).build(), .put("password", "newpass").build())).build(),
HttpResponse.builder().statusCode(200).build()).getArchiveClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()).getArchiveClient();
client.changeArchivePassword("username", "newpass"); assertEquals(client.changeArchivePassword("username", "newpass"), detailsInArchiveDetails());
} }
@Test(expectedExceptions = {ResourceNotFoundException.class}) @Test(expectedExceptions = {ResourceNotFoundException.class})
@ -189,8 +191,9 @@ public class ArchiveClientExpectTest extends BaseRestClientExpectTest<GleSYSClie
ArchiveClient client = requestSendsResponse( ArchiveClient client = requestSendsResponse(
HttpRequest.builder().method("POST") HttpRequest.builder().method("POST")
.endpoint(URI.create("https://api.glesys.com/archive/changepassword/format/json")) .endpoint(URI.create("https://api.glesys.com/archive/changepassword/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("username", "username") .put("username", "username")
.put("password", "newpass").build())).build(), .put("password", "newpass").build())).build(),

View File

@ -24,8 +24,8 @@ import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.jclouds.glesys.domain.Archive;
import org.jclouds.glesys.domain.ArchiveAllowedArguments; import org.jclouds.glesys.domain.ArchiveAllowedArguments;
import org.jclouds.glesys.domain.ArchiveDetails;
import org.jclouds.glesys.internal.BaseGleSYSClientLiveTest; import org.jclouds.glesys.internal.BaseGleSYSClientLiveTest;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
@ -47,7 +47,7 @@ public class ArchiveClientLiveTest extends BaseGleSYSClientLiveTest {
super.setupContext(); super.setupContext();
client = gleContext.getApi().getArchiveClient(); client = gleContext.getApi().getArchiveClient();
archiveUser = gleContext.getIdentity().toLowerCase() + "_jcloudstest9"; archiveUser = gleContext.getIdentity().toLowerCase() + "_test9";
archiveCounter = new RetryablePredicate<Integer>( archiveCounter = new RetryablePredicate<Integer>(
new Predicate<Integer>() { new Predicate<Integer>() {
public boolean apply(Integer value){ public boolean apply(Integer value){
@ -97,10 +97,8 @@ public class ArchiveClientLiveTest extends BaseGleSYSClientLiveTest {
@Test(dependsOnMethods = "testCreateArchive") @Test(dependsOnMethods = "testCreateArchive")
public void testArchiveDetails() throws Exception { public void testArchiveDetails() throws Exception {
ArchiveDetails details = client.getArchiveDetails(archiveUser); Archive details = client.getArchive(archiveUser);
assertEquals(details.getUsername(), archiveUser); assertEquals(details.getUsername(), archiveUser);
assertNotNull(details.getFreeSize());
assertNotNull(details.getTotalSize());
} }
@Test(dependsOnMethods = "testCreateArchive") @Test(dependsOnMethods = "testCreateArchive")
@ -116,7 +114,7 @@ public class ArchiveClientLiveTest extends BaseGleSYSClientLiveTest {
assertTrue(new RetryablePredicate<String>( assertTrue(new RetryablePredicate<String>(
new Predicate<String>() { new Predicate<String>() {
public boolean apply(String value){ public boolean apply(String value){
return client.getArchiveDetails(archiveUser) != null && value.equals(client.getArchiveDetails(archiveUser).getTotalSize()); return client.getArchive(archiveUser) != null && value.equals(client.getArchive(archiveUser).getTotalSize());
} }
}, 30, 1, TimeUnit.SECONDS).apply("20 GB")); }, 30, 1, TimeUnit.SECONDS).apply("20 GB"));
} }

View File

@ -20,17 +20,22 @@ package org.jclouds.glesys.features;
import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; import static org.jclouds.io.Payloads.newUrlEncodedFormPayload;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.net.URI; import java.net.URI;
import java.util.Set; import java.util.Set;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.glesys.GleSYSClient; import org.jclouds.glesys.GleSYSClient;
import org.jclouds.glesys.domain.Domain; import org.jclouds.glesys.domain.Domain;
import org.jclouds.glesys.domain.DomainRecord; import org.jclouds.glesys.domain.DomainRecord;
import org.jclouds.glesys.internal.BaseGleSYSClientExpectTest;
import org.jclouds.glesys.options.AddDomainOptions; import org.jclouds.glesys.options.AddDomainOptions;
import org.jclouds.glesys.options.EditRecordOptions;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
@ -38,7 +43,7 @@ import org.jclouds.rest.internal.BaseRestClientExpectTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
@ -47,12 +52,7 @@ import com.google.common.collect.Iterables;
* @author Adam Lowe * @author Adam Lowe
*/ */
@Test(groups = "unit", testName = "DomainClientExpectTest") @Test(groups = "unit", testName = "DomainClientExpectTest")
public class DomainClientExpectTest extends BaseRestClientExpectTest<GleSYSClient> { public class DomainClientExpectTest extends BaseGleSYSClientExpectTest {
private DateService dateService = new SimpleDateFormatDateService();
public DomainClientExpectTest() {
provider = "glesys";
}
public void testListDomainsWhenResponseIs2xx() throws Exception { public void testListDomainsWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse( DomainClient client = requestSendsResponse(
@ -93,7 +93,7 @@ public class DomainClientExpectTest extends BaseRestClientExpectTest<GleSYSClien
.put("domainname", "testglesys.jclouds.org").build())).build(), .put("domainname", "testglesys.jclouds.org").build())).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/domain_list_records.json")).build()).getDomainClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResource("/domain_list_records.json")).build()).getDomainClient();
Set<DomainRecord> expected = ImmutableSortedSet.of( Set<DomainRecord> expected = ImmutableSet.of(
DomainRecord.builder().id("224538").domainname("testglesys.jclouds.org").host("@").type("NS").data("ns1.namesystem.se.").ttl(3600).build(), DomainRecord.builder().id("224538").domainname("testglesys.jclouds.org").host("@").type("NS").data("ns1.namesystem.se.").ttl(3600).build(),
DomainRecord.builder().id("224539").domainname("testglesys.jclouds.org").host("@").type("NS").data("ns2.namesystem.se.").ttl(3600).build(), DomainRecord.builder().id("224539").domainname("testglesys.jclouds.org").host("@").type("NS").data("ns2.namesystem.se.").ttl(3600).build(),
DomainRecord.builder().id("224540").domainname("testglesys.jclouds.org").host("@").type("NS").data("ns3.namesystem.se.").ttl(3600).build(), DomainRecord.builder().id("224540").domainname("testglesys.jclouds.org").host("@").type("NS").data("ns3.namesystem.se.").ttl(3600).build(),
@ -109,8 +109,8 @@ public class DomainClientExpectTest extends BaseRestClientExpectTest<GleSYSClien
assertEquals(actual, expected); assertEquals(actual, expected);
for(DomainRecord result : actual) { for (DomainRecord result : actual) {
for(DomainRecord expect : expected) { for (DomainRecord expect : expected) {
if (result.equals(expect)) { if (result.equals(expect)) {
assertEquals(result.toString(), expect.toString(), "Deep comparison using toString() failed!"); assertEquals(result.toString(), expect.toString(), "Deep comparison using toString() failed!");
} }
@ -130,24 +130,150 @@ public class DomainClientExpectTest extends BaseRestClientExpectTest<GleSYSClien
assertTrue(client.listDomains().isEmpty()); assertTrue(client.listDomains().isEmpty());
} }
public void testAddDomainRecordsWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/addrecord/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(payloadFromStringWithContentType("domainname=jclouds.org&type=A&host=jclouds.org&data=", MediaType.APPLICATION_FORM_URLENCODED))
.build(),
HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_record.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
assertEquals(client.addRecord("jclouds.org", "jclouds.org", "A", ""), recordInDomainRecord());
}
protected DomainRecord recordInDomainRecord() {
return DomainRecord.builder().id("256151").domainname("cl13016-domain.jclouds.org").host("test").type("A").data("127.0.0.1").ttl(3600).build();
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testAddDomainRecordsWhenResponseIs4xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/addrecord/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(payloadFromStringWithContentType("domainname=jclouds.org&type=A&host=jclouds.org&data=", MediaType.APPLICATION_FORM_URLENCODED))
.build(),
HttpResponse.builder().statusCode(404).build()).getDomainClient();
client.addRecord("jclouds.org", "jclouds.org", "A", "");
}
public void testEditDomainRecordsWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/updaterecord/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(payloadFromStringWithContentType("recordid=256151&host=somehost&ttl=1800", MediaType.APPLICATION_FORM_URLENCODED))
.build(),
HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_record.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
assertEquals(client.editRecord("256151", EditRecordOptions.Builder.host("somehost"), EditRecordOptions.Builder.ttl(1800)), recordInDomainRecord());
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testEditDomainRecordsWhenResponseIs4xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/updaterecord/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(payloadFromStringWithContentType("recordid=256151&host=somehost&ttl=1800", MediaType.APPLICATION_FORM_URLENCODED))
.build(),
HttpResponse.builder().statusCode(404).build()).getDomainClient();
client.editRecord("256151", EditRecordOptions.Builder.host("somehost"), EditRecordOptions.Builder.ttl(1800));
}
public void testDeleteDomainRecordsWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/deleterecord/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(payloadFromStringWithContentType("recordid=256151", MediaType.APPLICATION_FORM_URLENCODED))
.build(),
HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_record.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
client.deleteRecord("256151");
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testDeleteDomainRecordsWhenResponseIs4xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/deleterecord/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(payloadFromStringWithContentType("recordid=256151", MediaType.APPLICATION_FORM_URLENCODED))
.build(),
HttpResponse.builder().statusCode(404).build()).getDomainClient();
client.deleteRecord("256151");
}
public void testGetDomainWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/details/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("domainname", "cl66666_x").build())).build(),
HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
assertEquals(client.getDomain("cl66666_x"), domainInDomainDetails());
}
public void testGetDomainWhenResponseIs4xx() throws Exception {
DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/details/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("domainname", "cl66666_x").build())).build(),
HttpResponse.builder().statusCode(404).build())
.getDomainClient();
assertNull(client.getDomain("cl66666_x"));
}
protected Domain domainInDomainDetails() {
return Domain.builder().domainName("cl13016-domain.jclouds.org").createTime(dateService.iso8601SecondsDateParse("2012-06-24T11:52:49+02:00")).recordCount(9).build();
}
public void testAddDomainWhenResponseIs2xx() throws Exception { public void testAddDomainWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse( DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/add/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/add/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("domainname", "cl66666_x").build())).build(), .put("domainname", "cl66666_x").build())).build(),
HttpResponse.builder().statusCode(200).build()).getDomainClient(); HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
client.addDomain("cl66666_x"); assertEquals(client.addDomain("cl66666_x"), domainInDomainDetails());
} }
public void testAddDomainWithOptsWhenResponseIs2xx() throws Exception { public void testAddDomainWithOptsWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse( DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/add/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/add/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("domainname", "cl66666_x") .put("domainname", "cl66666_x")
.put("primarynameserver", "ns1.somewhere.x") .put("primarynameserver", "ns1.somewhere.x")
@ -158,31 +284,37 @@ public class DomainClientExpectTest extends BaseRestClientExpectTest<GleSYSClien
.put("retry", "1") .put("retry", "1")
.put("ttl", "1") .put("ttl", "1")
.build())).build(), .build())).build(),
HttpResponse.builder().statusCode(200).build()).getDomainClient(); HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
AddDomainOptions options = (AddDomainOptions) AddDomainOptions.Builder.primaryNameServer("ns1.somewhere.x") AddDomainOptions options = (AddDomainOptions) AddDomainOptions.Builder.primaryNameServer("ns1.somewhere.x")
.expire(1).minimum(1).refresh(1).responsiblePerson("Tester").retry(1).ttl(1); .expire(1).minimum(1).refresh(1).responsiblePerson("Tester").retry(1).ttl(1);
client.addDomain("cl66666_x", options); assertEquals(client.addDomain("cl66666_x", options), domainInDomainDetails());
} }
public void testEditDomainWhenResponseIs2xx() throws Exception { public void testEditDomainWhenResponseIs2xx() throws Exception {
DomainClient client = requestSendsResponse( DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/edit/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/edit/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("domainname", "x").build())).build(), .put("domainname", "x").build())).build(),
HttpResponse.builder().statusCode(200).build()).getDomainClient(); HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build())
.getDomainClient();
client.editDomain("x"); assertEquals(client.editDomain("x"), domainInDomainDetails());
} }
@Test(expectedExceptions = {ResourceNotFoundException.class}) @Test(expectedExceptions = {ResourceNotFoundException.class})
public void testEditDomainWhenResponseIs4xxThrows() throws Exception { public void testEditDomainWhenResponseIs4xxThrows() throws Exception {
DomainClient client = requestSendsResponse( DomainClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/edit/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/domain/edit/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder()
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("domainname", "x").build())).build(), .put("domainname", "x").build())).build(),
HttpResponse.builder().statusCode(404).build()).getDomainClient(); HttpResponse.builder().statusCode(404).build()).getDomainClient();

View File

@ -44,12 +44,12 @@ import com.google.common.base.Predicate;
*/ */
@Test(groups = "live", testName = "DomainClientLiveTest", singleThreaded = true) @Test(groups = "live", testName = "DomainClientLiveTest", singleThreaded = true)
public class DomainClientLiveTest extends BaseGleSYSClientLiveTest { public class DomainClientLiveTest extends BaseGleSYSClientLiveTest {
public final String testDomain = "glesystest.jclouds.org"; public String testDomain;
@BeforeGroups(groups = {"live"}) @BeforeGroups(groups = {"live"})
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
testDomain = identity.toLowerCase() + "-domain.jclouds.org";
client = gleContext.getApi().getDomainClient(); client = gleContext.getApi().getDomainClient();
domainCounter = new RetryablePredicate<Integer>( domainCounter = new RetryablePredicate<Integer>(
new Predicate<Integer>() { new Predicate<Integer>() {
@ -85,10 +85,19 @@ public class DomainClientLiveTest extends BaseGleSYSClientLiveTest {
private RetryablePredicate<Integer> domainCounter; private RetryablePredicate<Integer> domainCounter;
private RetryablePredicate<Integer> recordCounter; private RetryablePredicate<Integer> recordCounter;
@Test
public void testGetDomain() throws Exception {
Domain domain = client.getDomain(testDomain);
assertNotNull(domain);
assertEquals(domain.getDomainName(), testDomain);
assertNotNull(domain.getCreateTime());
}
@Test @Test
public void testEditDomain() throws Exception { public void testEditDomain() throws Exception {
client.editDomain(testDomain, DomainOptions.Builder.responsiblePerson("tester.jclouds.org")); client.editDomain(testDomain, DomainOptions.Builder.responsiblePerson("another-tester.jclouds.org."));
assertTrue(client.listDomains().contains(Domain.builder().domainName(testDomain).build())); Domain domain = client.getDomain(testDomain);
assertEquals(domain.getResponsiblePerson(), "another-tester.jclouds.org.");
} }
@Test @Test

View File

@ -24,24 +24,27 @@ import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.net.URI; import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Set; import java.util.Set;
import org.jclouds.glesys.GleSYSClient; import javax.ws.rs.core.MediaType;
import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAccount;
import org.jclouds.glesys.domain.EmailAlias;
import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.domain.EmailOverview;
import org.jclouds.glesys.domain.EmailOverviewDomain; import org.jclouds.glesys.domain.EmailOverviewDomain;
import org.jclouds.glesys.domain.EmailOverviewSummary; import org.jclouds.glesys.domain.EmailOverviewSummary;
import org.jclouds.glesys.domain.EmailQuota;
import org.jclouds.glesys.internal.BaseGleSYSClientExpectTest;
import org.jclouds.glesys.options.EditAccountOptions;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.rest.internal.BaseRestClientExpectTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
/** /**
* Tests annotation parsing of {@code EmailClient} * Tests annotation parsing of {@code EmailClient}
@ -49,10 +52,7 @@ import com.google.common.collect.ImmutableSet;
* @author Adam Lowe * @author Adam Lowe
*/ */
@Test(groups = "unit", testName = "EmailAsyncClientTest") @Test(groups = "unit", testName = "EmailAsyncClientTest")
public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient> { public class EmailClientExpectTest extends BaseGleSYSClientExpectTest {
public EmailClientExpectTest() {
provider = "glesys";
}
public void testListWhenResponseIs2xx() throws Exception { public void testListWhenResponseIs2xx() throws Exception {
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
@ -61,18 +61,22 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
.put("Accept", "application/json") .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("domain", "test").build())).build(), ImmutableMultimap.<String, String>builder().put("domainname", "cl13016.test.jclouds.org").build())).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailClient();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); EmailAccount.Builder builder = EmailAccount.builder().quota(EmailQuota.builder().max(200).unit("MB").build()).antispamLevel(3).antiVirus(true).autoRespond(false).autoRespondSaveEmail(true);
EmailAccount.Builder builder = EmailAccount.builder().quota("200 MB").usedQuota("0 MB").antispamLevel(3).antiVirus(true).autoRespond(false).autoRespondSaveEmail(true).autoRespondMessage("false");
Set<EmailAccount> expected = Set<EmailAccount> expected =
ImmutableSet.of( ImmutableSet.of(
builder.account("test@adamlowe.net").created(dateFormat.parse("2011-12-22T12:13:14")).modified(dateFormat.parse("2011-12-22T12:13:35")).build(), builder.account("test1@cl13016.test.jclouds.org").antispamLevel(3)
builder.account("test2@adamlowe.net").created(dateFormat.parse("2011-12-22T12:14:29")).modified(dateFormat.parse("2011-12-22T12:14:31")).build() .created(dateService.iso8601SecondsDateParse("2012-06-24T11:53:45+02:00")).build(),
builder.account("test@cl13016.test.jclouds.org").antispamLevel(3)
.created(dateService.iso8601SecondsDateParse("2012-06-21T11:26:09+02:00"))
.modified(dateService.iso8601SecondsDateParse("2012-06-24T11:53:48+02:00")).build()
); );
assertEquals(client.listAccounts("test"), expected); Set<EmailAccount> actual = client.listAccounts("cl13016.test.jclouds.org");
assertEquals(actual, expected);
assertEquals(Iterables.get(actual, 0).toString(), Iterables.get(expected, 0).toString());
} }
public void testListWhenResponseIs404IsEmpty() throws Exception { public void testListWhenResponseIs404IsEmpty() throws Exception {
@ -82,12 +86,40 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
.put("Accept", "application/json") .put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("domain", "test").build())).build(), ImmutableMultimap.<String, String>builder().put("domainname", "test").build())).build(),
HttpResponse.builder().statusCode(404).build()).getEmailClient(); HttpResponse.builder().statusCode(404).build()).getEmailClient();
assertTrue(client.listAccounts("test").isEmpty()); assertTrue(client.listAccounts("test").isEmpty());
} }
public void testListAliasesWhenResponseIs2xx() throws Exception {
EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/list/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("domainname", "cl13016.test.jclouds.org").build())).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailClient();
EmailAlias expected = EmailAlias.builder().alias("test2@cl13016.test.jclouds.org").forwardTo("test2@cl13016.test.jclouds.org").build();
EmailAlias actual = Iterables.getOnlyElement(client.listAliases("cl13016.test.jclouds.org"));
assertEquals(actual, expected);
}
public void testListAliasesWhenResponseIs404IsEmpty() throws Exception {
EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/list/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("domainname", "test").build())).build(),
HttpResponse.builder().statusCode(404).build()).getEmailClient();
assertTrue(client.listAliases("test").isEmpty());
}
public void testOverviewWhenResponseIs2xx() throws Exception { public void testOverviewWhenResponseIs2xx() throws Exception {
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/overview/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/overview/format/json"))
@ -97,8 +129,8 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
.build(), .build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_overview.json")).build()).getEmailClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_overview.json")).build()).getEmailClient();
EmailOverviewSummary summary = EmailOverviewSummary.builder().accounts(2).maxAccounts(50).aliases(0).maxAliases(1000).build(); EmailOverviewSummary summary = EmailOverviewSummary.builder().accounts(2).maxAccounts(50).aliases(1).maxAliases(1000).build();
EmailOverviewDomain domain = EmailOverviewDomain.builder().domain("adamlowe.net").accounts(2).aliases(0).build(); EmailOverviewDomain domain = EmailOverviewDomain.builder().domain("cl13016.test.jclouds.org").accounts(2).aliases(0).build();
EmailOverview expected = EmailOverview.builder().summary(summary).domains(domain).build(); EmailOverview expected = EmailOverview.builder().summary(summary).domains(domain).build();
assertEquals(client.getEmailOverview(), expected); assertEquals(client.getEmailOverview(), expected);
@ -120,15 +152,61 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createaccount/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createaccount/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailaccount", "test@jclouds.org") .put("emailaccount", "test@jclouds.org")
.put("password", "newpass") .put("password", "newpass")
.build())) .build()))
.build(), .build(),
HttpResponse.builder().statusCode(200).build()).getEmailClient(); HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/email_details.json", MediaType.APPLICATION_JSON)).build())
.getEmailClient();
client.createAccount("test@jclouds.org", "newpass"); assertEquals(client.createAccount("test@jclouds.org", "newpass").toString(), getEmailAccountInDetails().toString());
}
public void testEditAccountWhenResponseIs2xx() throws Exception {
EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/editaccount/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailaccount", "test@jclouds.org")
.put("password", "anotherpass")
.build()))
.build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/email_details.json", MediaType.APPLICATION_JSON)).build())
.getEmailClient();
assertEquals(client.editAccount("test@jclouds.org", EditAccountOptions.Builder.password("anotherpass")).toString(), getEmailAccountInDetails().toString());
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testEditAccountWhenResponseIs4xx() throws Exception {
EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/editaccount/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailaccount", "test@jclouds.org")
.put("password", "anotherpass")
.build()))
.build(),
HttpResponse.builder().statusCode(404).build())
.getEmailClient();
assertEquals(client.editAccount("test@jclouds.org", EditAccountOptions.Builder.password("anotherpass")).toString(), getEmailAccountInDetails().toString());
}
private EmailAccount getEmailAccountInDetails() {
return EmailAccount.builder().account("test@CL13016.jclouds.org")
.antispamLevel(3)
.antiVirus(true)
.autoRespondSaveEmail(true)
.created(dateService.iso8601SecondsDateParse("2012-06-20T12:01:01+02:00"))
.quota(EmailQuota.builder().max(200).unit("MB").build()).build();
} }
@Test(expectedExceptions = {ResourceNotFoundException.class}) @Test(expectedExceptions = {ResourceNotFoundException.class})
@ -136,6 +214,7 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createaccount/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createaccount/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailaccount", "test@jclouds.org") .put("emailaccount", "test@jclouds.org")
@ -151,6 +230,7 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createalias/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createalias/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailalias", "test2@jclouds.org") .put("emailalias", "test2@jclouds.org")
@ -167,6 +247,7 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createalias/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/createalias/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailalias", "test2@jclouds.org") .put("emailalias", "test2@jclouds.org")
@ -182,6 +263,7 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/editalias/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/editalias/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailalias", "test2@jclouds.org") .put("emailalias", "test2@jclouds.org")
@ -198,6 +280,7 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
EmailClient client = requestSendsResponse( EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/editalias/format/json")) HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/editalias/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder()
.put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder() .payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("emailalias", "test2@jclouds.org") .put("emailalias", "test2@jclouds.org")
@ -208,4 +291,33 @@ public class EmailClientExpectTest extends BaseRestClientExpectTest<GleSYSClient
client.editAlias("test2@jclouds.org", "test@jclouds.org"); client.editAlias("test2@jclouds.org", "test@jclouds.org");
} }
public void testDeleteWhenResponseIs2xx() throws Exception {
EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/delete/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("email", "test2@jclouds.org")
.build()))
.build(),
HttpResponse.builder().statusCode(200).build()).getEmailClient();
client.delete("test2@jclouds.org");
}
@Test(expectedExceptions = {ResourceNotFoundException.class})
public void testDeleteWhenResponseIs4xxThrows() throws Exception {
EmailClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(URI.create("https://api.glesys.com/email/delete/format/json"))
.headers(ImmutableMultimap.<String, String>builder()
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(ImmutableMultimap.<String, String>builder()
.put("email", "test2@jclouds.org")
.build()))
.build(),
HttpResponse.builder().statusCode(404).build()).getEmailClient();
client.delete("test2@jclouds.org");
}
} }

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.glesys.features; package org.jclouds.glesys.features;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -26,11 +27,11 @@ import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAccount;
import org.jclouds.glesys.domain.EmailAlias;
import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.domain.EmailOverview;
import org.jclouds.glesys.domain.EmailOverviewDomain; import org.jclouds.glesys.domain.EmailOverviewDomain;
import org.jclouds.glesys.internal.BaseGleSYSClientLiveTest; import org.jclouds.glesys.internal.BaseGleSYSClientWithAServerLiveTest;
import org.jclouds.glesys.options.CreateAccountOptions; import org.jclouds.glesys.options.CreateAccountOptions;
import org.jclouds.glesys.options.DestroyServerOptions;
import org.jclouds.glesys.options.EditAccountOptions; import org.jclouds.glesys.options.EditAccountOptions;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
@ -38,6 +39,7 @@ import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/** /**
* Tests behavior of {@code EmailClient} * Tests behavior of {@code EmailClient}
@ -45,15 +47,13 @@ import com.google.common.base.Predicate;
* @author Adam Lowe * @author Adam Lowe
*/ */
@Test(groups = "live", testName = "EmailClientLiveTest", singleThreaded = true) @Test(groups = "live", testName = "EmailClientLiveTest", singleThreaded = true)
public class EmailClientLiveTest extends BaseGleSYSClientLiveTest { public class EmailClientLiveTest extends BaseGleSYSClientWithAServerLiveTest {
@BeforeGroups(groups = {"live"}) @BeforeGroups(groups = {"live"})
public void setupContext() { public void setupDomains() {
super.setupContext(); testDomain = identity + ".test.jclouds.org";
client = gleContext.getApi().getEmailClient(); client = gleContext.getApi().getEmailClient();
serverId = createServer("test-email-jclouds").getServerId();
createDomain(testDomain); createDomain(testDomain);
emailAccountCounter = new RetryablePredicate<Integer>( emailAccountCounter = new RetryablePredicate<Integer>(
@ -61,24 +61,26 @@ public class EmailClientLiveTest extends BaseGleSYSClientLiveTest {
public boolean apply(Integer value) { public boolean apply(Integer value) {
return client.listAccounts(testDomain).size() == value; return client.listAccounts(testDomain).size() == value;
} }
}, 90, 5, TimeUnit.SECONDS); }, 180, 5, TimeUnit.SECONDS);
assertTrue(emailAccountCounter.apply(0)); assertTrue(emailAccountCounter.apply(0));
try {
client.delete("test2@" + testDomain);
} catch(Exception e) {
}
} }
@AfterGroups(groups = {"live"}) @AfterGroups(groups = {"live"})
public void tearDownContext() { public void tearDownDomains() {
client.delete("test@" + testDomain); client.delete("test@" + testDomain);
client.delete("test1@" + testDomain); client.delete("test1@" + testDomain);
assertTrue(emailAccountCounter.apply(0)); assertTrue(emailAccountCounter.apply(0));
gleContext.getApi().getDomainClient().deleteDomain(testDomain); gleContext.getApi().getDomainClient().deleteDomain(testDomain);
gleContext.getApi().getServerClient().destroyServer(serverId, DestroyServerOptions.Builder.discardIp());
super.tearDownContext();
} }
private EmailClient client; private EmailClient client;
private String serverId; private String testDomain;
private final String testDomain = "email-test.jclouds.org";
private RetryablePredicate<Integer> emailAccountCounter; private RetryablePredicate<Integer> emailAccountCounter;
@Test @Test
@ -95,15 +97,25 @@ public class EmailClientLiveTest extends BaseGleSYSClientLiveTest {
@Test(dependsOnMethods = "testCreateEmail") @Test(dependsOnMethods = "testCreateEmail")
public void testAliases() { public void testAliases() {
client.createAlias("test2@" + testDomain, "test@" + testDomain); assertTrue(client.listAliases(testDomain).isEmpty());
EmailAlias alias = client.createAlias("test2@" + testDomain, "test@" + testDomain);
assertEquals(alias.getAlias(), "test2@" + testDomain);
assertEquals(alias.getForwardTo(), "test@" + testDomain);
EmailAlias aliasFromList = Iterables.getOnlyElement(client.listAliases(testDomain));
assertEquals(aliasFromList, alias);
EmailOverview overview = client.getEmailOverview(); EmailOverview overview = client.getEmailOverview();
assertTrue(overview.getSummary().getAliases() == 1); assertTrue(overview.getSummary().getAliases() == 1);
// TODO verify the result of editing the alias alias = client.editAlias("test2@" + testDomain, "test1@" + testDomain);
client.editAlias("test2@" + testDomain, "test1@" + testDomain);
overview = client.getEmailOverview(); overview = client.getEmailOverview();
assertTrue(overview.getSummary().getAliases() == 1); assertTrue(overview.getSummary().getAliases() == 1);
aliasFromList = Iterables.getOnlyElement(client.listAliases(testDomain));
assertEquals(aliasFromList, alias);
client.delete("test2@" + testDomain); client.delete("test2@" + testDomain);
overview = client.getEmailOverview(); overview = client.getEmailOverview();
assertTrue(overview.getSummary().getAliases() == 0); assertTrue(overview.getSummary().getAliases() == 0);
@ -113,8 +125,8 @@ public class EmailClientLiveTest extends BaseGleSYSClientLiveTest {
public void testOverview() throws Exception { public void testOverview() throws Exception {
EmailOverview overview = client.getEmailOverview(); EmailOverview overview = client.getEmailOverview();
assertNotNull(overview.getSummary()); assertNotNull(overview.getSummary());
assertTrue(overview.getSummary().getAccounts() >= 1); assertTrue(overview.getSummary().getAccounts() > 0);
assertTrue(overview.getSummary().getAliases() == 0); assertTrue(overview.getSummary().getAliases() > -1);
assertTrue(overview.getSummary().getMaxAccounts() > 0); assertTrue(overview.getSummary().getMaxAccounts() > 0);
assertTrue(overview.getSummary().getMaxAliases() > 0); assertTrue(overview.getSummary().getMaxAliases() > 0);
assertNotNull(overview.getDomains()); assertNotNull(overview.getDomains());
@ -135,7 +147,7 @@ public class EmailClientLiveTest extends BaseGleSYSClientLiveTest {
Set<EmailAccount> accounts = client.listAccounts(testDomain); Set<EmailAccount> accounts = client.listAccounts(testDomain);
for (EmailAccount account : accounts) { for (EmailAccount account : accounts) {
if (account.getAccount().equals("test@" + testDomain)) { if (account.getAccount().equals("test@" + testDomain)) {
assertTrue(account.getAntiVirus()); assertTrue(account.isAntiVirus());
} }
} }
@ -144,7 +156,7 @@ public class EmailClientLiveTest extends BaseGleSYSClientLiveTest {
accounts = client.listAccounts(testDomain); accounts = client.listAccounts(testDomain);
for (EmailAccount account : accounts) { for (EmailAccount account : accounts) {
if (account.getAccount().equals("test@" + testDomain)) { if (account.getAccount().equals("test@" + testDomain)) {
assertFalse(account.getAntiVirus()); assertFalse(account.isAntiVirus());
} }
} }
} }

View File

@ -1,62 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.glesys.features;
import java.io.IOException;
import java.lang.reflect.Method;
import org.jclouds.glesys.internal.BaseGleSYSAsyncClientTest;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseFirstJsonValueNamed;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
import com.google.inject.TypeLiteral;
/**
* Tests annotation parsing of {@code IpAsyncClient}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "IpAsyncClientTest")
public class IpAsyncClientTest extends BaseGleSYSAsyncClientTest<IpAsyncClient> {
public void testGetIpDetails() throws SecurityException, NoSuchMethodException, IOException {
Method method = IpAsyncClient.class.getMethod("getIpDetails", String.class);
HttpRequest request = processor.createRequest(method, "31.192.227.37");
assertRequestLineEquals(request,
"GET https://api.glesys.com/ip/details/ipaddress/31.192.227.37/format/json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, "application/xml", false);
assertResponseParserClassEquals(method, request, ParseFirstJsonValueNamed.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request);
}
@Override
protected TypeLiteral<RestAnnotationProcessor<IpAsyncClient>> createTypeLiteral() {
return new TypeLiteral<RestAnnotationProcessor<IpAsyncClient>>() {
};
}
}

View File

@ -18,234 +18,345 @@
*/ */
package org.jclouds.glesys.features; package org.jclouds.glesys.features;
import static java.util.Arrays.asList;
import static java.util.Collections.emptySet; import static java.util.Collections.emptySet;
import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; import static org.jclouds.io.Payloads.newUrlEncodedFormPayload;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail; import static org.testng.Assert.assertTrue;
import static org.testng.collections.Sets.newHashSet;
import java.net.URI; import java.net.URI;
import java.util.Set;
import org.jclouds.glesys.GleSYSClient; import javax.ws.rs.core.MediaType;
import org.jclouds.glesys.domain.Cost;
import org.jclouds.glesys.domain.IpDetails; import org.jclouds.glesys.domain.IpDetails;
import org.jclouds.glesys.internal.BaseGleSYSClientExpectTest;
import org.jclouds.glesys.parse.ParseIpAddressFromResponseTest;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.rest.internal.BaseRestClientExpectTest; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ResourceNotFoundException;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
/** /**
* Allows us to test a client via its side effects. * Allows us to test a client via its side effects.
* *
* @author Adrian Cole * @author Adrian Cole, Adam Lowe
*/ */
@Test(groups = "unit", testName = "IpClientExpectTest") @Test(groups = "unit", testName = "IpClientExpectTest")
public class IpClientExpectTest extends BaseRestClientExpectTest<GleSYSClient> { public class IpClientExpectTest extends BaseGleSYSClientExpectTest {
public IpClientExpectTest() {
provider = "glesys"; public void testListIpsWhenResponseIs2xx() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.glesys.com/ip/listown/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_list_own.json")).build())
.getIpClient();
IpDetails.Builder builder = IpDetails.builder().datacenter("Falkenberg").version4().reserved(true)
.platform("OpenVZ")
.nameServers("79.99.4.100", "79.99.4.101")
.cost(Cost.builder().amount(2.0).currency("EUR").timePeriod("month").build());
assertEquals(client.listIps().toString(), ImmutableSet.of(
builder.ptr("31-192-230-68-static.serverhotell.net.").address("31.192.230.68").serverId(null).build(),
builder.ptr("31-192-231-148-static.serverhotell.net.").address("31.192.231.148").serverId("vz1609110").build()).toString());
}
public void testListIpsWhenResponseIs4xxReturnsEmpty() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.glesys.com/ip/listown/format/json")).headers(
ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put(
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(),
HttpResponse.builder().statusCode(404).build()).getIpClient();
assertTrue(client.listIps().isEmpty());
} }
public void testGetIpDetailsWhenResponseIs2xx() { public void testGetIpDetailsWhenResponseIs2xx() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("GET").endpoint( HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.glesys.com/ip/details/ipaddress/31.192.227.37/format/json")).headers( URI.create("https://api.glesys.com/ip/details/ipaddress/31.192.227.113/format/json"))
ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(), .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_get_details.json")).build()) HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_get_details.json")).build())
.getIpClient(); .getIpClient();
assertEquals(client.getIpDetails("31.192.227.37"), IpDetails.builder().datacenter("Falkenberg").ipversion("4") assertEquals(client.getIp("31.192.227.113"), getIpInIpDetails());
.platform("OpenVZ").ptr("31-192-227-37-static.serverhotell.net.").build()); }
protected IpDetails getIpInIpDetails() {
return IpDetails.builder().datacenter("Falkenberg").version4()
.platform("OpenVZ").ptr("31-192-227-113-static.serverhotell.net.")
.nameServers("79.99.4.100", "79.99.4.101")
.address("31.192.227.113")
.cost(Cost.builder().amount(2.0).currency("EUR").timePeriod("month").build()).build();
} }
public void testGetIpDetailsWhenResponseIs4xxReturnsNull() { public void testGetIpDetailsWhenResponseIs4xxReturnsNull() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("GET").endpoint( HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.glesys.com/ip/details/ipaddress/31.192.227.37/format/json")).headers( URI.create("https://api.glesys.com/ip/details/ipaddress/31.192.227.37/format/json")).headers(
ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put( ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put(
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(), "Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(),
HttpResponse.builder().statusCode(404).build()).getIpClient(); HttpResponse.builder().statusCode(404).build()).getIpClient();
assertEquals(client.getIpDetails("31.192.227.37"), null);
assertEquals(client.getIp("31.192.227.37"), null);
} }
public void testTakeWhenResponseIs2xx() { public void testTakeWhenResponseIs2xx() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/take/format/json")) URI.create("https://api.glesys.com/ip/take/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build() ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build()
)).build(), )).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_take.json")).build()) HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_take.json")).build())
.getIpClient(); .getIpClient();
client.take("46.21.105.186"); client.take("46.21.105.186");
} }
@Test(expectedExceptions = HttpResponseException.class)
public void testTakeWhenResponseIs4xxThrowsResponseException() { public void testTakeWhenResponseIs4xxThrowsResponseException() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/take/format/json")) URI.create("https://api.glesys.com/ip/take/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build() ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build()
)).build(), )).build(),
HttpResponse.builder().statusCode(400).build()) HttpResponse.builder().statusCode(400).build()).getIpClient();
.getIpClient(); client.take("46.21.105.186");
try {
client.take("46.21.105.186");
fail();
} catch (HttpResponseException e) {
// Expected
}
} }
public void testReleaseWhenResponseIs2xx() { public void testReleaseWhenResponseIs2xx() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/release/format/json")) URI.create("https://api.glesys.com/ip/release/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build() ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build()
)).build(), )).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_release.json")).build()) HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_release.json")).build())
.getIpClient(); .getIpClient();
client.release("46.21.105.186"); client.release("46.21.105.186");
} }
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testReleaseWhenResponseIs4xxThrowsResponseException() { public void testReleaseWhenResponseIs4xxThrowsResponseException() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/release/format/json")) URI.create("https://api.glesys.com/ip/release/format/json"))
.headers(ImmutableMultimap.<String, String>builder() .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build() ImmutableMultimap.<String, String>builder().put("ipaddress", "46.21.105.186").build()
)).build(), )).build(),
HttpResponse.builder().statusCode(400).build()) HttpResponse.builder().statusCode(404).build())
.getIpClient(); .getIpClient();
try { client.release("46.21.105.186");
client.release("46.21.105.186");
fail();
} catch (HttpResponseException e) {
// Expected
}
} }
public void testListFreeWhenResponseIs2xx() { public void testListFreeWhenResponseIs2xx() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("GET").endpoint( HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.glesys.com/ip/listfree/ipversion/4/datacenter/Falkenberg/platform/OpenVZ/format/json")) URI.create("https://api.glesys.com/ip/listfree/ipversion/4/datacenter/Falkenberg/platform/OpenVZ/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put(
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(), "Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_list_free.json")).build()) HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_list_free.json")).build())
.getIpClient(); .getIpClient();
Set<Object> expectedIps = newHashSet(); assertEquals(client.listFree(4, "Falkenberg", "OpenVZ"), ParseIpAddressFromResponseTest.EXPECTED_IPS);
expectedIps.addAll(asList("31.192.226.131", "31.192.226.133"));
assertEquals(client.listFree("4", "Falkenberg", "OpenVZ"), expectedIps);
} }
public void testListFreeWhenResponseIs404ReturnsEmptySet() { public void testListFreeWhenResponseIs404ReturnsEmptySet() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("GET").endpoint( HttpRequest.builder().method("GET").endpoint(
URI.create("https://api.glesys.com/ip/listfree/ipversion/4/datacenter/Falkenberg/platform/OpenVZ/format/json")) URI.create("https://api.glesys.com/ip/listfree/ipversion/6/datacenter/Falkenberg/platform/OpenVZ/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json").put(
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(), "Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()).build(),
HttpResponse.builder().statusCode(404).build()) HttpResponse.builder().statusCode(404).build())
.getIpClient(); .getIpClient();
assertEquals(client.listFree("4", "Falkenberg", "OpenVZ"), emptySet()); assertEquals(client.listFree(6, "Falkenberg", "OpenVZ"), emptySet());
} }
public void testAddWhenResponseIs2xx() { public void testAddWhenResponseIs2xx() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/add/format/json")) URI.create("https://api.glesys.com/ip/add/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder() ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37") .put("ipaddress", "31.192.227.37")
.put("serverid", "vz1946889").build())).build(), .put("serverid", "vz1946889").build())).build(),
HttpResponse.builder().statusCode(200).build()) HttpResponse.builder().statusCode(200).build())
.getIpClient(); .getIpClient();
client.addIpToServer("31.192.227.37", "vz1946889"); client.addIpToServer("31.192.227.37", "vz1946889");
} }
@Test(expectedExceptions = AuthorizationException.class)
public void testAddWhenResponseIs4xxThrowsHttpException() { public void testAddWhenResponseIs4xxThrowsHttpException() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/add/format/json")) URI.create("https://api.glesys.com/ip/add/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder() ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37") .put("ipaddress", "31.192.227.37")
.put("serverid", "vz1946889") .put("serverid", "vz1946889")
.build())).build(), .build())).build(),
HttpResponse.builder().statusCode(400).build()) HttpResponse.builder().statusCode(401).build())
.getIpClient(); .getIpClient();
client.addIpToServer("31.192.227.37", "vz1946889");
try {
client.addIpToServer("31.192.227.37", "vz1946889");
fail();
} catch (HttpResponseException e) {
// Expected
}
} }
public void testRemoveWhenResponseIs2xx() { public void testRemoveWhenResponseIs2xx() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/remove/format/json")) URI.create("https://api.glesys.com/ip/remove/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder() ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37") .put("ipaddress", "31.192.227.37")
.put("serverid", "vz1946889").build())).build(), .put("serverid", "vz1946889").build())).build(),
HttpResponse.builder().statusCode(200).build()) HttpResponse.builder().statusCode(200).build())
.getIpClient(); .getIpClient();
client.removeIpFromServer("31.192.227.37", "vz1946889"); client.removeIpFromServer("31.192.227.37", "vz1946889");
} }
@Test(expectedExceptions = HttpResponseException.class)
public void testRemoveWhenResponseIs4xxThrowsHttpException() { public void testRemoveWhenResponseIs4xxThrowsHttpException() {
IpClient client = requestSendsResponse( IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint( HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/remove/format/json")) URI.create("https://api.glesys.com/ip/remove/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put( .headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
"Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build()) .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload( .payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder() ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37") .put("ipaddress", "31.192.227.37")
.put("serverid", "vz1946889").build())).build(), .put("serverid", "vz1946889").build())).build(),
HttpResponse.builder().statusCode(400).build()) HttpResponse.builder().statusCode(400).build())
.getIpClient(); .getIpClient();
try { client.removeIpFromServer("31.192.227.37", "vz1946889");
client.removeIpFromServer("31.192.227.37", "vz1946889");
fail();
} catch (HttpResponseException e) {
// Expected
}
} }
public void testRemoveAndReleaseWhenResponseIs2xx() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/remove/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder()
.put("release", "true")
.put("ipaddress", "31.192.227.37")
.put("serverid", "vz1946889").build())).build(),
HttpResponse.builder().statusCode(200).build())
.getIpClient();
client.removeIpFromServerAndRelease("31.192.227.37", "vz1946889");
}
@Test(expectedExceptions = HttpResponseException.class)
public void testRemoveAndReleaseWhenResponseIs4xxThrowsHttpException() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/remove/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder()
.put("release", "true")
.put("ipaddress", "31.192.227.37")
.put("serverid", "vz1946889").build())).build(),
HttpResponse.builder().statusCode(400).build())
.getIpClient();
client.removeIpFromServerAndRelease("31.192.227.37", "vz1946889");
}
public void testSetPrtWhenResponseIs2xx() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/setptr/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37")
.put("data", "sommeptr.").build())).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/ip_get_details.json", MediaType.APPLICATION_JSON)).build())
.getIpClient();
assertEquals(client.setPtr("31.192.227.37", "sommeptr."), getIpInIpDetails());
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testSetPtrWhenResponseIs4xxThrowsHttpException() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/setptr/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37")
.put("data", "sommeptr.").build())).build(),
HttpResponse.builder().statusCode(404).build())
.getIpClient();
client.setPtr("31.192.227.37", "sommeptr.");
}
public void testResetPrtWhenResponseIs2xx() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/resetptr/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37").build())).build(),
HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/ip_get_details.json", MediaType.APPLICATION_JSON)).build())
.getIpClient();
assertEquals(client.resetPtr("31.192.227.37"), getIpInIpDetails());
}
@Test(expectedExceptions = AuthorizationException.class)
public void testResetPtrWhenResponseIs4xxThrowsHttpException() {
IpClient client = requestSendsResponse(
HttpRequest.builder().method("POST").endpoint(
URI.create("https://api.glesys.com/ip/resetptr/format/json"))
.headers(ImmutableMultimap.<String, String>builder().put("Accept", "application/json")
.put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build())
.payload(newUrlEncodedFormPayload(
ImmutableMultimap.<String, String>builder()
.put("ipaddress", "31.192.227.37").build())).build(),
HttpResponse.builder().statusCode(401).build())
.getIpClient();
client.resetPtr("31.192.227.37");
}
} }

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