JCLOUDS-716: Remove Rackspace First-Gen Cloud Servers

This commit is contained in:
Everett Toews 2014-11-18 11:50:01 -06:00
parent 60ba755219
commit 162226b8a9
107 changed files with 0 additions and 9318 deletions

View File

@ -1,6 +0,0 @@
#
# The jclouds API for Rackspace's Cloud Server (http://www.rackspacecloud.com/cloud_hosting_products/servers/).
#
# TODO: Implementation status.
# TODO: Supported features.
# TODO: Usage example.

View File

@ -1,131 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF 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.apache.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.apache.jclouds.api</groupId>
<artifactId>cloudservers</artifactId>
<name>jclouds cloudservers api</name>
<description>jclouds components to access an implementation of CloudServers</description>
<packaging>bundle</packaging>
<properties>
<test.cloudservers.endpoint>https://auth.api.rackspacecloud.com</test.cloudservers.endpoint>
<test.cloudservers.api-version>1.0</test.cloudservers.api-version>
<test.cloudservers.build-version />
<test.cloudservers.identity>${test.rackspace.identity}</test.cloudservers.identity>
<test.cloudservers.credential>${test.rackspace.credential}</test.cloudservers.credential>
<test.cloudservers.template />
<jclouds.osgi.export>org.jclouds.cloudservers*;version="${project.version}"</jclouds.osgi.export>
<jclouds.osgi.import>
org.jclouds.compute.internal;version="${project.version}",
org.jclouds.rest.internal;version="${project.version}",
org.jclouds*;version="${project.version}",
*
</jclouds.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.jclouds.common</groupId>
<artifactId>openstack-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.common</groupId>
<artifactId>openstack-common</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-sshj</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.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.cloudstack.endpoint>${test.cloudstack.endpoint}</test.cloudstack.endpoint>
<test.cloudstack.api-version>${test.cloudstack.api-version}</test.cloudstack.api-version>
<test.cloudstack.build-version>${test.cloudstack.build-version}</test.cloudstack.build-version>
<test.cloudstack.identity>${test.cloudstack.identity}</test.cloudstack.identity>
<test.cloudstack.credential>${test.cloudstack.credential}</test.cloudstack.credential>
<test.cloudstack.template>${test.cloudstack.template}</test.cloudstack.template>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,78 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers;
import static org.jclouds.reflect.Reflection2.typeToken;
import java.net.URI;
import java.util.Properties;
import org.jclouds.cloudservers.compute.config.CloudServersComputeServiceContextModule;
import org.jclouds.cloudservers.config.CloudServersHttpApiModule;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.rest.internal.BaseHttpApiMetadata;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
public class CloudServersApiMetadata extends BaseHttpApiMetadata {
@Override
public Builder toBuilder() {
return new Builder().fromApiMetadata(this);
}
public CloudServersApiMetadata() {
this(new Builder());
}
protected CloudServersApiMetadata(Builder builder) {
super(builder);
}
public static Properties defaultProperties() {
Properties properties = BaseHttpApiMetadata.defaultProperties();
return properties;
}
public static class Builder extends BaseHttpApiMetadata.Builder<CloudServersClient, Builder> {
protected Builder() {
super(CloudServersClient.class);
id("cloudservers")
.name("Rackspace Cloud Servers API")
.identityName("Username")
.credentialName("API Key")
.documentation(URI.create("http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide/content/ch01.html"))
.version("1.0")
.defaultEndpoint("https://auth.api.rackspacecloud.com")
.defaultProperties(CloudServersApiMetadata.defaultProperties())
.view(typeToken(ComputeServiceContext.class))
.defaultModules(ImmutableSet.<Class<? extends Module>>of(CloudServersHttpApiModule.class, CloudServersComputeServiceContextModule.class));
}
@Override
public CloudServersApiMetadata build() {
return new CloudServersApiMetadata(this);
}
@Override
protected Builder self() {
return this;
}
}
}

View File

@ -1,554 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;
import static org.jclouds.Fallbacks.FalseOnNotFoundOr404;
import static org.jclouds.Fallbacks.NullOnNotFoundOr404;
import static org.jclouds.Fallbacks.VoidOnNotFoundOr404;
import java.io.Closeable;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import org.jclouds.cloudservers.binders.BindBackupScheduleToJsonPayload;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.cloudservers.domain.Image;
import org.jclouds.cloudservers.domain.Limits;
import org.jclouds.cloudservers.domain.RebootType;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.SharedIpGroup;
import org.jclouds.cloudservers.options.CreateServerOptions;
import org.jclouds.cloudservers.options.CreateSharedIpGroupOptions;
import org.jclouds.cloudservers.options.ListOptions;
import org.jclouds.cloudservers.options.RebuildServerOptions;
import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest;
import org.jclouds.openstack.services.Compute;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.Fallback;
import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.Payload;
import org.jclouds.rest.annotations.PayloadParam;
import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.Unwrap;
/**
* Provides access to Cloud Servers via their REST API.
*
* @deprecated The Rackspace First-Gen Cloud Servers product has been deprecated. Please refer to the
* <a href="http://jclouds.apache.org/guides/rackspace">Rackspace Getting Started Guide</a>
* for accessing the Rackspace Cloud. This API will be removed in 2.0.
*/
@Deprecated
@RequestFilters({ AuthenticateRequest.class, AddTimestampQuery.class })
@Endpoint(Compute.class)
public interface CloudServersClient extends Closeable {
/**
* All accounts, by default, have a preconfigured set of thresholds (or limits) to manage
* capacity and prevent abuse of the system. The system recognizes two kinds of limits: rate
* limits and absolute limits. Rate limits are thresholds that are reset after a certain amount
* of time passes. Absolute limits are fixed.
*
* @return limits on the account
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/limits")
@Fallback(NullOnNotFoundOr404.class)
Limits getLimits();
/**
*
* List all servers (IDs and names only)
*
* This operation provides a list of servers associated with your identity. Servers that have
* been deleted are not included in this list.
* <p/>
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@Fallback(EmptySetOnNotFoundOr404.class)
Set<Server> listServers(ListOptions... options);
/**
*
* This operation returns details of the specified server.
*
* @return null, if the server is not found
* @see Server
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Fallback(NullOnNotFoundOr404.class)
@Path("/servers/{id}")
Server getServer(@PathParam("id") int id);
/**
*
* This operation deletes a cloud server instance from the system.
* <p/>
* Note: When a server is deleted, all images created from that server are also removed.
*
* @return false if the server is not found
* @see Server
*/
@DELETE
@Fallback(FalseOnNotFoundOr404.class)
@Path("/servers/{id}")
boolean deleteServer(@PathParam("id") int id);
/**
* The reboot function allows for either a soft or hard reboot of a server.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - REBOOT - ACTIVE (soft reboot)
* <p/>
* ACTIVE - HARD_REBOOT - ACTIVE (hard reboot)
*
* @param rebootType
* With a soft reboot, the operating system is signaled to restart, which allows for a
* graceful shutdown of all processes. A hard reboot is the equivalent of power cycling
* the server.
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(APPLICATION_JSON)
@Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D")
void rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly confirmed, at which time the
* original server is removed. All resizes are automatically confirmed after 24 hours if they are
* not confirmed or reverted.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE
* <p/>
* ACTIVE - QUEUE_RESIZE - ACTIVE (on error)
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(APPLICATION_JSON)
@Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D")
void resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly confirmed, at which time the
* original server is removed. All resizes are automatically confirmed after 24 hours if they are
* not confirmed or reverted.
* <p/>
* Status Transition:
* <p/>
* VERIFY_RESIZE - ACTIVE
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(APPLICATION_JSON)
@Payload("{\"confirmResize\":null}")
void confirmResizeServer(@PathParam("id") int id);
/**
* The resize function converts an existing server to a different flavor, in essence, scaling the
* server up or down. The original server is saved for a period of time to allow rollback if
* there is a problem. All resizes should be tested and explicitly reverted, at which time the
* original server is removed. All resizes are automatically reverted after 24 hours if they are
* not reverted or reverted.
* <p/>
* Status Transition:
* <p/>
* VERIFY_RESIZE - ACTIVE
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(APPLICATION_JSON)
@Payload("{\"revertResize\":null}")
void revertResizeServer(@PathParam("id") int id);
/**
* This operation asynchronously provisions a new server. The progress of this operation depends
* on several factors including location of the requested image, network i/o, host load, and the
* selected flavor. The progress of the request can be checked by performing a GET on /server/id,
* which will return a progress attribute (0-100% completion). A password will be randomly
* generated for you and returned in the response object. For security reasons, it will not be
* returned in subsequent GET calls against a given server ID.
*
* @param options
* - used to specify extra files, metadata, or ip parameters during server creation.
*/
@POST
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@MapBinder(CreateServerOptions.class)
Server createServer(@PayloadParam("name") String name, @PayloadParam("imageId") int imageId,
@PayloadParam("flavorId") int flavorId, CreateServerOptions... options);
/**
* The rebuild function removes all data on the server and replaces it with the specified image.
* Server ID and IP addresses remain the same.
* <p/>
* Status Transition:
* <p/>
* ACTIVE - REBUILD - ACTIVE
* <p/>
* ACTIVE - REBUILD - ERROR (on error)
* <p/>
*
* @param options
* - imageId is an optional argument. If it is not specified, the server is rebuilt
* with the original imageId.
*/
@POST
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@MapBinder(RebuildServerOptions.class)
void rebuildServer(@PathParam("id") int id, RebuildServerOptions... options);
/**
* /** This operation allows you share an IP address to the specified server
* <p/>
* This operation shares an IP from an existing server in the specified shared IP group to
* another specified server in the same group. The operation modifies cloud network restrictions
* to allow IP traffic for the given IP to/from the server specified.
*
* <p/>
* Status Transition: ACTIVE - SHARE_IP - ACTIVE (if configureServer is true) ACTIVE -
* SHARE_IP_NO_CONFIG - ACTIVE
*
* @param configureServer
* <p/>
* if set to true, the server is configured with the new address, though the address is
* not enabled. Note that configuring the server does require a reboot.
* <p/>
* If set to false, does not bind the IP to the server itself. A heartbeat facility
* (e.g. keepalived) can then be used within the servers to perform health checks and
* manage IP failover.
*/
@PUT
@Path("/servers/{id}/ips/public/{address}")
@Produces(APPLICATION_JSON)
@Payload("%7B\"shareIp\":%7B\"sharedIpGroupId\":{sharedIpGroupId},\"configureServer\":{configureServer}%7D%7D")
void shareIp(@PathParam("address") String addressToShare, @PathParam("id") int serverToTosignBindressTo,
@PayloadParam("sharedIpGroupId") int sharedIpGroup, @PayloadParam("configureServer") boolean configureServer);
/**
* This operation removes a shared IP address from the specified server.
* <p/>
* Status Transition: ACTIVE - DELETE_IP - ACTIVE
*
* @param addressToShare
* @param serverToTosignBindressTo
* @return
*/
@DELETE
@Path("/servers/{id}/ips/public/{address}")
@Fallback(VoidOnNotFoundOr404.class)
void unshareIp(@PathParam("address") String addressToShare, @PathParam("id") int serverToTosignBindressTo);
/**
* This operation allows you to change the administrative password.
* <p/>
* Status Transition: ACTIVE - PASSWORD - ACTIVE
*
*/
@PUT
@Path("/servers/{id}")
@Produces(APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D")
void changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass);
/**
* This operation allows you to update the name of the server. This operation changes the name of
* the server in the Cloud Servers system and does not change the server host name itself.
* <p/>
* Status Transition: ACTIVE - PASSWORD - ACTIVE
*
*/
@PUT
@Path("/servers/{id}")
@Produces(APPLICATION_JSON)
@Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D")
void renameServer(@PathParam("id") int id, @PayloadParam("name") String newName);
/**
*
* List available flavors (IDs and names only)
*
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors")
@Fallback(EmptySetOnNotFoundOr404.class)
Set<Flavor> listFlavors(ListOptions... options);
/**
*
* This operation returns details of the specified flavor.
*
* @return null, if the flavor is not found
* @see Flavor
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors/{id}")
@Fallback(NullOnNotFoundOr404.class)
Flavor getFlavor(@PathParam("id") int id);
/**
*
* List available images (IDs and names only)
*
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
@Fallback(EmptySetOnNotFoundOr404.class)
Set<Image> listImages(ListOptions... options);
/**
*
* This operation returns details of the specified image.
*
* @return null, if the image is not found
*
* @see Image
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@Fallback(NullOnNotFoundOr404.class)
@QueryParams(keys = "format", values = "json")
@Path("/images/{id}")
Image getImage(@PathParam("id") int id);
/**
*
* This operation deletes an image from the system.
* <p/>
* Note: Images are immediately removed. Currently, there are no state transitions to track the
* delete operation.
*
* @return false if the image is not found
* @see Image
*/
@DELETE
@Fallback(FalseOnNotFoundOr404.class)
@Path("/images/{id}")
boolean deleteImage(@PathParam("id") int id);
/**
*
* This operation creates a new image for the given server ID. Once complete, a new image will be
* available that can be used to rebuild or create servers. Specifying the same image name as an
* existing custom image replaces the image. The image creation status can be queried by
* performing a GET on /images/id and examining the status and progress attributes.
*
* Status Transition:
* <p/>
* QUEUED - PREPARING - SAVING - ACTIVE
* <p/>
* QUEUED - PREPARING - SAVING - FAILED (on error)
* <p/>
* Note: At present, image creation is an asynchronous operation, so coordinating the creation
* with data quiescence, etc. is currently not possible.
*
* @throws ResourceNotFoundException if the server is not found
* @see Image
*/
@POST
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
@Produces(APPLICATION_JSON)
@Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D")
Image createImageFromServer(@PayloadParam("name") String imageName, @PayloadParam("serverId") int serverId);
/**
*
* List shared IP groups (IDs and names only)
*
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups")
@Fallback(EmptySetOnNotFoundOr404.class)
Set<SharedIpGroup> listSharedIpGroups(ListOptions... options);
/**
*
* This operation returns details of the specified shared IP group.
*
* @return null, if the shared ip group is not found
*
* @see SharedIpGroup
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups/{id}")
@Fallback(NullOnNotFoundOr404.class)
SharedIpGroup getSharedIpGroup(@PathParam("id") int id);
/**
* This operation creates a new shared IP group. Please note, all responses to requests for
* shared_ip_groups return an array of servers. However, on a create request, the shared IP group
* can be created empty or can be initially populated with a single server. Use
* {@link CreateSharedIpGroupOptions} to specify an server.
*/
@POST
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups")
@MapBinder(CreateSharedIpGroupOptions.class)
SharedIpGroup createSharedIpGroup(@PayloadParam("name") String name,
CreateSharedIpGroupOptions... options);
/**
* This operation deletes the specified shared IP group. This operation will ONLY succeed if 1)
* there are no active servers in the group (i.e. they have all been terminated) or 2) no servers
* in the group are actively sharing IPs.
*
* @return false if the shared ip group is not found
* @see SharedIpGroup
*/
@DELETE
@Fallback(FalseOnNotFoundOr404.class)
@Path("/shared_ip_groups/{id}")
boolean deleteSharedIpGroup(@PathParam("id") int id);
/**
* List the backup schedule for the specified server
*
* @throws ResourceNotFoundException, if the server doesn't exist
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/backup_schedule")
BackupSchedule getBackupSchedule(@PathParam("id") int serverId);
/**
* Delete backup schedule for the specified server.
* <p/>
* Web Hosting #119571 currently disables the schedule, not deletes it.
*
* @return false if the schedule is not found
*/
@DELETE
@Fallback(FalseOnNotFoundOr404.class)
@Path("/servers/{id}/backup_schedule")
boolean deleteBackupSchedule(@PathParam("id") int serverId);
/**
* Enable/update the backup schedule for the specified server
*
*/
@POST
@Path("/servers/{id}/backup_schedule")
void replaceBackupSchedule(@PathParam("id") int id,
@BinderParam(BindBackupScheduleToJsonPayload.class) BackupSchedule backupSchedule);
/**
* List all server addresses
*
* returns empty set if the server doesn't exist
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips")
Addresses getAddresses(@PathParam("id") int serverId);
/**
* List all public server addresses
*
* returns empty set if the server doesn't exist
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/public")
@Fallback(EmptySetOnNotFoundOr404.class)
Set<String> listPublicAddresses(@PathParam("id") int serverId);
/**
* List all private server addresses
*
* returns empty set if the server doesn't exist
*/
@GET
@Unwrap
@Consumes(APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/private")
@Fallback(EmptySetOnNotFoundOr404.class)
Set<String> listPrivateAddresses(@PathParam("id") int serverId);
}

View File

@ -1,50 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.binders;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.Json;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
@Singleton
public class BindBackupScheduleToJsonPayload extends BindToJsonPayload {
@Inject
public BindBackupScheduleToJsonPayload(Json jsonBinder) {
super(jsonBinder);
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
throw new IllegalStateException("Replace Backup Schedule needs an BackupSchedule object, not a Map");
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
checkArgument(toBind instanceof BackupSchedule, "this binder is only valid for BackupSchedules!");
return super.bindToRequest(request, (Object) ImmutableMap.of("backupSchedule", toBind));
}
}

View File

@ -1,136 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.config;
import java.util.Map;
import javax.inject.Singleton;
import org.jclouds.cloudservers.compute.extensions.CloudServersImageExtension;
import org.jclouds.cloudservers.compute.functions.CloudServersImageToImage;
import org.jclouds.cloudservers.compute.functions.CloudServersImageToOperatingSystem;
import org.jclouds.cloudservers.compute.functions.FlavorToHardware;
import org.jclouds.cloudservers.compute.functions.ServerToNodeMetadata;
import org.jclouds.cloudservers.compute.strategy.CloudServersComputeServiceAdapter;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.cloudservers.domain.ImageStatus;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
public class CloudServersComputeServiceContextModule extends
ComputeServiceAdapterContextModule<Server, Flavor, org.jclouds.cloudservers.domain.Image, Location> {
@SuppressWarnings("unchecked")
@Override
protected void configure() {
super.configure();
bind(new TypeLiteral<ComputeServiceAdapter<Server, Flavor, org.jclouds.cloudservers.domain.Image, Location>>() {
}).to(CloudServersComputeServiceAdapter.class);
bind(new TypeLiteral<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.cloudservers.domain.Image, Image>>() {
}).to(CloudServersImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.cloudservers.domain.Image, OperatingSystem>>() {
}).to(CloudServersImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
// we aren't converting location from a provider-specific type
bind(new TypeLiteral<Function<Location, Location>>() {
}).to(Class.class.cast(IdentityFunction.class));
bind(new TypeLiteral<ImageExtension>() {
}).to(CloudServersImageExtension.class);
}
@VisibleForTesting
public static final Map<ServerStatus, NodeMetadata.Status> toPortableNodeStatus = ImmutableMap
.<ServerStatus, NodeMetadata.Status> builder()
.put(ServerStatus.ACTIVE, NodeMetadata.Status.RUNNING)
.put(ServerStatus.SUSPENDED, NodeMetadata.Status.SUSPENDED)
.put(ServerStatus.DELETED, NodeMetadata.Status.TERMINATED)
.put(ServerStatus.QUEUE_RESIZE, NodeMetadata.Status.PENDING)
.put(ServerStatus.PREP_RESIZE, NodeMetadata.Status.PENDING)
.put(ServerStatus.RESIZE, NodeMetadata.Status.PENDING)
.put(ServerStatus.VERIFY_RESIZE, NodeMetadata.Status.PENDING)
.put(ServerStatus.QUEUE_MOVE, NodeMetadata.Status.PENDING)
.put(ServerStatus.PREP_MOVE, NodeMetadata.Status.PENDING)
.put(ServerStatus.MOVE, NodeMetadata.Status.PENDING)
.put(ServerStatus.VERIFY_MOVE, NodeMetadata.Status.PENDING)
.put(ServerStatus.RESCUE, NodeMetadata.Status.PENDING)
.put(ServerStatus.ERROR, NodeMetadata.Status.ERROR)
.put(ServerStatus.BUILD, NodeMetadata.Status.PENDING)
.put(ServerStatus.RESTORING, NodeMetadata.Status.PENDING)
.put(ServerStatus.PASSWORD, NodeMetadata.Status.PENDING)
.put(ServerStatus.REBUILD, NodeMetadata.Status.PENDING)
.put(ServerStatus.DELETE_IP, NodeMetadata.Status.PENDING)
.put(ServerStatus.SHARE_IP_NO_CONFIG, NodeMetadata.Status.PENDING)
.put(ServerStatus.SHARE_IP, NodeMetadata.Status.PENDING)
.put(ServerStatus.REBOOT, NodeMetadata.Status.PENDING)
.put(ServerStatus.HARD_REBOOT, NodeMetadata.Status.PENDING)
.put(ServerStatus.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED)
.put(ServerStatus.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).build();
@Singleton
@Provides
Map<ServerStatus, NodeMetadata.Status> toPortableNodeStatus() {
return toPortableNodeStatus;
}
@VisibleForTesting
public static final Map<ImageStatus, Image.Status> toPortableImageStatus = ImmutableMap
.<ImageStatus, Image.Status> builder()
.put(ImageStatus.ACTIVE, Image.Status.AVAILABLE)
.put(ImageStatus.SAVING, Image.Status.PENDING)
.put(ImageStatus.PREPARING, Image.Status.PENDING)
.put(ImageStatus.QUEUED, Image.Status.PENDING)
.put(ImageStatus.FAILED, Image.Status.ERROR)
.put(ImageStatus.UNKNOWN, Image.Status.UNRECOGNIZED)
.put(ImageStatus.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build();
@Singleton
@Provides
Map<ImageStatus, Image.Status> toPortableImageStatus() {
return toPortableImageStatus;
}
@Override
protected Optional<ImageExtension> provideImageExtension(Injector i) {
return Optional.of(i.getInstance(ImageExtension.class));
}
}

View File

@ -1,125 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.extensions;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.compute.domain.CloneImageTemplate;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.domain.ImageTemplateBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.Atomics;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.UncheckedTimeoutException;
/**
* CloudServers implementation of {@link ImageExtension}
*
* @see <a href="http://docs.rackspace.com/servers/api/v1.0/cs-devguide/content/Images-d1e4062.html">docs</a>
*/
@Singleton
public class CloudServersImageExtension implements ImageExtension {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final CloudServersClient client;
private final ListeningExecutorService userExecutor;
private final Supplier<Location> location;
private final Predicate<AtomicReference<Image>> imageAvailablePredicate;
@Inject
public CloudServersImageExtension(CloudServersClient client, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
Supplier<Location> location,
@Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate) {
this.client = checkNotNull(client, "client");
this.userExecutor = checkNotNull(userExecutor, "userExecutor");
this.location = checkNotNull(location, "location");
this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, "imageAvailablePredicate");
}
@Override
public ImageTemplate buildImageTemplateFromNode(String name, final String id) {
Server server = client.getServer(Integer.parseInt(id));
if (server == null)
throw new NoSuchElementException("Cannot find server with id: " + id);
CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build();
return template;
}
@Override
public ListenableFuture<Image> createImage(ImageTemplate template) {
checkState(template instanceof CloneImageTemplate,
" openstack-nova only supports creating images through cloning.");
CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;
org.jclouds.cloudservers.domain.Image csImage = client.createImageFromServer(cloneTemplate.getName(),
Integer.parseInt(cloneTemplate.getSourceNodeId()));
final AtomicReference<Image> image = Atomics.newReference(new ImageBuilder()
.location(location.get())
.ids(csImage.getId() + "")
.description(cloneTemplate.getName())
.operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())
.status(Image.Status.PENDING).build());
return userExecutor.submit(new Callable<Image>() {
@Override
public Image call() throws Exception {
if (imageAvailablePredicate.apply(image))
return image.get();
// TODO: get rid of the expectation that the image will be available, as it is very brittle
throw new UncheckedTimeoutException("Image was not created within the time limit: " + image.get());
}
});
}
@Override
public boolean deleteImage(String id) {
try {
this.client.deleteImage(Integer.parseInt(id));
} catch (Exception e) {
return false;
}
return true;
}
}

View File

@ -1,54 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.cloudservers.domain.ImageStatus;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.Image.Status;
import com.google.common.base.Function;
@Singleton
public class CloudServersImageToImage implements Function<org.jclouds.cloudservers.domain.Image, Image> {
private final Map<ImageStatus, Status> toPortableImageStatus;
private final Function<org.jclouds.cloudservers.domain.Image, OperatingSystem> imageToOs;
@Inject
CloudServersImageToImage(Map<ImageStatus, Image.Status> toPortableImageStatus, Function<org.jclouds.cloudservers.domain.Image, OperatingSystem> imageToOs) {
this.toPortableImageStatus = toPortableImageStatus;
this.imageToOs = imageToOs;
}
public Image apply(org.jclouds.cloudservers.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.description(from.getName());
builder.version(from.getUpdated().getTime() + "");
builder.operatingSystem(imageToOs.apply(from));
builder.status(toPortableImageStatus.get(from.getStatus()));
Image image = builder.build();
return image;
}
}

View File

@ -1,85 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.util.ComputeServiceUtils;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
@Singleton
public class CloudServersImageToOperatingSystem implements
Function<org.jclouds.cloudservers.domain.Image, OperatingSystem> {
public static final Pattern DEFAULT_PATTERN = Pattern.compile("(([^ ]*) ([0-9.]+) ?.*)");
// Windows Server 2008 R2 x64
public static final Pattern WINDOWS_PATTERN = Pattern.compile("Windows (.*) (x[86][64])");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Map<OsFamily, Map<String, String>> osVersionMap;
@Inject
public CloudServersImageToOperatingSystem(Map<OsFamily, Map<String, String>> osVersionMap) {
this.osVersionMap = osVersionMap;
}
public OperatingSystem apply(final org.jclouds.cloudservers.domain.Image from) {
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getName();
boolean is64Bit = true;
if (from.getName().indexOf("Red Hat EL") != -1) {
osFamily = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
osFamily = OsFamily.OEL;
} else if (from.getName().indexOf("Windows") != -1) {
osFamily = OsFamily.WINDOWS;
Matcher matcher = WINDOWS_PATTERN.matcher(from.getName());
if (matcher.find()) {
osVersion = ComputeServiceUtils.parseVersionOrReturnEmptyString(osFamily, matcher.group(1), osVersionMap);
is64Bit = matcher.group(2).equals("x64");
}
} else {
Matcher matcher = DEFAULT_PATTERN.matcher(from.getName());
if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
osVersion = ComputeServiceUtils.parseVersionOrReturnEmptyString(osFamily, matcher.group(3), osVersionMap);
}
}
return new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
}
}

View File

@ -1,38 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import javax.inject.Singleton;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
@Singleton
public class FlavorToHardware implements Function<Flavor, Hardware> {
public Hardware apply(Flavor from) {
return new HardwareBuilder().ids(from.getId() + "").name(from.getName()).hypervisor("xen")
.processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0))).ram(from.getRam())
.volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDisk(), true, true))).build();
}
}

View File

@ -1,139 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromCommaDelimitedValue;
import static org.jclouds.compute.util.ComputeServiceUtils.groupFromMapOrName;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.NodeMetadata.Status;
import org.jclouds.compute.functions.GroupNamingConvention;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
@Singleton
public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
protected final Supplier<Location> location;
protected final Map<ServerStatus, Status> serverToNodeStatus;
protected final Supplier<Set<? extends Image>> images;
protected final Supplier<Set<? extends Hardware>> hardwares;
protected final GroupNamingConvention nodeNamingConvention;
private static class FindImageForServer implements Predicate<Image> {
private final Server instance;
private FindImageForServer(Server instance) {
this.instance = instance;
}
@Override
public boolean apply(Image input) {
return input.getProviderId().equals(instance.getImageId() + "");
}
}
private static class FindHardwareForServer implements Predicate<Hardware> {
private final Server instance;
private FindHardwareForServer(Server instance) {
this.instance = instance;
}
@Override
public boolean apply(Hardware input) {
return input.getProviderId().equals(instance.getFlavorId() + "");
}
}
@Inject
ServerToNodeMetadata(Map<ServerStatus, Status> serverStateToNodeStatus,
@Memoized Supplier<Set<? extends Image>> images, Supplier<Location> location,
@Memoized Supplier<Set<? extends Hardware>> hardwares,
GroupNamingConvention.Factory namingConvention) {
this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix();
this.serverToNodeStatus = checkNotNull(serverStateToNodeStatus, "serverStateToNodeStatus");
this.images = checkNotNull(images, "images");
this.location = checkNotNull(location, "location");
this.hardwares = checkNotNull(hardwares, "hardwares");
}
@Override
public NodeMetadata apply(Server from) {
NodeMetadataBuilder builder = new NodeMetadataBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.hostname(from.getName());
builder.location(new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId()).description(
from.getHostId()).parent(location.get()).build());
addMetadataAndParseTagsFromCommaDelimitedValue(builder, from.getMetadata());
builder.group(groupFromMapOrName(from.getMetadata(), from.getName(), nodeNamingConvention));
builder.imageId(from.getImageId() + "");
builder.operatingSystem(parseOperatingSystem(from));
builder.hardware(parseHardware(from));
builder.status(serverToNodeStatus.get(from.getStatus()));
builder.publicAddresses(from.getAddresses().getPublicAddresses());
builder.privateAddresses(from.getAddresses().getPrivateAddresses());
return builder.build();
}
protected Hardware parseHardware(Server from) {
try {
return Iterables.find(hardwares.get(), new FindHardwareForServer(from));
} catch (NoSuchElementException e) {
logger.debug("could not find a matching hardware for server %s", from);
}
return null;
}
protected OperatingSystem parseOperatingSystem(Server from) {
try {
return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem();
} catch (NoSuchElementException e) {
logger.debug("could not find a matching image for server %s in location %s", from, location.get());
}
return null;
}
}

View File

@ -1,141 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.contains;
import static com.google.common.collect.Iterables.filter;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withMetadata;
import static org.jclouds.cloudservers.options.ListOptions.Builder.withDetails;
import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.cloudservers.domain.Image;
import org.jclouds.cloudservers.domain.RebootType;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.options.ListOptions;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
/**
* defines the connection between the {@link CloudServersClient} implementation and the jclouds
* {@link ComputeService}
*/
@Singleton
public class CloudServersComputeServiceAdapter implements ComputeServiceAdapter<Server, Flavor, Image, Location> {
protected final CloudServersClient client;
@Inject
protected CloudServersComputeServiceAdapter(CloudServersClient client) {
this.client = checkNotNull(client, "client");
}
@Override
public NodeAndInitialCredentials<Server> createNodeWithGroupEncodedIntoName(String group, String name,
Template template) {
template.getOptions().userMetadata(ComputeServiceConstants.NODE_GROUP_KEY, group);
Server server = client
.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer.parseInt(template
.getHardware().getProviderId()), withMetadata(metadataAndTagsAsCommaDelimitedValue(template.getOptions())));
return new NodeAndInitialCredentials<Server>(server, server.getId() + "", LoginCredentials.builder().password(
server.getAdminPass()).build());
}
@Override
public Iterable<Flavor> listHardwareProfiles() {
return client.listFlavors(withDetails());
}
@Override
public Iterable<Image> listImages() {
return client.listImages(withDetails());
}
@Override
public Iterable<Server> listNodes() {
return client.listServers(ListOptions.Builder.withDetails());
}
@Override
public Iterable<Server> listNodesByIds(final Iterable<String> ids) {
return filter(listNodes(), new Predicate<Server>() {
@Override
public boolean apply(Server server) {
return contains(ids, server.getId());
}
});
}
@Override
public Iterable<Location> listLocations() {
// Not using the adapter to determine locations
return ImmutableSet.<Location>of();
}
@Override
public Server getNode(String id) {
int serverId = Integer.parseInt(id);
return client.getServer(serverId);
}
@Override
public Image getImage(String id) {
int imageId = Integer.parseInt(id);
return client.getImage(imageId);
}
@Override
public void destroyNode(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.deleteServer(serverId);
}
@Override
public void rebootNode(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.rebootServer(serverId, RebootType.HARD);
}
@Override
public void resumeNode(String id) {
throw new UnsupportedOperationException("suspend not supported");
}
@Override
public void suspendNode(String id) {
throw new UnsupportedOperationException("suspend not supported");
}
}

View File

@ -1,87 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.config;
import static com.google.common.base.Suppliers.memoizeWithExpiration;
import static org.jclouds.util.Suppliers2.getLastValueInMap;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.handlers.ParseCloudServersErrorFromHttpResponse;
import org.jclouds.date.TimeStamp;
import org.jclouds.http.HttpErrorHandler;
import org.jclouds.http.annotation.ClientError;
import org.jclouds.http.annotation.Redirection;
import org.jclouds.http.annotation.ServerError;
import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.jclouds.location.suppliers.RegionIdToURISupplier;
import org.jclouds.openstack.keystone.v1_1.config.AuthenticationServiceModule;
import org.jclouds.openstack.services.Compute;
import org.jclouds.rest.ConfiguresHttpApi;
import org.jclouds.rest.annotations.ApiVersion;
import org.jclouds.rest.config.HttpApiModule;
import com.google.common.base.Supplier;
import com.google.inject.Provides;
@ConfiguresHttpApi
public class CloudServersHttpApiModule extends HttpApiModule<CloudServersClient> {
@Override
protected void configure() {
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
super.configure();
}
@Override
protected void bindErrorHandlers() {
bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseCloudServersErrorFromHttpResponse.class);
bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseCloudServersErrorFromHttpResponse.class);
bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseCloudServersErrorFromHttpResponse.class);
}
@Override
protected void installLocations() {
super.installLocations();
install(new AuthenticationServiceModule());
}
@Provides
@Singleton
@Compute
protected Supplier<URI> provideCloudServers(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion) {
return getLastValueInMap(factory.createForApiTypeAndVersion("cloudServers", apiVersion));
}
// TODO: see if we still need this.
@Provides
@Singleton
@TimeStamp
protected Supplier<Date> provideCacheBusterDate() {
return memoizeWithExpiration(new Supplier<Date>() {
public Date get() {
return new Date();
}
}, 1, TimeUnit.SECONDS);
}
}

View File

@ -1,123 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.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;
/**
* Class AbsoluteLimit
*
*/
public class AbsoluteLimit {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromAbsoluteLimit(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected String name;
protected int value;
/**
* @see AbsoluteLimit#getName()
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* @see AbsoluteLimit#getValue()
*/
public T value(int value) {
this.value = value;
return self();
}
public AbsoluteLimit build() {
return new AbsoluteLimit(name, value);
}
public T fromAbsoluteLimit(AbsoluteLimit in) {
return this
.name(in.getName())
.value(in.getValue());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String name;
private final int value;
@ConstructorProperties({
"name", "value"
})
protected AbsoluteLimit(String name, int value) {
this.name = checkNotNull(name, "name");
this.value = value;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
@Override
public int hashCode() {
return Objects.hashCode(name, value);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
AbsoluteLimit that = AbsoluteLimit.class.cast(obj);
return Objects.equal(this.name, that.name)
&& Objects.equal(this.value, that.value);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("name", name).add("value", value);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,21 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
public enum Action {
CONFIRM_RESIZE, REBOOT, REBUILD, RESIZE, REVERT_RESIZE
}

View File

@ -1,142 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Collection;
import java.util.Set;
import javax.inject.Named;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableSet;
/**
* Class Addresses
*
*/
public class Addresses {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromAddresses(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected Set<String> publicAddresses;
protected Set<String> privateAddresses;
/**
* @see Addresses#getPublicAddresses()
*/
public T publicAddresses(Collection<String> publicAddresses) {
this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses"));
return self();
}
public T publicAddresses(String... in) {
return publicAddresses(ImmutableSet.copyOf(in));
}
/**
* @see Addresses#getPrivateAddresses()
*/
public T privateAddresses(Collection<String> privateAddresses) {
this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses"));
return self();
}
public T privateAddresses(String... in) {
return privateAddresses(ImmutableSet.copyOf(in));
}
public Addresses build() {
return new Addresses(publicAddresses, privateAddresses);
}
public T fromAddresses(Addresses in) {
return this
.publicAddresses(in.getPublicAddresses())
.privateAddresses(in.getPrivateAddresses());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
@Named("public")
private final Set<String> publicAddresses;
@Named("private")
private final Set<String> privateAddresses;
@ConstructorProperties({
"public", "private"
})
protected Addresses(@Nullable Set<String> publicAddresses, @Nullable Set<String> privateAddresses) {
this.publicAddresses = publicAddresses == null ? null : ImmutableSet.copyOf(publicAddresses);
this.privateAddresses = privateAddresses == null ? null : ImmutableSet.copyOf(privateAddresses);
}
@Nullable
public Set<String> getPublicAddresses() {
return this.publicAddresses;
}
@Nullable
public Set<String> getPrivateAddresses() {
return this.privateAddresses;
}
@Override
public int hashCode() {
return Objects.hashCode(publicAddresses, privateAddresses);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Addresses that = Addresses.class.cast(obj);
return Objects.equal(this.publicAddresses, that.publicAddresses)
&& Objects.equal(this.privateAddresses, that.privateAddresses);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("publicAddresses", publicAddresses).add("privateAddresses", privateAddresses);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,143 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import java.beans.ConstructorProperties;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* A backup schedule can be defined to create server images at regular intervals (daily and weekly).
* Backup schedules are configurable per server.
*
*/
public class BackupSchedule {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromBackupSchedule(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected DailyBackup daily;
protected boolean enabled;
protected WeeklyBackup weekly;
/**
* @see BackupSchedule#getDaily()
*/
public T daily(DailyBackup daily) {
this.daily = daily;
return self();
}
/**
* @see BackupSchedule#isEnabled()
*/
public T enabled(boolean enabled) {
this.enabled = enabled;
return self();
}
/**
* @see BackupSchedule#getWeekly()
*/
public T weekly(WeeklyBackup weekly) {
this.weekly = weekly;
return self();
}
public BackupSchedule build() {
return new BackupSchedule(daily, enabled, weekly);
}
public T fromBackupSchedule(BackupSchedule in) {
return this
.daily(in.getDaily())
.enabled(in.isEnabled())
.weekly(in.getWeekly());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final DailyBackup daily;
private final boolean enabled;
private final WeeklyBackup weekly;
@ConstructorProperties({
"daily", "enabled", "weekly"
})
protected BackupSchedule(@Nullable DailyBackup daily, boolean enabled, @Nullable WeeklyBackup weekly) {
this.daily = daily;
this.enabled = enabled;
this.weekly = weekly;
}
@Nullable
public DailyBackup getDaily() {
return this.daily;
}
public boolean isEnabled() {
return this.enabled;
}
@Nullable
public WeeklyBackup getWeekly() {
return this.weekly;
}
@Override
public int hashCode() {
return Objects.hashCode(daily, enabled, weekly);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
BackupSchedule that = BackupSchedule.class.cast(obj);
return Objects.equal(this.daily, that.daily)
&& Objects.equal(this.enabled, that.enabled)
&& Objects.equal(this.weekly, that.weekly);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("daily", daily).add("enabled", enabled).add("weekly", weekly);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
public enum DailyBackup {
DISABLED, H_0000_0200, H_0200_0400, H_0400_0600, H_0600_0800, H_0800_1000, H_1000_1200, H_1200_1400, H_1400_1600, H_1600_1800, H_1800_2000, H_2000_2200, H_2200_0000, UNRECOGNIZED;
public String value() {
return name();
}
public static DailyBackup fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,162 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.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.ToStringHelper;
/**
* A flavor is an available hardware configuration for a server. Each flavor has a unique
* combination of disk space and memory capacity.
*
*/
public class Flavor {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromFlavor(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected int id;
protected String name;
protected Integer disk;
protected Integer ram;
/**
* @see Flavor#getId()
*/
public T id(int id) {
this.id = id;
return self();
}
/**
* @see Flavor#getName()
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* @see Flavor#getDisk()
*/
public T disk(Integer disk) {
this.disk = disk;
return self();
}
/**
* @see Flavor#getRam()
*/
public T ram(Integer ram) {
this.ram = ram;
return self();
}
public Flavor build() {
return new Flavor(id, name, disk, ram);
}
public T fromFlavor(Flavor in) {
return this
.id(in.getId())
.name(in.getName())
.disk(in.getDisk())
.ram(in.getRam());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final int id;
private final String name;
private final Integer disk;
private final Integer ram;
@ConstructorProperties({
"id", "name", "disk", "ram"
})
protected Flavor(int id, String name, @Nullable Integer disk, @Nullable Integer ram) {
this.id = id;
this.name = checkNotNull(name, "name");
this.disk = disk;
this.ram = ram;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Nullable
public Integer getDisk() {
return this.disk;
}
@Nullable
public Integer getRam() {
return this.ram;
}
@Override
public int hashCode() {
return Objects.hashCode(id, name, disk, ram);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Flavor that = Flavor.class.cast(obj);
return Objects.equal(this.id, that.id)
&& Objects.equal(this.name, that.name)
&& Objects.equal(this.disk, that.disk)
&& Objects.equal(this.ram, that.ram);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("id", id).add("name", name).add("disk", disk).add("ram", ram);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,219 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Date;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* An image is a collection of files used to create or rebuild a server. Rackspace provides a number
* of pre-built OS images by default. You may also create custom images from cloud servers you have
* launched. These custom images are useful for backup purposes or for producing gold server images
* if you plan to deploy a particular server configuration frequently.
*
*/
public class Image {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromImage(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected Date created;
protected int id;
protected String name;
protected Integer progress;
protected Integer serverId;
protected ImageStatus status;
protected Date updated;
/**
* @see Image#getCreated()
*/
public T created(Date created) {
this.created = created;
return self();
}
/**
* @see Image#getId()
*/
public T id(int id) {
this.id = id;
return self();
}
/**
* @see Image#getName()
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* @see Image#getProgress()
*/
public T progress(Integer progress) {
this.progress = progress;
return self();
}
/**
* @see Image#getServerId()
*/
public T serverId(Integer serverId) {
this.serverId = serverId;
return self();
}
/**
* @see Image#getStatus()
*/
public T status(ImageStatus status) {
this.status = status;
return self();
}
/**
* @see Image#getUpdated()
*/
public T updated(Date updated) {
this.updated = updated;
return self();
}
public Image build() {
return new Image(created, id, name, progress, serverId, status, updated);
}
public T fromImage(Image in) {
return this
.created(in.getCreated())
.id(in.getId())
.name(in.getName())
.progress(in.getProgress())
.serverId(in.getServerId())
.status(in.getStatus())
.updated(in.getUpdated());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final Date created;
private final int id;
private final String name;
private final Integer progress;
private final Integer serverId;
private final ImageStatus status;
private final Date updated;
@ConstructorProperties({
"created", "id", "name", "progress", "serverId", "status", "updated"
})
protected Image(@Nullable Date created, int id, String name, @Nullable Integer progress, @Nullable Integer serverId, @Nullable ImageStatus status, @Nullable Date updated) {
this.created = created;
this.id = id;
this.name = checkNotNull(name, "name");
this.progress = progress;
this.serverId = serverId;
this.status = status;
this.updated = updated;
}
@Nullable
public Date getCreated() {
return this.created;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Nullable
public Integer getProgress() {
return this.progress;
}
@Nullable
public Integer getServerId() {
return this.serverId;
}
@Nullable
public ImageStatus getStatus() {
return this.status;
}
@Nullable
public Date getUpdated() {
return this.updated;
}
@Override
public int hashCode() {
return Objects.hashCode(created, id, name, progress, serverId, status, updated);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Image that = Image.class.cast(obj);
return Objects.equal(this.created, that.created)
&& Objects.equal(this.id, that.id)
&& Objects.equal(this.name, that.name)
&& Objects.equal(this.progress, that.progress)
&& Objects.equal(this.serverId, that.serverId)
&& Objects.equal(this.status, that.status)
&& Objects.equal(this.updated, that.updated);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("created", created).add("id", id).add("name", name).add("progress", progress).add("serverId", serverId).add("status", status).add("updated", updated);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,41 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
/**
* In-flight images will have the status attribute set to SAVING and the conditional progress
* element (0- 100% completion) will also be returned. Other possible values for the status
* attribute include: UNKNOWN, PREPARING, ACTIVE QUEUED, FAILED. Images with an ACTIVE status are
* available for install.
*/
public enum ImageStatus {
UNRECOGNIZED, UNKNOWN, ACTIVE, SAVING, PREPARING, QUEUED, FAILED;
public String value() {
return name();
}
public static ImageStatus fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,130 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* Class Limits
*/
public class Limits {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromLimits(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected Set<RateLimit> rate = ImmutableSet.of();
protected Map<String, Integer> absolute = ImmutableMap.of();
/**
* @see Limits#getRate()
*/
public T rate(Set<RateLimit> rate) {
this.rate = ImmutableSet.copyOf(checkNotNull(rate, "rate"));
return self();
}
public T rate(RateLimit... in) {
return rate(ImmutableSet.copyOf(in));
}
/**
* @see Limits#getAbsolute()
*/
public T absolute(Map<String, Integer> absolute) {
this.absolute = ImmutableMap.copyOf(checkNotNull(absolute, "absolute"));
return self();
}
public Limits build() {
return new Limits(rate, absolute);
}
public T fromLimits(Limits in) {
return this
.rate(in.getRate())
.absolute(in.getAbsolute());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final Set<RateLimit> rate;
private final Map<String, Integer> absolute;
@ConstructorProperties({
"rate", "absolute"
})
protected Limits(Set<RateLimit> rate, Map<String, Integer> absolute) {
this.rate = ImmutableSet.copyOf(checkNotNull(rate, "rate"));
this.absolute = ImmutableMap.copyOf(checkNotNull(absolute, "absolute"));
}
public Set<RateLimit> getRate() {
return this.rate;
}
public Map<String, Integer> getAbsolute() {
return this.absolute;
}
@Override
public int hashCode() {
return Objects.hashCode(rate, absolute);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Limits that = Limits.class.cast(obj);
return Objects.equal(this.rate, that.rate)
&& Objects.equal(this.absolute, that.absolute);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("rate", rate).add("absolute", absolute);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,225 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.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.ToStringHelper;
/**
* RateLimit.
* <p/>
* we specify rate limits in terms of both a human readable wild-card URI and a machine processable
* regular expression. The regular expression boundary matcher '^' takes affect after the root URI
* path. For example, the regular expression ^/servers would match the bolded portion of the
* following URI: https://servers.api.rackspacecloud.com/v1.0/3542812 /servers .
* <p/>
* Rate limits are applied in order relative to the verb, going from least to most specific. For
* example, although the threshold for POST to /servers is 25 per day, one cannot POST to /servers
* more than 10 times within a single minute because the rate limits for any POST is 10/min. In the
* event you exceed the thresholds established for your identity, a 413 Rate Control HTTP response
* will be returned with a Reply-After header to notify the client when theyagain.
*
*/
public class RateLimit {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromRateLimit(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected String uri;
protected String regex;
protected int remaining;
protected long resetTime;
protected RateLimitUnit unit;
protected int value;
protected String verb;
/**
* @see RateLimit#getUri()
*/
public T uri(String uri) {
this.uri = uri;
return self();
}
/**
* @see RateLimit#getRegex()
*/
public T regex(String regex) {
this.regex = regex;
return self();
}
/**
* @see RateLimit#getRemaining()
*/
public T remaining(int remaining) {
this.remaining = remaining;
return self();
}
/**
* @see RateLimit#getResetTime()
*/
public T resetTime(long resetTime) {
this.resetTime = resetTime;
return self();
}
/**
* @see RateLimit#getUnit()
*/
public T unit(RateLimitUnit unit) {
this.unit = unit;
return self();
}
/**
* @see RateLimit#getValue()
*/
public T value(int value) {
this.value = value;
return self();
}
/**
* @see RateLimit#getVerb()
*/
public T verb(String verb) {
this.verb = verb;
return self();
}
public RateLimit build() {
return new RateLimit(uri, regex, remaining, resetTime, unit, value, verb);
}
public T fromRateLimit(RateLimit in) {
return this
.uri(in.getUri())
.regex(in.getRegex())
.remaining(in.getRemaining())
.resetTime(in.getResetTime())
.unit(in.getUnit())
.value(in.getValue())
.verb(in.getVerb());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String uri;
private final String regex;
private final int remaining;
private final long resetTime;
private final RateLimitUnit unit;
private final int value;
private final String verb;
@ConstructorProperties({
"uri", "regex", "remaining", "resetTime", "unit", "value", "verb"
})
protected RateLimit(String uri, @Nullable String regex, int remaining, long resetTime, @Nullable RateLimitUnit unit,
int value, @Nullable String verb) {
this.uri = checkNotNull(uri, "uri");
this.regex = regex;
this.remaining = remaining;
this.resetTime = resetTime;
this.unit = unit;
this.value = value;
this.verb = verb;
}
public String getUri() {
return this.uri;
}
@Nullable
public String getRegex() {
return this.regex;
}
public int getRemaining() {
return this.remaining;
}
public long getResetTime() {
return this.resetTime;
}
@Nullable
public RateLimitUnit getUnit() {
return this.unit;
}
public int getValue() {
return this.value;
}
@Nullable
public String getVerb() {
return this.verb;
}
@Override
public int hashCode() {
return Objects.hashCode(uri, regex, remaining, resetTime, unit, value, verb);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
RateLimit that = RateLimit.class.cast(obj);
return Objects.equal(this.uri, that.uri)
&& Objects.equal(this.regex, that.regex)
&& Objects.equal(this.remaining, that.remaining)
&& Objects.equal(this.resetTime, that.resetTime)
&& Objects.equal(this.unit, that.unit)
&& Objects.equal(this.value, that.value)
&& Objects.equal(this.verb, that.verb);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("uri", uri).add("regex", regex).add("remaining", remaining).add("resetTime", resetTime).add("unit", unit).add("value", value).add("verb", verb);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
public enum RateLimitUnit {
MINUTE, HOUR, DAY, UNRECOGNIZED;
public String value() {
return name();
}
public static RateLimitUnit fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,31 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
public enum RebootType {
HARD, SOFT;
public String value() {
return name();
}
public static RebootType fromValue(String v) {
return valueOf(v);
}
}

View File

@ -1,301 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableMap;
/**
* A server is a virtual machine instance in the Cloud Servers system. Flavor and image are
* requisite elements when creating a server.
*
*/
public class Server {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromServer(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected int id;
protected String name;
protected Map<String, String> metadata;
protected Addresses addresses;
protected String adminPass;
protected Integer flavorId;
protected String hostId;
protected Integer imageId;
protected Integer sharedIpGroupId;
protected Integer progress;
protected ServerStatus status;
/**
* @see Server#getId()
*/
public T id(int id) {
this.id = id;
return self();
}
/**
* @see Server#getName()
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* @see Server#getMetadata()
*/
public T metadata(Map<String, String> metadata) {
this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, "metadata"));
return self();
}
/**
* @see Server#getAddresses()
*/
public T addresses(Addresses addresses) {
this.addresses = addresses;
return self();
}
/**
* @see Server#getAdminPass()
*/
public T adminPass(String adminPass) {
this.adminPass = adminPass;
return self();
}
/**
* @see Server#getFlavorId()
*/
public T flavorId(Integer flavorId) {
this.flavorId = flavorId;
return self();
}
/**
* @see Server#getHostId()
*/
public T hostId(String hostId) {
this.hostId = hostId;
return self();
}
/**
* @see Server#getImageId()
*/
public T imageId(Integer imageId) {
this.imageId = imageId;
return self();
}
/**
* @see Server#getSharedIpGroupId()
*/
public T sharedIpGroupId(Integer sharedIpGroupId) {
this.sharedIpGroupId = sharedIpGroupId;
return self();
}
/**
* @see Server#getProgress()
*/
public T progress(Integer progress) {
this.progress = progress;
return self();
}
/**
* @see Server#getStatus()
*/
public T status(ServerStatus status) {
this.status = status;
return self();
}
public Server build() {
return new Server(id, name, metadata, addresses, adminPass, flavorId, hostId, imageId, sharedIpGroupId, progress, status);
}
public T fromServer(Server in) {
return this
.id(in.getId())
.name(in.getName())
.metadata(in.getMetadata())
.addresses(in.getAddresses())
.adminPass(in.getAdminPass())
.flavorId(in.getFlavorId())
.hostId(in.getHostId())
.imageId(in.getImageId())
.sharedIpGroupId(in.getSharedIpGroupId())
.progress(in.getProgress())
.status(in.getStatus());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final int id;
private final String name;
private final Map<String, String> metadata;
private final Addresses addresses;
private final String adminPass;
private final Integer flavorId;
private final String hostId;
private final Integer imageId;
private final Integer sharedIpGroupId;
private final Integer progress;
private final ServerStatus status;
@ConstructorProperties({
"id", "name", "metadata", "addresses", "adminPass", "flavorId", "hostId", "imageId", "sharedIpGroupId", "progress", "status"
})
protected Server(int id, String name, @Nullable Map<String, String> metadata, @Nullable Addresses addresses,
@Nullable String adminPass, @Nullable Integer flavorId, @Nullable String hostId, @Nullable Integer imageId,
@Nullable Integer sharedIpGroupId, @Nullable Integer progress, @Nullable ServerStatus status) {
this.id = id;
this.name = checkNotNull(name, "name");
this.metadata = metadata == null ? null : ImmutableMap.copyOf(metadata);
this.addresses = addresses;
this.adminPass = adminPass;
this.flavorId = flavorId;
this.hostId = hostId;
this.imageId = imageId;
this.sharedIpGroupId = sharedIpGroupId;
this.progress = progress;
this.status = status == null ? ServerStatus.UNKNOWN : status;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Nullable
public Map<String, String> getMetadata() {
return this.metadata;
}
@Nullable
public Addresses getAddresses() {
return this.addresses;
}
@Nullable
public String getAdminPass() {
return this.adminPass;
}
@Nullable
public Integer getFlavorId() {
return this.flavorId;
}
/**
* The Cloud Servers provisioning algorithm has an anti-affinity property that attempts to spread
* out customer VMs across hosts. Under certain situations, VMs from the same customer may be
* placed on the same host. hostId represents the host your cloud server runs on and can be used
* to determine this scenario if it's relevant to your application.
* <p/>
* Note: hostId is unique PER ACCOUNT and is not globally unique.
*/
@Nullable
public String getHostId() {
return this.hostId;
}
@Nullable
public Integer getImageId() {
return this.imageId;
}
@Nullable
public Integer getSharedIpGroupId() {
return this.sharedIpGroupId;
}
@Nullable
public Integer getProgress() {
return this.progress;
}
/**
* Servers contain a status attribute that can be used as an indication of the current server
* state. Servers with an ACTIVE status are available for use.
*/
public ServerStatus getStatus() {
return this.status;
}
@Override
public int hashCode() {
return Objects.hashCode(id, name, metadata, addresses, adminPass, flavorId, hostId, imageId, sharedIpGroupId);
}
@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)
&& Objects.equal(this.name, that.name)
&& Objects.equal(this.metadata, that.metadata)
&& Objects.equal(this.addresses, that.addresses)
&& Objects.equal(this.adminPass, that.adminPass)
&& Objects.equal(this.flavorId, that.flavorId)
&& Objects.equal(this.hostId, that.hostId)
&& Objects.equal(this.imageId, that.imageId)
&& Objects.equal(this.sharedIpGroupId, that.sharedIpGroupId);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("id", id).add("name", name).add("metadata", metadata).add("addresses", addresses).add("adminPass", adminPass).add("flavorId", flavorId).add("hostId", hostId).add("imageId", imageId).add("sharedIpGroupId", sharedIpGroupId).add("progress", progress).add("status", status);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,50 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
/**
*
* Servers contain a status attribute that can be used as an indication of the current server state.
* Servers with an ACTIVE status are available for use.
* <p/>
* <h2>Note</h2>
* When the system changes a server's status from BUILD to ACTIVE the system will not be immediately
* available. The 'ACTIVE' label is really misleading in the fact that it just means the system
* doesn't have any activity going on related to it's configuration.
* <p/>
* Processes such as ssh will not be available until 5-10 seconds following the phase ACTIVE
* <ul>
* <li>[Web Hosting #119335]</li>
* </ul>
*/
public enum ServerStatus {
ACTIVE, SUSPENDED, DELETED, QUEUE_RESIZE, PREP_RESIZE, RESIZE, VERIFY_RESIZE, QUEUE_MOVE, PREP_MOVE, MOVE, VERIFY_MOVE, RESCUE, ERROR, BUILD, RESTORING, PASSWORD, REBUILD, DELETE_IP, SHARE_IP_NO_CONFIG, SHARE_IP, REBOOT, HARD_REBOOT, UNKNOWN, UNRECOGNIZED;
public String value() {
return name();
}
public static ServerStatus fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,120 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Class ShareIp
*/
public class ShareIp {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromShareIp(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected boolean configureServer;
protected int sharedIpGroupId;
/**
* @see ShareIp#isConfigureServer()
*/
public T configureServer(boolean configureServer) {
this.configureServer = configureServer;
return self();
}
/**
* @see ShareIp#getSharedIpGroupId()
*/
public T sharedIpGroupId(int sharedIpGroupId) {
this.sharedIpGroupId = sharedIpGroupId;
return self();
}
public ShareIp build() {
return new ShareIp(configureServer, sharedIpGroupId);
}
public T fromShareIp(ShareIp in) {
return this
.configureServer(in.isConfigureServer())
.sharedIpGroupId(in.getSharedIpGroupId());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final boolean configureServer;
private final int sharedIpGroupId;
@ConstructorProperties({
"configureServer", "sharedIpGroupId"
})
protected ShareIp(boolean configureServer, int sharedIpGroupId) {
this.configureServer = configureServer;
this.sharedIpGroupId = sharedIpGroupId;
}
public boolean isConfigureServer() {
return this.configureServer;
}
public int getSharedIpGroupId() {
return this.sharedIpGroupId;
}
@Override
public int hashCode() {
return Objects.hashCode(configureServer, sharedIpGroupId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ShareIp that = ShareIp.class.cast(obj);
return Objects.equal(this.configureServer, that.configureServer)
&& Objects.equal(this.sharedIpGroupId, that.sharedIpGroupId);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("configureServer", configureServer).add("sharedIpGroupId", sharedIpGroupId);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,152 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.List;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableList;
/**
* A shared IP group is a collection of servers that can share IPs with other members of the group.
* Any server in a group can share one or more public IPs with any other server in the group. With
* the exception of the first server in a shared IP group, servers must be launched into shared IP
* groups. A server may only be a member of one shared IP group.
*
*/
public class SharedIpGroup {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromSharedIpGroup(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected int id;
protected String name;
protected List<Integer> servers = null;
/**
* @see SharedIpGroup#getId()
*/
public T id(int id) {
this.id = id;
return self();
}
/**
* @see SharedIpGroup#getName()
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* @see SharedIpGroup#getServers()
*/
public T servers(List<Integer> servers) {
this.servers = ImmutableList.copyOf(checkNotNull(servers, "servers"));
return self();
}
public T servers(Integer... in) {
return servers(ImmutableList.copyOf(in));
}
public SharedIpGroup build() {
return new SharedIpGroup(id, name, servers);
}
public T fromSharedIpGroup(SharedIpGroup in) {
return this
.id(in.getId())
.name(in.getName())
.servers(in.getServers());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final int id;
private final String name;
private final List<Integer> servers;
@ConstructorProperties({
"id", "name", "servers"
})
protected SharedIpGroup(int id, String name, @Nullable List<Integer> servers) {
this.id = id;
this.name = checkNotNull(name, "name");
this.servers = servers == null ? null : ImmutableList.copyOf(servers);
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Nullable
public List<Integer> getServers() {
return this.servers;
}
@Override
public int hashCode() {
return Objects.hashCode(id, name, servers);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
SharedIpGroup that = SharedIpGroup.class.cast(obj);
return Objects.equal(this.id, that.id)
&& Objects.equal(this.name, that.name)
&& Objects.equal(this.servers, that.servers);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("id", id).add("name", name).add("servers", servers);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,159 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.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.ToStringHelper;
/**
* Class Version
*/
public class Version {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromVersion(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected String docURL;
protected String id;
protected VersionStatus status;
protected String wadl;
/**
* @see Version#getDocURL()
*/
public T docURL(String docURL) {
this.docURL = docURL;
return self();
}
/**
* @see Version#getId()
*/
public T id(String id) {
this.id = id;
return self();
}
/**
* @see Version#getStatus()
*/
public T status(VersionStatus status) {
this.status = status;
return self();
}
/**
* @see Version#getWadl()
*/
public T wadl(String wadl) {
this.wadl = wadl;
return self();
}
public Version build() {
return new Version(docURL, id, status, wadl);
}
public T fromVersion(Version in) {
return this
.docURL(in.getDocURL())
.id(in.getId())
.status(in.getStatus())
.wadl(in.getWadl());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String docURL;
private final String id;
private final VersionStatus status;
private final String wadl;
@ConstructorProperties({
"docURL", "id", "status", "wadl"
})
protected Version(String docURL, String id, @Nullable VersionStatus status, @Nullable String wadl) {
this.docURL = checkNotNull(docURL, "docURL");
this.id = checkNotNull(id, "id");
this.status = status == null ? VersionStatus.UNRECOGNIZED : status;
this.wadl = wadl;
}
public String getDocURL() {
return this.docURL;
}
public String getId() {
return this.id;
}
public VersionStatus getStatus() {
return this.status;
}
@Nullable
public String getWadl() {
return this.wadl;
}
@Override
public int hashCode() {
return Objects.hashCode(docURL, id, status, wadl);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Version that = Version.class.cast(obj);
return Objects.equal(this.docURL, that.docURL)
&& Objects.equal(this.id, that.id)
&& Objects.equal(this.status, that.status)
&& Objects.equal(this.wadl, that.wadl);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("docURL", docURL).add("id", id).add("status", status).add("wadl", wadl);
}
@Override
public String toString() {
return string().toString();
}
}

View File

@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
public enum VersionStatus {
BETA, CURRENT, DEPRECATED, UNRECOGNIZED;
public String value() {
return name();
}
public static VersionStatus fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
public enum WeeklyBackup {
DISABLED, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, UNRECOGNIZED;
public String value() {
return name();
}
public static WeeklyBackup fromValue(String v) {
try {
return valueOf(v);
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}

View File

@ -1,90 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.handlers;
import static org.jclouds.http.HttpUtils.releasePayload;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpErrorHandler;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpResponseException;
import org.jclouds.logging.Logger;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.util.Strings2;
/**
* This will parse and set an appropriate exception on the command object.
*/
public class ParseCloudServersErrorFromHttpResponse implements HttpErrorHandler {
@Resource
protected Logger logger = Logger.NULL;
public static final Pattern RESOURCE_PATTERN = Pattern
.compile("^/v1[^/]*/[0-9]+/([^/]+)/([0-9]+)");
public void handleError(HttpCommand command, HttpResponse response) {
Exception exception = new HttpResponseException(command, response);
try {
String content = parseErrorFromContentOrNull(command, response);
exception = content != null ? new HttpResponseException(command, response, content) : exception;
switch (response.getStatusCode()) {
case 401:
exception = new AuthorizationException(exception.getMessage(), exception);
break;
case 404:
if (!command.getCurrentRequest().getMethod().equals("DELETE")) {
String path = command.getCurrentRequest().getEndpoint().getPath();
Matcher matcher = RESOURCE_PATTERN.matcher(path);
String message;
if (matcher.find()) {
message = String.format("%s %s not found", matcher.group(1), matcher.group(2));
} else {
message = path;
}
exception = new ResourceNotFoundException(message);
}
break;
case 409:
exception = new IllegalStateException(content);
break;
default:
exception = new HttpResponseException(command, response, content);
break;
}
} finally {
releasePayload(response);
command.setException(exception);
}
}
String parseErrorFromContentOrNull(HttpCommand command, HttpResponse response) {
if (response.getPayload() != null) {
try {
return Strings2.toStringAndClose(response.getPayload().openStream());
} catch (IOException e) {
logger.warn(e, "exception reading error from response", response);
}
}
return null;
}
}

View File

@ -1,234 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.io.BaseEncoding.base64;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.inject.Inject;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class CreateServerOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
static class File {
private final String path;
private final String contents;
public File(String path, byte[] contents) {
this.path = checkNotNull(path, "path");
this.contents = base64().encode(checkNotNull(contents, "contents"));
checkArgument(path.getBytes().length < 255, String.format(
"maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path.getBytes().length));
checkArgument(contents.length < 10 * 1024, String.format(
"maximum size of the file is 10KB. Contents specified is %d bytes", contents.length));
}
public String getContents() {
return contents;
}
public String getPath() {
return path;
}
}
@SuppressWarnings("unused")
private static class ServerRequest {
final String name;
final int imageId;
final int flavorId;
Map<String, String> metadata;
List<File> personality;
Integer sharedIpGroupId;
Addresses addresses;
private ServerRequest(String name, int imageId, int flavorId) {
this.name = name;
this.imageId = imageId;
this.flavorId = flavorId;
}
}
private Map<String, String> metadata = Maps.newHashMap();
private List<File> files = Lists.newArrayList();
private Integer sharedIpGroupId;
private String publicIp;
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present").toString(),
Integer.parseInt(checkNotNull(postParams.get("imageId"), "imageId parameter not present").toString()),
Integer.parseInt(checkNotNull(postParams.get("flavorId"), "flavorId parameter not present").toString()));
if (!metadata.isEmpty())
server.metadata = metadata;
if (!files.isEmpty())
server.personality = files;
if (sharedIpGroupId != null)
server.sharedIpGroupId = this.sharedIpGroupId;
if (publicIp != null) {
server.addresses = Addresses.builder().publicAddresses(ImmutableSet.of(publicIp)).build();
}
return bindToRequest(request, ImmutableMap.of("server", server));
}
/**
* You may further customize a cloud server by injecting data into the file system of the cloud
* server itself. This is useful, for example, for inserting ssh keys, setting configuration
* files, or storing data that you want to retrieve from within the instance itself. It is
* intended to provide a minimal amount of launch-time personalization. If significant
* customization is required, a custom image should be created. The max size of the file path
* data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents
* should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the
* decoded data not the number of characters in the encoded data. The maximum number of file
* path/content pairs that can be supplied is 5. Any existing files that match the specified file
* will be renamed to include the extension bak followed by a time stamp. For example, the file
* /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and
* the root group as owner and group owner, respectively and will allow user and group read
* access only (-r--r-----).
*/
public CreateServerOptions withFile(String path, byte[] contents) {
checkState(files.size() < 5, "maximum number of files allowed is 5");
files.add(new File(path, contents));
return this;
}
/**
* A shared IP group is a collection of servers that can share IPs with other members of the
* group. Any server in a group can share one or more public IPs with any other server in the
* group. With the exception of the first server in a shared IP group, servers must be launched
* into shared IP groups. A server may only be a member of one shared IP group.
*
* <p/>
* Servers in the same shared IP group can share public IPs for various high availability and
* load balancing configurations. To launch an HA server, include the optional sharedIpGroupId
* element and the server will be launched into that shared IP group.
* <p />
*
* Note: sharedIpGroupId is an optional parameter and for optimal performance, should ONLY be
* specified when intending to share IPs between servers.
*
* @see #withSharedIp(String)
*/
public CreateServerOptions withSharedIpGroup(int id) {
checkArgument(id > 0, "id must be positive or zero. was: " + id);
this.sharedIpGroupId = id;
return this;
}
/**
* Custom cloud server metadata can also be supplied at launch time. This metadata is stored in
* the API system where it is retrievable by querying the API for server status. The maximum size
* of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that
* can be supplied per server is 5.
*/
public CreateServerOptions withMetadata(Map<String, String> metadata) {
checkNotNull(metadata, "metadata");
checkArgument(metadata.size() <= 5, "you cannot have more then 5 metadata values. You specified: "
+ metadata.size());
for (Entry<String, String> entry : metadata.entrySet()) {
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", entry.getKey(), entry
.getKey().getBytes().length));
checkArgument(entry.getKey().getBytes().length < 255, String.format(
"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes", entry
.getKey(), entry.getValue(), entry.getValue().getBytes().length));
}
this.metadata = metadata;
return this;
}
/**
* Public IP addresses can be shared across multiple servers for use in various high availability
* scenarios. When an IP address is shared to another server, the cloud network restrictions are
* modified to allow each server to listen to and respond on that IP address (you may optionally
* specify that the target server network configuration be modified). Shared IP addresses can be
* used with many standard heartbeat facilities (e.g. keepalived) that monitor for failure and
* manage IP failover.
*
* <p/>
* If you intend to use a shared IP on the server being created and have no need for a separate
* public IP address, you may launch the server into a shared IP group and specify an IP address
* from that shared IP group to be used as its public IP. You can accomplish this by specifying
* the public shared IP address in your request. This is optional and is only valid if
* sharedIpGroupId is also supplied.
*/
public CreateServerOptions withSharedIp(String publicIp) {
checkState(sharedIpGroupId != null, "sharedIp is invalid unless a shared ip group is specified.");
this.publicIp = checkNotNull(publicIp, "ip");
return this;
}
public static class Builder {
/**
* @see CreateServerOptions#withFile(String,byte[])
*/
public static CreateServerOptions withFile(String path, byte[] contents) {
CreateServerOptions options = new CreateServerOptions();
return options.withFile(path, contents);
}
/**
* @see CreateServerOptions#withSharedIpGroup(int)
*/
public static CreateServerOptions withSharedIpGroup(int id) {
CreateServerOptions options = new CreateServerOptions();
return options.withSharedIpGroup(id);
}
/**
* @see CreateServerOptions#withMetadata(Map<String, String>)
*/
public static CreateServerOptions withMetadata(Map<String, String> metadata) {
CreateServerOptions options = new CreateServerOptions();
return options.withMetadata(metadata);
}
/**
* @see CreateServerOptions#withSharedIp(String)
*/
public static CreateServerOptions withSharedIp(String publicIp) {
CreateServerOptions options = new CreateServerOptions();
return options.withSharedIp(publicIp);
}
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
return jsonBinder.bindToRequest(request, input);
}
}

View File

@ -1,84 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
public class CreateSharedIpGroupOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
Integer serverId;
@SuppressWarnings("unused")
private static class SharedIpGroupRequest {
final String name;
Integer server;
private SharedIpGroupRequest(String name, @Nullable Integer serverId) {
this.name = name;
this.server = serverId;
}
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams.get("name")).toString(), serverId);
return jsonBinder.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest));
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
throw new IllegalStateException("CreateSharedIpGroup is a POST operation");
}
/**
*
* @param id
* of the server to include with this request.
*/
public CreateSharedIpGroupOptions withServer(int id) {
checkArgument(id > 0, "server id must be a positive number");
this.serverId = id;
return this;
}
public static class Builder {
/**
* @see CreateSharedIpGroupOptions#withServer(int)
*/
public static CreateSharedIpGroupOptions withServer(int id) {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
return options.withServer(id);
}
}
}

View File

@ -1,106 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import java.util.Date;
import org.jclouds.openstack.options.BaseListOptions;
/**
* Options used to control the amount of detail in the request.
*
* @see BaseListOptions
* @see <a href="http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf" />
*/
public class ListOptions extends BaseListOptions {
public static final ListOptions NONE = new ListOptions();
/**
* unless used, only the name and id will be returned per row.
*
* @return
*/
public ListOptions withDetails() {
this.pathSuffix = "/detail";
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ListOptions changesSince(Date ifModifiedSince) {
super.changesSince(ifModifiedSince);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ListOptions maxResults(int limit) {
super.maxResults(limit);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ListOptions startAt(long offset) {
super.startAt(offset);
return this;
}
public static class Builder {
/**
* @see ListOptions#withDetails()
*/
public static ListOptions withDetails() {
ListOptions options = new ListOptions();
return options.withDetails();
}
/**
* @see BaseListOptions#startAt(long)
*/
public static ListOptions startAt(long prefix) {
ListOptions options = new ListOptions();
return options.startAt(prefix);
}
/**
* @see BaseListOptions#maxResults(long)
*/
public static ListOptions maxResults(int maxKeys) {
ListOptions options = new ListOptions();
return options.maxResults(maxKeys);
}
/**
* @see BaseListOptions#changesSince(Date)
*/
public static ListOptions changesSince(Date since) {
ListOptions options = new ListOptions();
return options.changesSince(since);
}
}
}

View File

@ -1,71 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToJsonPayload;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
public class RebuildServerOptions implements MapBinder {
@Inject
private BindToJsonPayload jsonBinder;
Integer imageId;
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
Map<String, Integer> image = Maps.newHashMap();
if (imageId != null)
image.put("imageId", imageId);
return jsonBinder.bindToRequest(request, ImmutableMap.of("rebuild", image));
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
throw new IllegalStateException("RebuildServer is a POST operation");
}
/**
*
* @param id
* of the image to rebuild the server with.
*/
public RebuildServerOptions withImage(int id) {
checkArgument(id > 0, "server id must be a positive number");
this.imageId = id;
return this;
}
public static class Builder {
/**
* @see RebuildServerOptions#withImage(int)
*/
public static RebuildServerOptions withImage(int id) {
RebuildServerOptions options = new RebuildServerOptions();
return options.withImage(id);
}
}
}

View File

@ -1,62 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Singleton;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.inject.Inject;
/**
*
* Tests to see if a task succeeds.
*/
@Singleton
public class ServerActive implements Predicate<Server> {
private final CloudServersClient client;
@Resource
protected Logger logger = Logger.NULL;
@Inject
public ServerActive(CloudServersClient client) {
this.client = client;
}
public boolean apply(Server server) {
logger.trace("looking for state on server %s", checkNotNull(server, "server"));
server = refresh(server);
if (server == null)
return false;
logger.trace("%s: looking for server state %s: currently: %s", server.getId(),
ServerStatus.ACTIVE, server.getStatus());
return server.getStatus() == ServerStatus.ACTIVE;
}
private Server refresh(Server server) {
return client.getServer(server.getId());
}
}

View File

@ -1,62 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Singleton;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.inject.Inject;
/**
*
* Tests to see if a task succeeds.
*/
@Singleton
public class ServerDeleted implements Predicate<Server> {
private final CloudServersClient client;
@Resource
protected Logger logger = Logger.NULL;
@Inject
public ServerDeleted(CloudServersClient client) {
this.client = client;
}
public boolean apply(Server server) {
logger.trace("looking for state on server %s", checkNotNull(server, "server"));
server = refresh(server);
if (server == null)
return true;
logger.trace("%s: looking for server state %s: currently: %s", server.getId(),
ServerStatus.DELETED, server.getStatus());
return server.getStatus() == ServerStatus.DELETED;
}
private Server refresh(Server server) {
return client.getServer(server.getId());
}
}

View File

@ -1 +0,0 @@
org.jclouds.cloudservers.CloudServersApiMetadata

View File

@ -1,28 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers;
import org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "CloudServersApiMetadataTest")
public class CloudServersApiMetadataTest extends BaseComputeServiceApiMetadataTest {
public CloudServersApiMetadataTest() {
super(new CloudServersApiMetadata());
}
}

View File

@ -1,606 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.cloudservers.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.jclouds.cloudservers.options.ListOptions.Builder.withDetails;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Set;
import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.cloudservers.domain.DailyBackup;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.cloudservers.domain.Image;
import org.jclouds.cloudservers.domain.ImageStatus;
import org.jclouds.cloudservers.domain.Limits;
import org.jclouds.cloudservers.domain.RebootType;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.cloudservers.domain.SharedIpGroup;
import org.jclouds.cloudservers.domain.WeeklyBackup;
import org.jclouds.cloudservers.options.RebuildServerOptions;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payload;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshException;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.util.Strings2;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.net.HostAndPort;
import com.google.inject.Injector;
import com.google.inject.Module;
/**
* Tests behavior of {@code CloudServersClient}
*/
@Test(groups = "live", singleThreaded = true, testName = "CloudServersClientLiveTest")
public class CloudServersClientLiveTest extends BaseComputeServiceContextLiveTest {
public CloudServersClientLiveTest() {
provider = "cloudservers";
}
protected CloudServersClient client;
protected SshClient.Factory sshFactory;
protected Predicate<HostAndPort> socketTester;
@BeforeGroups(groups = { "integration", "live" })
@Override
public void setupContext() {
super.setupContext();
Injector injector = view.utils().injector();
client = injector.getInstance(CloudServersClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = retry(socketOpen, 120, 1, SECONDS);
injector.injectMembers(socketOpen); // add logger
}
public void testLimits() throws Exception {
Limits response = client.getLimits();
assert null != response;
assertTrue(!response.getAbsolute().isEmpty());
assertTrue(!response.getRate().isEmpty());
}
public void testListServers() throws Exception {
Set<Server> response = client.listServers();
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
public void testListServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
public void testListImages() throws Exception {
Set<Image> response = client.listImages();
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 1);
for (Image image : response) {
assertTrue(image.getId() >= 0);
assert null != image.getName() : image;
}
}
public void testListImagesDetail() throws Exception {
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
assertTrue(image.getId() >= 1);
assert null != image.getName() : image;
assert null != image.getStatus() : image;
}
}
public void testGetImagesDetail() throws Exception {
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
Image newDetails = client.getImage(image.getId());
assertEquals(image, newDetails);
}
}
@Test
public void testGetImageDetailsNotFound() throws Exception {
assert client.getImage(12312987) == null;
}
@Test
public void testGetServerDetailsNotFound() throws Exception {
assert client.getServer(12312987) == null;
}
public void testGetServersDetail() throws Exception {
Set<Server> response = client.listServers(withDetails());
assert null != response;
long serverCount = response.size();
assertTrue(serverCount >= 0);
for (Server server : response) {
Server newDetails = client.getServer(server.getId());
assertEquals(server, newDetails);
}
}
public void testListFlavors() throws Exception {
Set<Flavor> response = client.listFlavors();
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 1);
for (Flavor flavor : response) {
assertTrue(flavor.getId() >= 0);
assert null != flavor.getName() : flavor;
}
}
public void testListFlavorsDetail() throws Exception {
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
for (Flavor flavor : response) {
assertTrue(flavor.getId() >= 1);
assert null != flavor.getName() : flavor;
assert null != flavor.getDisk() : flavor;
assert null != flavor.getRam() : flavor;
}
}
public void testGetFlavorsDetail() throws Exception {
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
for (Flavor flavor : response) {
Flavor newDetails = client.getFlavor(flavor.getId());
assertEquals(flavor, newDetails);
}
}
@Test
public void testGetFlavorDetailsNotFound() throws Exception {
assert client.getFlavor(12312987) == null;
}
public void testListSharedIpGroups() throws Exception {
Set<SharedIpGroup> response = client.listSharedIpGroups();
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
for (SharedIpGroup sharedIpGroup : response) {
assertTrue(sharedIpGroup.getId() >= 0);
assert null != sharedIpGroup.getName() : sharedIpGroup;
}
}
public void testListSharedIpGroupsDetail() throws Exception {
Set<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
for (SharedIpGroup sharedIpGroup : response) {
assertTrue(sharedIpGroup.getId() >= 1);
assert null != sharedIpGroup.getName() : sharedIpGroup;
assert null != sharedIpGroup.getServers() : sharedIpGroup;
}
}
public void testGetSharedIpGroupsDetail() throws Exception {
Set<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
for (SharedIpGroup sharedIpGroup : response) {
SharedIpGroup newDetails = client.getSharedIpGroup(sharedIpGroup.getId());
assertEquals(sharedIpGroup, newDetails);
}
}
@Test
public void testGetSharedIpGroupDetailsNotFound() throws Exception {
assert client.getSharedIpGroup(12312987) == null;
}
@Test(timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testCreateSharedIpGroup() throws Exception {
SharedIpGroup sharedIpGroup = null;
while (sharedIpGroup == null) {
String sharedIpGroupName = serverPrefix + "createSharedIpGroup" + new SecureRandom().nextInt();
try {
sharedIpGroup = client.createSharedIpGroup(sharedIpGroupName, withServer(serverId));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
continue;
throw e;
}
}
assertNotNull(sharedIpGroup.getName());
sharedIpGroupId = sharedIpGroup.getId();
// Response doesn't include the server id Web Hosting #119311
assert !sharedIpGroup.getServers().equals(ImmutableList.of(serverId));
}
private int sharedIpGroupId;
private String serverPrefix = System.getProperty("user.name") + ".cs";
private int serverId;
private String adminPass;
Map<String, String> metadata = ImmutableMap.of("jclouds", "rackspace");
private String ip;
private int serverId2;
private String adminPass2;
private int imageId;
public void testCreateServer() throws Exception {
int imageId = 14362;
int flavorId = 1;
Server server = null;
while (server == null) {
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
try {
server = client.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
continue;
throw e;
}
}
assertNotNull(server.getAdminPass());
serverId = server.getId();
adminPass = server.getAdminPass();
ip = server.getAddresses().getPublicAddresses().iterator().next();
assertEquals(server.getStatus(), ServerStatus.BUILD);
blockUntilServerActive(serverId);
}
private void blockUntilServerActive(int serverId) throws InterruptedException {
Server currentDetails = null;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
private void blockUntilServerVerifyResize(int serverId) throws InterruptedException {
Server currentDetails = null;
for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client
.getServer(serverId)) {
System.out.printf("blocking on status verify resize%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
private void blockUntilImageActive(int imageId) throws InterruptedException {
Image currentDetails = null;
for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client
.getImage(imageId)) {
System.out.printf("blocking on status active%n%s%n", currentDetails);
Thread.sleep(5 * 1000);
}
}
@Test(timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testServerDetails() throws Exception {
Server server = client.getServer(serverId);
assertNotNull(server.getHostId());
assertEquals(server.getStatus(), ServerStatus.ACTIVE);
assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress();
assertEquals(Integer.valueOf(14362), server.getImageId());
assertEquals(Integer.valueOf(1), server.getFlavorId());
assertNotNull(server.getAddresses());
// listAddresses tests..
assertEquals(client.getAddresses(serverId), server.getAddresses());
assertEquals(server.getAddresses().getPublicAddresses().size(), 1);
assertEquals(client.listPublicAddresses(serverId), server.getAddresses().getPublicAddresses());
assertEquals(server.getAddresses().getPrivateAddresses().size(), 1);
assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses());
// check metadata
assertEquals(server.getMetadata(), metadata);
checkPassOk(server, adminPass);
}
/**
* this tests "personality" as the file looked up was sent during server creation
*/
private void checkPassOk(Server newDetails, String pass) throws IOException {
try {
doCheckPass(newDetails, pass);
} catch (SshException e) {// try twice in case there is a network timeout
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e1) {
}
doCheckPass(newDetails, pass);
}
}
private void doCheckPass(Server newDetails, String pass) throws IOException {
HostAndPort socket = HostAndPort.fromParts(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, LoginCredentials.builder().user("root").password(pass).build());
try {
client.connect();
Payload etcPasswd = client.get("/etc/jclouds.txt");
String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.openStream());
assertEquals("rackspace", etcPasswdContents.trim());
} finally {
if (client != null)
client.disconnect();
}
}
private ExecResponse exec(Server details, String pass, String command) throws IOException {
HostAndPort socket = HostAndPort.fromParts(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, LoginCredentials.builder().user("root").password(pass).build());
try {
client.connect();
return client.exec(command);
} finally {
if (client != null)
client.disconnect();
}
}
@Test(timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testRenameServer() throws Exception {
Server server = client.getServer(serverId);
String oldName = server.getName();
client.renameServer(serverId, oldName + "new");
blockUntilServerActive(serverId);
assertEquals(oldName + "new", client.getServer(serverId).getName());
}
@Test(timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer")
public void testChangePassword() throws Exception {
client.changeAdminPass(serverId, "elmo");
blockUntilServerActive(serverId);
checkPassOk(client.getServer(serverId), "elmo");
this.adminPass = "elmo";
}
@Test(timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateSharedIpGroup")
public void testCreateServerIp() throws Exception {
int imageId = 14362;
int flavorId = 1;
Server server = null;
while (server == null) {
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
try {
server = client
.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt", "rackspace".getBytes())
.withMetadata(metadata).withSharedIpGroup(sharedIpGroupId).withSharedIp(ip));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
continue;
throw e;
}
}
assertNotNull(server.getAdminPass());
serverId2 = server.getId();
adminPass2 = server.getAdminPass();
blockUntilServerActive(serverId2);
assertIpConfigured(server, adminPass2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses() + " doesn't contain " + ip;
assertEquals(server.getSharedIpGroupId(), Integer.valueOf(sharedIpGroupId));
}
private void assertIpConfigured(Server server, String password) {
try {
ExecResponse response = exec(server, password, "ifconfig -a");
assert response.getOutput().indexOf(ip) > 0 : String.format("server %s didn't get ip %s%n%s", server, ip,
response);
} catch (Exception e) {
e.printStackTrace();
} catch (AssertionError e) {
e.printStackTrace();
}
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateServerIp")
public void testUnshare() throws Exception {
client.unshareIp(ip, serverId2);
blockUntilServerActive(serverId2);
Server server = client.getServer(serverId2);
assert !server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses();
assertIpNotConfigured(server, adminPass2);
}
private void assertIpNotConfigured(Server server, String password) {
try {
ExecResponse response = exec(server, password, "ifconfig -a");
assert response.getOutput().indexOf(ip) == -1 : String.format("server %s still has get ip %s%n%s", server, ip,
response);
} catch (Exception e) {
e.printStackTrace();
} catch (AssertionError e) {
e.printStackTrace();
}
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testUnshare")
public void testShareConfig() throws Exception {
client.shareIp(ip, serverId2, sharedIpGroupId, true);
blockUntilServerActive(serverId2);
Server server = client.getServer(serverId2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses();
assertIpConfigured(server, adminPass2);
testUnshare();
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareConfig")
public void testShareNoConfig() throws Exception {
client.shareIp(ip, serverId2, sharedIpGroupId, false);
blockUntilServerActive(serverId2);
Server server = client.getServer(serverId2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses();
assertIpNotConfigured(server, adminPass2);
testUnshare();
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareNoConfig")
public void testBackup() throws Exception {
assertEquals(BackupSchedule.builder().build(), client.getBackupSchedule(serverId));
BackupSchedule dailyWeekly = BackupSchedule.builder().enabled(true).weekly(WeeklyBackup.FRIDAY).daily(DailyBackup.H_0400_0600).build();
client.replaceBackupSchedule(serverId, dailyWeekly);
client.deleteBackupSchedule(serverId);
// disables, doesn't delete: Web Hosting #119571
assertEquals(client.getBackupSchedule(serverId).isEnabled(), false);
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup")
public void testCreateImage() throws Exception {
Image image = client.createImageFromServer("hoofie", serverId);
assertEquals("hoofie", image.getName());
assertEquals(Integer.valueOf(serverId), image.getServerId());
imageId = image.getId();
blockUntilImageActive(imageId);
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage")
public void testRebuildServer() throws Exception {
client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId));
blockUntilServerActive(serverId);
// issue Web Hosting #119580 imageId comes back incorrect after rebuild
assert !Integer.valueOf(imageId).equals(client.getServer(serverId).getImageId());
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer")
public void testRebootHard() throws Exception {
client.rebootServer(serverId, RebootType.HARD);
blockUntilServerActive(serverId);
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard")
public void testRebootSoft() throws Exception {
client.rebootServer(serverId, RebootType.SOFT);
blockUntilServerActive(serverId);
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft")
public void testRevertResize() throws Exception {
client.resizeServer(serverId, 2);
blockUntilServerVerifyResize(serverId);
client.revertResizeServer(serverId);
blockUntilServerActive(serverId);
assertEquals(Integer.valueOf(1), client.getServer(serverId).getFlavorId());
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft")
public void testConfirmResize() throws Exception {
client.resizeServer(serverId2, 2);
blockUntilServerVerifyResize(serverId2);
client.confirmResizeServer(serverId2);
blockUntilServerActive(serverId2);
assertEquals(Integer.valueOf(2), client.getServer(serverId2).getFlavorId());
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = { "testRebootSoft", "testRevertResize", "testConfirmResize" })
void deleteServer2() {
if (serverId2 > 0) {
client.deleteServer(serverId2);
assert client.getServer(serverId2) == null;
}
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2")
void testDeleteImage() {
if (imageId > 0) {
client.deleteImage(imageId);
assert client.getImage(imageId) == null;
}
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage")
void deleteServer1() {
if (serverId > 0) {
client.deleteServer(serverId);
assert client.getServer(serverId) == null;
}
}
@Test(timeOut = 10 * 60 * 1000, dependsOnMethods = { "deleteServer1" })
void testDeleteSharedIpGroup() {
if (sharedIpGroupId > 0) {
client.deleteSharedIpGroup(sharedIpGroupId);
assert client.getSharedIpGroup(sharedIpGroupId) == null;
}
}
@AfterTest
void deleteServersOnEnd() {
if (serverId > 0) {
client.deleteServer(serverId);
}
if (serverId2 > 0) {
client.deleteServer(serverId2);
}
if (sharedIpGroupId > 0) {
client.deleteSharedIpGroup(sharedIpGroupId);
}
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
}

View File

@ -1,898 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers;
import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withMetadata;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withSharedIpGroup;
import static org.jclouds.cloudservers.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.jclouds.cloudservers.options.ListOptions.Builder.changesSince;
import static org.jclouds.cloudservers.options.ListOptions.Builder.withDetails;
import static org.jclouds.cloudservers.options.RebuildServerOptions.Builder.withImage;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import static org.jclouds.reflect.Reflection2.method;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;
import javax.inject.Singleton;
import javax.ws.rs.core.MediaType;
import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;
import org.jclouds.Fallbacks.FalseOnNotFoundOr404;
import org.jclouds.Fallbacks.NullOnNotFoundOr404;
import org.jclouds.Fallbacks.VoidOnNotFoundOr404;
import org.jclouds.apis.ApiMetadata;
import org.jclouds.cloudservers.config.CloudServersHttpApiModule;
import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.cloudservers.domain.DailyBackup;
import org.jclouds.cloudservers.domain.RebootType;
import org.jclouds.cloudservers.domain.WeeklyBackup;
import org.jclouds.cloudservers.options.CreateServerOptions;
import org.jclouds.cloudservers.options.CreateSharedIpGroupOptions;
import org.jclouds.cloudservers.options.ListOptions;
import org.jclouds.cloudservers.options.RebuildServerOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.openstack.filters.AddTimestampQuery;
import org.jclouds.openstack.filters.AuthenticateRequest;
import org.jclouds.openstack.keystone.v1_1.config.AuthenticationServiceModule.GetAuth;
import org.jclouds.openstack.keystone.v1_1.domain.Auth;
import org.jclouds.openstack.keystone.v1_1.parse.ParseAuthTest;
import org.jclouds.rest.ConfiguresHttpApi;
import org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.reflect.Invokable;
import com.google.inject.Module;
import com.google.inject.Provides;
@Test(groups = "unit", singleThreaded = true, testName = "CloudServersClientTest")
public class CloudServersClientTest extends BaseRestAnnotationProcessingTest<CloudServersClient> {
public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createServer", String.class, int.class, int.class,
CreateServerOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie", 2, 1));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createServer", String.class, int.class, int.class,
CreateServerOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie", 2, 1, withSharedIpGroup(2)));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createServer", String.class, int.class, int.class,
CreateServerOptions[].class);
GeneratedHttpRequest request = processor
.createRequest(method, ImmutableList.<Object> of("ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes())));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createServer", String.class, int.class, int.class,
CreateServerOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie", 2, 1,
withMetadata(ImmutableMap.of("foo", "bar"))));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testCreateServerWithIpGroupAndSharedIp() throws IOException, SecurityException, NoSuchMethodException,
UnknownHostException {
Invokable<?, ?> method = method(CloudServersClient.class, "createServer", String.class, int.class, int.class,
CreateServerOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie", 2, 1,
withSharedIpGroup(2).withSharedIp("127.0.0.1")));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "deleteImage", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "DELETE https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, FalseOnNotFoundOr404.class);
checkFilters(request);
}
public void testLimits() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getLimits");
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/limits?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(request);
}
public void testListServers() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listServers", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
Date now = new Date(10000000l);
public void testListServersOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listServers", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListServersDetail() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listServers", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails()));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testGetServer() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getServer", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(request);
}
public void testListFlavors() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listFlavors", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/flavors?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListFlavorsOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listFlavors", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListFlavorsDetail() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listFlavors", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails()));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/flavors/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListFlavorsDetailOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listFlavors", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails().changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/flavors/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testGetFlavor() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getFlavor", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/flavors/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(request);
}
public void testListImages() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listImages", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListImagesDetail() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listImages", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails()));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListImagesOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listImages", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListImagesDetailOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listImages", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails().changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testGetImage() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getImage", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(request);
}
public void testDeleteServer() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "deleteServer", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "DELETE https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, FalseOnNotFoundOr404.class);
checkFilters(request);
}
public void testShareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException {
Invokable<?, ?> method = method(CloudServersClient.class, "shareIp", String.class, int.class, int.class,
boolean.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("127.0.0.1", 2, 3, false));
assertRequestLineEquals(request, "PUT https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":false}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testShareIpConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException {
Invokable<?, ?> method = method(CloudServersClient.class, "shareIp", String.class, int.class, int.class,
boolean.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("127.0.0.1", 2, 3, true));
assertRequestLineEquals(request, "PUT https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":true}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testUnshareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException,
UnknownHostException {
Invokable<?, ?> method = method(CloudServersClient.class, "unshareIp", String.class, int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("127.0.0.1", 2, 3, false));
assertRequestLineEquals(request, "DELETE https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);
checkFilters(request);
}
public void testReplaceBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "replaceBackupSchedule", int.class, BackupSchedule.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2, BackupSchedule.builder().weekly(WeeklyBackup.MONDAY)
.daily(DailyBackup.H_0800_1000).enabled(true).build()));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/backup_schedule HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request,
"{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(request);
}
public void testDeleteBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "deleteBackupSchedule", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "DELETE https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/backup_schedule HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, FalseOnNotFoundOr404.class);
checkFilters(request);
}
public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "changeAdminPass", int.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2, "foo"));
assertRequestLineEquals(request, "PUT https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testChangeServerName() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "renameServer", int.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2, "foo"));
assertRequestLineEquals(request, "PUT https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testListSharedIpGroups() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listSharedIpGroups", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListSharedIpGroupsOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listSharedIpGroups", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListSharedIpGroupsDetail() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listSharedIpGroups", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails()));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups/detail?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListSharedIpGroupsDetailOptions() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listSharedIpGroups", ListOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withDetails().changesSince(now).maxResults(1).startAt(2)));
assertRequestLineEquals(request,
"GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testGetSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getSharedIpGroup", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups/2?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(request);
}
public void testCreateSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createSharedIpGroup", String.class,
CreateSharedIpGroupOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie"));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testCreateSharedIpGroupWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createSharedIpGroup", String.class,
CreateSharedIpGroupOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie", withServer(2)));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\",\"server\":2}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testDeleteSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "deleteSharedIpGroup", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "DELETE https://lon.servers.api.rackspacecloud.com/v1.0/10001786/shared_ip_groups/2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, FalseOnNotFoundOr404.class);
checkFilters(request);
}
public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getAddresses", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/ips?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testListPublicAddresses() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listPublicAddresses", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/ips/public?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "listPrivateAddresses", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/ips/private?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testListBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "getBackupSchedule", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "GET https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/backup_schedule?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(request);
}
public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "createImageFromServer", String.class, int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("ralphie", 2));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON,
false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "rebuildServer", int.class,
RebuildServerOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(3));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/3/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "rebuildServer", int.class,
RebuildServerOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(3, withImage(2)));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/3/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testReboot() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "rebootServer", int.class, RebootType.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2, RebootType.HARD));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testResize() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "resizeServer", int.class, int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2, 3));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testConfirmResize() throws IOException, IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "confirmResizeServer", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testRevertResize() throws IOException, SecurityException, NoSuchMethodException {
Invokable<?, ?> method = method(CloudServersClient.class, "revertResizeServer", int.class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(2));
assertRequestLineEquals(request, "POST https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/2/action?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
@Override
protected void checkFilters(HttpRequest request) {
assertEquals(request.getFilters().size(), 2);
assertEquals(request.getFilters().get(0).getClass(), AuthenticateRequest.class);
assertEquals(request.getFilters().get(1).getClass(), AddTimestampQuery.class);
}
@Override
protected Module createModule() {
return new TestCloudServersHttpApiModule();
}
@ConfiguresHttpApi
protected static class TestCloudServersHttpApiModule extends CloudServersHttpApiModule {
@Provides
@Singleton
GetAuth provideGetAuth() {
return new GetAuth(null) {
@Override
public Auth load(Credentials in) {
return new ParseAuthTest().expected();
}
};
}
}
protected String provider = "cloudservers";
@Override
protected ApiMetadata createApiMetadata() {
return new CloudServersApiMetadata();
}
@Override
protected Properties setupProperties() {
Properties overrides = new Properties();
overrides.setProperty(PROPERTY_REGIONS, "US");
overrides.setProperty(PROPERTY_API_VERSION, "1");
overrides.setProperty(provider + ".endpoint", "https://auth");
return overrides;
}
}

View File

@ -1,50 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers;
import java.net.URI;
import org.jclouds.cloudservers.internal.BaseCloudServersRestClientExpectTest;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
@Test(groups = "unit", testName = "CloudServersExpectTest")
public class CloudServersExpectTest extends BaseCloudServersRestClientExpectTest {
public void deleteImageReturnsTrueOn200AndFalseOn404() {
HttpRequest deleteImage11 = HttpRequest.builder().method("DELETE").endpoint(
URI.create("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/11?now=1257695648897")).headers(
ImmutableMultimap.<String, String> builder()
.put("X-Auth-Token", authToken).build()).build();
HttpResponse imageDeleted = HttpResponse.builder().statusCode(204).message("HTTP/1.1 204 No Content").build();
CloudServersClient clientWhenImageExists = requestsSendResponses(initialAuth, responseWithAuth, deleteImage11, imageDeleted);
assert clientWhenImageExists.deleteImage(11);
HttpResponse imageNotFound = HttpResponse.builder().statusCode(404).message("HTTP/1.1 404 Not Found").build();
CloudServersClient clientWhenImageDoesntExist = requestsSendResponses(initialAuth, responseWithAuth, deleteImage11, imageNotFound);
assert !clientWhenImageDoesntExist.deleteImage(11);
}
}

View File

@ -1,83 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.internal.BaseComputeServiceLiveTest;
import org.jclouds.domain.LocationScope;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.Test;
import com.google.inject.Module;
/**
*
* Generally disabled, as it incurs higher fees.
*/
@Test(groups = "live", enabled = true, singleThreaded = true, testName = "CloudServersComputeServiceLiveTest")
public class CloudServersComputeServiceLiveTest extends BaseComputeServiceLiveTest {
public CloudServersComputeServiceLiveTest() {
provider = "cloudservers";
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
@Override
protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String group, String task) throws IOException {
super.checkNodes(nodes, group, task);
for (NodeMetadata node : nodes) {
assertEquals(node.getLocation().getScope(), LocationScope.HOST);
}
}
@Test(enabled = true, dependsOnMethods = "testReboot", expectedExceptions = UnsupportedOperationException.class)
public void testSuspendResume() throws Exception {
super.testSuspendResume();
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testGetNodesWithDetails() throws Exception {
super.testGetNodesWithDetails();
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testListNodes() throws Exception {
super.testListNodes();
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testListNodesByIds() throws Exception {
super.testListNodesByIds();
}
@Test(enabled = true, dependsOnMethods = { "testListNodes", "testGetNodesWithDetails", "listNodesByIds" })
@Override
public void testDestroyNodes() {
super.testDestroyNodes();
}
}

View File

@ -1,32 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.config;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "CloudServersComputeServiceContextModuleTest")
public class CloudServersComputeServiceContextModuleTest {
public void testAllStatusCovered() {
for (ServerStatus state : ServerStatus.values()) {
assert CloudServersComputeServiceContextModule.toPortableNodeStatus.containsKey(state) : state;
}
}
}

View File

@ -1,88 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.extensions;
import static org.testng.Assert.assertEquals;
import org.jclouds.cloudservers.internal.BaseCloudServersComputeServiceExpectTest;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.net.HttpHeaders;
import com.google.common.util.concurrent.Futures;
@Test(groups = "unit", testName = "CloudServersImageExtensionExpectTest")
public class CloudServersImageExtensionExpectTest extends BaseCloudServersComputeServiceExpectTest<ComputeService> {
private HttpRequest getServerDetail = HttpRequest.builder().method("GET")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/1234?format=json&now=1257695648897")
.addHeader(HttpHeaders.ACCEPT, "application/json")
.addHeader("X-Auth-Token", authToken).build();
private HttpResponse getServerResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/test_get_server_detail.json")).build();
HttpRequest createImage = HttpRequest.builder().method("POST")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images?format=json&now=1257695648897")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken)
.payload(
payloadFromStringWithContentType(
"{\"image\":{\"serverId\":1234,\"name\":\"test\"}}",
"application/json")).build();
HttpResponse createImageResponse = HttpResponse.builder().statusCode(200)
.payload(
payloadFromStringWithContentType(
"{\"image\":{\"id\":2,\"serverId\":1234,\"name\":\"test\",\"status\":\"SAVING\"}}",
"application/json")).build();
private HttpRequest getImage = HttpRequest.builder().method("GET")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/2?format=json&now=1257695648897")
.addHeader(HttpHeaders.ACCEPT, "application/json")
.addHeader("X-Auth-Token", authToken).build();
private HttpResponse getImageResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/test_get_image_active.json")).build();
public void testCreateImage() {
Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();
requestResponseMap.put(initialAuth, responseWithAuth);
requestResponseMap.put(getServerDetail, getServerResponse).build();
requestResponseMap.put(createImage, createImageResponse).build();
requestResponseMap.put(getImage, getImageResponse).build();
ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap.build()).getImageExtension().get();
ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode("test", "1234");
Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));
assertEquals(image.getId(), "2");
}
public ComputeService apply(ComputeServiceContext input) {
return input.getComputeService();
}
}

View File

@ -1,40 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.extensions;
import org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.Test;
import com.google.inject.Module;
/**
* Live test for cloudservers {@link ImageExtension} implementation
*/
@Test(groups = "live", singleThreaded = true, testName = "CloudServersImageExtensionLiveTest")
public class CloudServersImageExtensionLiveTest extends BaseImageExtensionLiveTest {
public CloudServersImageExtensionLiveTest() {
provider = "cloudservers";
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
}

View File

@ -1,59 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import static org.testng.Assert.assertEquals;
import org.jclouds.cloudservers.compute.config.CloudServersComputeServiceContextModule;
import org.jclouds.cloudservers.functions.ParseImageFromJsonResponseTest;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.inject.Guice;
@Test(groups = "unit", testName = "CloudServersImageToImageTest")
public class CloudServersImageToImageTest {
@Test
public void test() {
Image toTest = convertImage();
assertEquals(toTest, new ImageBuilder().name("CentOS 5.2").operatingSystem(
new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(
true).build()).description("CentOS 5.2").ids("2").status(Image.Status.PENDING).version(
"1286712000000").build());
assertEquals(toTest.getStatus(), Image.Status.PENDING);
}
public static Image convertImage() {
org.jclouds.cloudservers.domain.Image image = ParseImageFromJsonResponseTest.parseImage();
CloudServersImageToImage parser = new CloudServersImageToImage(
CloudServersComputeServiceContextModule.toPortableImageStatus, new CloudServersImageToOperatingSystem(
new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(
new GsonModule()).getInstance(Json.class))));
return parser.apply(image);
}
}

View File

@ -1,56 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.cloudservers.functions.ParseFlavorFromJsonResponseTest;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
@Test(groups = "unit")
public class FlavorToHardwareTest {
Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build();
@Test
public void test() throws UnknownHostException {
assertEquals(convertFlavor(), new HardwareBuilder().ids("1").name("256 MB Server").processors(
ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes(
ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true)
.build())).build());
}
public static Hardware convertFlavor() {
Flavor flavor = ParseFlavorFromJsonResponseTest.parseFlavor();
FlavorToHardware parser = new FlavorToHardware();
return parser.apply(flavor);
}
}

View File

@ -1,163 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.compute.functions;
import static org.testng.Assert.assertEquals;
import java.util.Map;
import java.util.Set;
import org.jclouds.cloudservers.compute.config.CloudServersComputeServiceContextModule;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.cloudservers.functions.ParseServerFromJsonResponseTest;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.compute.domain.NodeMetadata.Status;
import org.jclouds.compute.functions.GroupNamingConvention;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
@Test(groups = "unit", testName = "ServerToNodeMetadataTest")
public class ServerToNodeMetadataTest {
Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build();
GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);
@Test
public void testApplyWhereImageAndHardwareNotFound() {
Map<ServerStatus, Status> serverStateToNodeStatus = CloudServersComputeServiceContextModule.toPortableNodeStatus;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);
NodeMetadata metadata = parser.apply(server);
assertEquals(
metadata,
new NodeMetadataBuilder()
.status(Status.PENDING)
.publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131"))
.privateAddresses(ImmutableSet.of("10.176.42.16"))
.imageId("2")
.id("1234")
.providerId("1234")
.name("sample-server")
.group("sample")
.hostname("sample-server")
.location(
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
}
@Test
public void testApplyWhereImageFoundAndHardwareNotFound() {
Map<ServerStatus, Status> serverStateToNodeStatus = CloudServersComputeServiceContextModule.toPortableNodeStatus;
org.jclouds.compute.domain.Image jcImage = CloudServersImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);
NodeMetadata metadata = parser.apply(server);
assertEquals(
metadata,
new NodeMetadataBuilder()
.status(Status.PENDING)
.publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131"))
.privateAddresses(ImmutableSet.of("10.176.42.16"))
.imageId("2")
.operatingSystem(
new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2")
.is64Bit(true).build())
.id("1234")
.providerId("1234")
.name("sample-server")
.hostname("sample-server")
.group("sample")
.location(
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
}
@Test
public void testApplyWhereImageAndHardwareFound() {
Map<ServerStatus, Status> serverStateToNodeStatus = CloudServersComputeServiceContextModule.toPortableNodeStatus;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(CloudServersImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);
NodeMetadata metadata = parser.apply(server);
assertEquals(
metadata,
new NodeMetadataBuilder()
.status(Status.PENDING)
.publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131"))
.privateAddresses(ImmutableSet.of("10.176.42.16"))
.imageId("2")
.hardware(
new HardwareBuilder()
.ids("1")
.name("256 MB Server")
.processors(ImmutableList.of(new Processor(1.0, 1.0)))
.ram(256)
.volumes(
ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f)
.durable(true).bootDevice(true).build())).build())
.operatingSystem(
new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2")
.is64Bit(true).build())
.id("1234")
.providerId("1234")
.name("sample-server")
.group("sample")
.hostname("sample-server")
.location(
new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0")
.description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
}
}

View File

@ -1,40 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.domain;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
/**
* Tests behavior of {@code CreateImageBinder}
*/
@Test(groups = "unit")
public class ServerTest {
public void testStatusDoesntAffectEquals() {
Server server1 = Server.builder().id(1).name("hello").status(ServerStatus.ACTIVE).build();
Server server2 = Server.builder().id(1).name("hello").status(ServerStatus.BUILD).build();
assertEquals(server1, server2);
}
public void testProgressDoesntAffectEquals() {
Server server1 = Server.builder().id(1).name("hello").progress(1).build();
Server server2 = Server.builder().id(1).name("hello").progress(2).build();
assertEquals(server1, server2);
}
}

View File

@ -1,57 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseAddressesFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseAddressesFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses.json");
UnwrapOnlyJsonValue<Addresses> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Addresses>>() {
}));
Addresses response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
List<String> publicAddresses = ImmutableList.of("67.23.10.132", "67.23.10.131");
List<String> privateAddresses = ImmutableList.of("10.176.42.16");
assertEquals(response.getPublicAddresses(), publicAddresses);
assertEquals(response.getPrivateAddresses(), privateAddresses);
}
}

View File

@ -1,64 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.cloudservers.domain.DailyBackup;
import org.jclouds.cloudservers.domain.WeeklyBackup;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseBackupScheduleFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseBackupScheduleFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_backupschedule.json");
UnwrapOnlyJsonValue<BackupSchedule> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<BackupSchedule>>() {
}));
BackupSchedule response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(BackupSchedule.builder().weekly(WeeklyBackup.THURSDAY).daily(DailyBackup.H_0400_0600).enabled(true).build(), response);
}
public void testNoSchedule() throws UnknownHostException {
UnwrapOnlyJsonValue<BackupSchedule> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<BackupSchedule>>() {
}));
BackupSchedule response = parser.apply(HttpResponse.builder()
.statusCode(200).message("ok")
.payload("{\"backupSchedule\":{\"enabled\" : false}}").build());
assertEquals(BackupSchedule.builder().build(), response);
}
}

View File

@ -1,59 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.gson.Gson;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseFlavorFromJsonResponseTest {
public void test() {
Flavor response = parseFlavor();
String json = new Gson().toJson(response);
assertEquals(json, "{\"id\":1,\"name\":\"256 MB Server\",\"disk\":10,\"ram\":256}");
}
public static Flavor parseFlavor() {
Injector i = Guice.createInjector(new GsonModule());
InputStream is = ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json");
UnwrapOnlyJsonValue<Flavor> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Flavor>>() {
}));
Flavor response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
return response;
}
}

View File

@ -1,77 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseFlavorListFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseFlavorListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_flavors.json");
List<Flavor> expects = ImmutableList.of(Flavor.builder().id(1).name("256 MB Server").build(),
Flavor.builder().id(2).name("512 MB Server").build());
UnwrapOnlyJsonValue<List<Flavor>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Flavor>>>() {
}));
List<Flavor> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, expects);
}
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json");
UnwrapOnlyJsonValue<List<Flavor>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Flavor>>>() {
}));
List<Flavor> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response.get(0).getId(), 1);
assertEquals(response.get(0).getName(), "256 MB Server");
assertEquals(response.get(0).getDisk(), Integer.valueOf(10));
assertEquals(response.get(0).getRam(), Integer.valueOf(256));
assertEquals(response.get(1).getId(), 2);
assertEquals(response.get(1).getName(), "512 MB Server");
assertEquals(response.get(1).getDisk(), Integer.valueOf(20));
assertEquals(response.get(1).getRam(), Integer.valueOf(512));
}
}

View File

@ -1,87 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.cloudservers.domain.Image;
import org.jclouds.cloudservers.domain.ImageStatus;
import org.jclouds.date.DateService;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseImageFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseImageFromJsonResponseTest {
Injector i = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
}
}, new GsonModule());
DateService dateService = i.getInstance(DateService.class);
public void testApplyInputStreamDetails() throws UnknownHostException {
Image response = parseImage();
assertEquals(response.getId(), 2);
assertEquals(response.getName(), "CentOS 5.2");
assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z"));
assertEquals(response.getProgress(), Integer.valueOf(80));
assertEquals(response.getServerId(), Integer.valueOf(12));
assertEquals(response.getStatus(), ImageStatus.SAVING);
assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));
}
public static Image parseImage() {
Injector i = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
}
}, new GsonModule());
InputStream is = ParseImageFromJsonResponseTest.class.getResourceAsStream("/test_get_image_details.json");
UnwrapOnlyJsonValue<Image> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Image>>() {
}));
Image response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
return response;
}
}

View File

@ -1,97 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.cloudservers.domain.Image;
import org.jclouds.cloudservers.domain.ImageStatus;
import org.jclouds.date.DateService;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseImageListFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseImageListFromJsonResponseTest {
Injector i = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(DateAdapter.class).to(Iso8601DateAdapter.class);
}
}, new GsonModule());
DateService dateService = i.getInstance(DateService.class);
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_images.json");
List<Image> expects = ImmutableList.of(Image.builder().id(2).name("CentOS 5.2").build(),
Image.builder().id(743).name("My Server Backup").build());
UnwrapOnlyJsonValue<List<Image>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Image>>>() {
}));
List<Image> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, expects);
}
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json");
UnwrapOnlyJsonValue<List<Image>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Image>>>() {
}));
List<Image> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response.get(0).getId(), 2);
assertEquals(response.get(0).getName(), "CentOS 5.2");
assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z"));
assertEquals(response.get(0).getProgress(), null);
assertEquals(response.get(0).getServerId(), null);
assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE);
assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));
assertEquals(response.get(1).getId(), 743);
assertEquals(response.get(1).getName(), "My Server Backup");
assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16-05:00"));
assertEquals(response.get(1).getProgress(), Integer.valueOf(80));
assertEquals(response.get(1).getServerId(), Integer.valueOf(12));
assertEquals(response.get(1).getStatus(), ImageStatus.SAVING);
assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));
}
}

View File

@ -1,65 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseInetAddressListFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseInetAddressListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testPublic() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json");
UnwrapOnlyJsonValue<List<String>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<String>>>() {
}));
List<String> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, ImmutableList.of("67.23.10.132", "67.23.10.131"));
}
public void testPrivate() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json");
UnwrapOnlyJsonValue<List<String>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<String>>>() {
}));
List<String> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, ImmutableList.of("10.176.42.16"));
}
}

View File

@ -1,75 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseServerFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseServerFromJsonResponseTest {
public void testApplyInputStreamDetails() throws UnknownHostException {
Server response = parseServer();
assertEquals(response.getId(), 1234);
assertEquals(response.getName(), "sample-server");
assertEquals(response.getImageId(), Integer.valueOf(2));
assertEquals(response.getFlavorId(), Integer.valueOf(1));
assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0");
assertEquals(response.getStatus(), ServerStatus.BUILD);
assertEquals(response.getProgress(), Integer.valueOf(60));
List<String> publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131");
List<String> privateAddresses = Lists.newArrayList("10.176.42.16");
Addresses addresses1 = Addresses.builder().publicAddresses(publicAddresses).privateAddresses(privateAddresses).build();
assertEquals(response.getAddresses(), addresses1);
assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1"));
}
public static Server parseServer() {
Injector i = Guice.createInjector(new GsonModule());
InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json");
UnwrapOnlyJsonValue<Server> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Server>>() {
}));
Server response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
return response;
}
}

View File

@ -1,98 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.cloudservers.domain.Addresses;
import org.jclouds.cloudservers.domain.Server;
import org.jclouds.cloudservers.domain.ServerStatus;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseServerListFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseServerListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_servers.json");
List<Server> expects = ImmutableList.of(Server.builder().id(1234).name("sample-server").build(),
Server.builder().id(5678).name("sample-server2").build());
UnwrapOnlyJsonValue<List<Server>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Server>>>() {
}));
List<Server> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, expects);
}
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json");
UnwrapOnlyJsonValue<List<Server>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Server>>>() {
}));
List<Server> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response.get(0).getId(), 1234);
assertEquals(response.get(0).getName(), "sample-server");
assertEquals(response.get(0).getImageId(), Integer.valueOf(2));
assertEquals(response.get(0).getFlavorId(), Integer.valueOf(1));
assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0");
assertEquals(response.get(0).getStatus(), ServerStatus.BUILD);
assertEquals(response.get(0).getProgress(), Integer.valueOf(60));
List<String> publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131");
List<String> privateAddresses = Lists.newArrayList("10.176.42.16");
Addresses addresses1 = Addresses.builder().privateAddresses(privateAddresses).publicAddresses(publicAddresses).build();
assertEquals(response.get(0).getAddresses(), addresses1);
assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1"));
assertEquals(response.get(1).getId(), 5678);
assertEquals(response.get(1).getName(), "sample-server2");
assertEquals(response.get(1).getImageId(), Integer.valueOf(2));
assertEquals(response.get(1).getFlavorId(), Integer.valueOf(1));
assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6");
assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE);
assertEquals(response.get(1).getProgress(), null);
List<String> publicAddresses2 = Lists.newArrayList("67.23.10.133");
List<String> privateAddresses2 = Lists.newArrayList("10.176.42.17");
Addresses addresses2 = Addresses.builder().privateAddresses(privateAddresses2).publicAddresses(publicAddresses2).build();
assertEquals(response.get(1).getAddresses(), addresses2);
assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1"));
}
}

View File

@ -1,56 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.cloudservers.domain.SharedIpGroup;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseSharedIpGroupFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseSharedIpGroupFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_get_sharedipgroup_details.json");
UnwrapOnlyJsonValue<SharedIpGroup> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<SharedIpGroup>>() {
}));
SharedIpGroup response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response.getId(), 1234);
assertEquals(response.getName(), "Shared IP Group 1");
assertEquals(response.getServers(), ImmutableList.of(422));
}
}

View File

@ -1,78 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import org.jclouds.cloudservers.domain.SharedIpGroup;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseSharedIpGroupListFromJsonResponse}
*/
@Test(groups = "unit")
public class ParseSharedIpGroupListFromJsonResponseTest {
Injector i = Guice.createInjector(new GsonModule());
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/test_list_sharedipgroups.json");
List<SharedIpGroup> expects = ImmutableList.of(SharedIpGroup.builder().id(1234).name("Shared IP Group 1").build(),
SharedIpGroup.builder().id(5678).name("Shared IP Group 2").build());
UnwrapOnlyJsonValue<List<SharedIpGroup>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<SharedIpGroup>>>() {
}));
List<SharedIpGroup> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, expects);
}
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_list_sharedipgroups_detail.json");
UnwrapOnlyJsonValue<List<SharedIpGroup>> parser = i.getInstance(Key
.get(new TypeLiteral<UnwrapOnlyJsonValue<List<SharedIpGroup>>>() {
}));
List<SharedIpGroup> response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response.get(0).getId(), 1234);
assertEquals(response.get(0).getName(), "Shared IP Group 1");
assertEquals(response.get(0).getServers(), ImmutableList.of(422, 3445));
assertEquals(response.get(1).getId(), 5678);
assertEquals(response.get(1).getName(), "Shared IP Group 2");
assertEquals(response.get(1).getServers(), ImmutableList.of(23203, 2456, 9891));
}
}

View File

@ -1,128 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.handlers;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.internal.BaseCloudServersRestClientExpectTest;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.io.Payloads;
import org.jclouds.rest.AuthorizationException;
import org.testng.annotations.Test;
/**
* Tests behavior of {@code RetryOnRenew} handler
*/
@Test(groups = "unit", testName = "RetryOnRenewExpectTest")
public class RetryOnRenewExpectTest extends BaseCloudServersRestClientExpectTest {
@Test
public void testShouldReauthenticateOn401() {
HttpRequest deleteImage = HttpRequest.builder().method("DELETE")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/11?now=1257695648897")
.addHeader("X-Auth-Token", authToken).build();
HttpResponse pleaseRenew = HttpResponse
.builder()
.statusCode(401)
.message("HTTP/1.1 401 Unauthorized")
.payload("[{\"unauthorized\":{\"message\":\"Invalid authentication token. Please renew.\",\"code\":401}}]")
.build();
// second auth uses same creds as initial one
HttpRequest redoAuth = initialAuth;
String authToken2 = "12345678-9012-47c0-9770-2c5097da25fc";
HttpResponse responseWithUrls2 = responseWithAuth.toBuilder()
.payload(responseWithAuth.getPayload().getRawContent().toString().replace(authToken, authToken2))
.build();
HttpRequest deleteImage2 = HttpRequest.builder().method("DELETE")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/11?now=1257695648897")
.addHeader("X-Auth-Token", authToken2).build();
HttpResponse imageDeleted = HttpResponse.builder().statusCode(204).message("HTTP/1.1 204 No Content").build();
CloudServersClient clientWhenImageExists = orderedRequestsSendResponses(initialAuth, responseWithAuth,
deleteImage, pleaseRenew, redoAuth, responseWithUrls2, deleteImage2, imageDeleted);
assert clientWhenImageExists.deleteImage(11);
}
public void testReauthenticateOn401ForFailedCommand() {
String requestUrl = "https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/11?now=1257695648897";
HttpRequest deleteImage = HttpRequest.builder().method("DELETE")
.endpoint(requestUrl)
.addHeader("X-Auth-Token", authToken).build();
HttpResponse unauthResponse = HttpResponse
.builder()
.statusCode(401)
.message("HTTP/1.1 401 Unauthorized")
.payload("[{\"unauthorized\":{\"message\":\"Fatal unauthorized.\",\"code\":401}}]")
.build();
// second auth uses same creds as initial one
HttpRequest redoAuth = initialAuth;
String authToken2 = "12345678-9012-47c0-9770-2c5097da25fc";
HttpResponse responseWithUrls2 = responseWithAuth.toBuilder()
.payload(responseWithAuth.getPayload().getRawContent().toString()
.replace(authToken, authToken2)).build();
HttpRequest deleteImage2 = HttpRequest
.builder().method("DELETE")
.endpoint(requestUrl).addHeader("X-Auth-Token", authToken2).build();
HttpResponse imageDeleted = HttpResponse.builder().statusCode(204)
.message("HTTP/1.1 204 No Content").build();
// The sequence of events simulated here is as follows:
// 1. First auth succeeds.
// 2. The token returned in #1 is used in the deleteImage command.
// 3. The deleteImage command fails with a 401 error.
// 4. This should result in a new auth request which succeeds.
// 5. The new token is used in the next deleteImage command.
// 6. Succeed that command.
CloudServersClient client = orderedRequestsSendResponses(initialAuth,
responseWithAuth, deleteImage, unauthResponse, redoAuth,
responseWithUrls2, deleteImage2, imageDeleted);
client.deleteImage(11);
}
// FIXME stack trace shows the AuthorizationException, but it's buried inside
// a guice TestException
@Test(expectedExceptions = AuthorizationException.class)
public void testDoesNotReauthenticateOnAuthentication401() {
HttpResponse unauthResponse = HttpResponse
.builder()
.statusCode(401)
.message("HTTP/1.1 401 Unauthorized")
.payload(
Payloads
.newStringPayload("[{\"unauthorized\":{\"message\":\"A different message implying fatal.\",\"code\":401}}]"))
.build();
CloudServersClient client = requestSendsResponse(initialAuth, unauthResponse);
client.deleteImage(11);
}
}

View File

@ -1,96 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.internal;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import java.util.Date;
import java.util.Properties;
import org.jclouds.apis.ApiMetadata;
import org.jclouds.cloudservers.CloudServersApiMetadata;
import org.jclouds.cloudservers.config.CloudServersHttpApiModule;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.keystone.v1_1.config.AuthenticationServiceModule;
import org.jclouds.openstack.keystone.v1_1.internal.BaseKeystoneRestClientExpectTest;
import org.jclouds.rest.ConfiguresHttpApi;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.inject.Module;
public abstract class BaseCloudServersComputeServiceExpectTest<T> extends BaseKeystoneRestClientExpectTest<T> implements
Function<ComputeServiceContext, T> {
public BaseCloudServersComputeServiceExpectTest() {
provider = "cloudservers";
}
protected static final String CONSTANT_DATE = "2009-11-08T15:54:08.897Z";
public static class TestAuthenticationServiceModule extends AuthenticationServiceModule {
@Override
protected void configure() {
super.configure();
}
}
@Override
protected Module createModule() {
return new TestCloudServersHttpApiModule();
}
@ConfiguresHttpApi
protected static class TestCloudServersHttpApiModule extends CloudServersHttpApiModule {
@Override
public Supplier<Date> provideCacheBusterDate() {
return new Supplier<Date>() {
public Date get() {
return new SimpleDateFormatDateService().iso8601DateParse(CONSTANT_DATE);
}
};
}
}
@Override
protected ApiMetadata createApiMetadata() {
return new CloudServersApiMetadata();
}
@Override
protected Properties setupProperties() {
Properties overrides = new Properties();
overrides.setProperty(PROPERTY_REGIONS, "US");
overrides.setProperty(provider + ".endpoint", endpoint);
return overrides;
}
@Override
public T createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {
return apply(createComputeServiceContext(fn, module, props));
}
private ComputeServiceContext createComputeServiceContext(Function<HttpRequest, HttpResponse> fn, Module module,
Properties props) {
return createInjector(fn, module, props).getInstance(ComputeServiceContext.class);
}
}

View File

@ -1,81 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.internal;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import java.util.Date;
import java.util.Properties;
import org.jclouds.apis.ApiMetadata;
import org.jclouds.cloudservers.CloudServersApiMetadata;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.config.CloudServersHttpApiModule;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.openstack.keystone.v1_1.internal.BaseKeystoneRestClientExpectTest;
import org.jclouds.rest.ConfiguresHttpApi;
import com.google.common.base.Supplier;
import com.google.inject.Module;
/**
* Base class for writing CloudServers Rest Client Expect tests
*/
public class BaseCloudServersRestClientExpectTest extends BaseKeystoneRestClientExpectTest<CloudServersClient> {
public BaseCloudServersRestClientExpectTest() {
provider = "cloudservers";
}
@Override
protected ApiMetadata createApiMetadata() {
return new CloudServersApiMetadata();
}
@Override
protected Properties setupProperties() {
Properties overrides = new Properties();
overrides.setProperty(PROPERTY_REGIONS, "US");
overrides.setProperty(provider + ".endpoint", endpoint);
return overrides;
}
protected static final String CONSTANT_DATE = "2009-11-08T15:54:08.897Z";
/**
* override so that we can control the timestamp used in
* {@link AddTimestampQuery}
*/
@Override
protected Module createModule() {
return new TestCloudServersHttpApiModule();
}
@ConfiguresHttpApi
protected static class TestCloudServersHttpApiModule extends CloudServersHttpApiModule {
@Override
public Supplier<Date> provideCacheBusterDate() {
return new Supplier<Date>() {
public Date get() {
return new SimpleDateFormatDateService().iso8601DateParse(CONSTANT_DATE);
}
};
}
}
}

View File

@ -1,132 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withSharedIp;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withSharedIpGroup;
import static org.testng.Assert.assertEquals;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
*/
@Test(groups = "unit")
public class CreateServerOptionsTest {
Injector injector = Guice.createInjector(new GsonModule());
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateServerOptions options = new CreateServerOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2}}", request.getPayload().getRawContent());
}
private HttpRequest buildRequest(CreateServerOptions options) {
injector.injectMembers(options);
HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
options.bindToRequest(request, ImmutableMap.<String, Object>of("name", "foo", "imageId", "1", "flavorId", "2"));
return request;
}
@Test
public void testWithFile() {
CreateServerOptions options = new CreateServerOptions();
options.withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertFile(request);
}
@Test
public void testWithFileStatic() {
CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes());
HttpRequest request = buildRequest(options);
assertFile(request);
}
private void assertFile(HttpRequest request) {
assertEquals(
"{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}",
request.getPayload().getRawContent());
}
@Test
public void testWithSharedIpGroup() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIpGroup(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
@Test
public void testWithSharedIpGroupStatic() {
CreateServerOptions options = withSharedIpGroup(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
private void assertSharedIpGroup(HttpRequest request) {
assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"sharedIpGroupId\":3}}", request
.getPayload().getRawContent());
}
@Test
public void testWithMetadata() {
}
@Test
public void testWithSharedIp() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIpGroup(3).withSharedIp("127.0.0.1");
HttpRequest request = buildRequest(options);
assertSharedIp(request);
}
@Test
public void testWithSharedIpStatic() {
CreateServerOptions options = withSharedIpGroup(3).withSharedIp("127.0.0.1");
HttpRequest request = buildRequest(options);
assertSharedIp(request);
}
private void assertSharedIp(HttpRequest request) {
assertEquals(
"{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"sharedIpGroupId\":3,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}",
request.getPayload().getRawContent());
}
@Test(expectedExceptions = IllegalStateException.class)
public void testWithSharedIpNoGroup() {
CreateServerOptions options = new CreateServerOptions();
options.withSharedIp("127.0.0.1");
buildRequest(options);
}
@Test(expectedExceptions = IllegalStateException.class)
public void testWithSharedIpNoGroupStatic() {
CreateServerOptions options = withSharedIp("127.0.0.1");
buildRequest(options);
}
}

View File

@ -1,71 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static org.jclouds.cloudservers.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.testng.Assert.assertEquals;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
*/
@Test(groups = "unit")
public class CreateSharedIpGroupOptionsTest {
Injector injector = Guice.createInjector(new GsonModule());
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\"}}", request.getPayload().getRawContent());
}
private HttpRequest buildRequest(CreateSharedIpGroupOptions options) {
injector.injectMembers(options);
HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
options.bindToRequest(request, ImmutableMap.<String, Object>of("name", "foo"));
return request;
}
@Test
public void testWithServer() {
CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions();
options.withServer(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
@Test
public void testWithServerStatic() {
CreateSharedIpGroupOptions options = withServer(3);
HttpRequest request = buildRequest(options);
assertSharedIpGroup(request);
}
private void assertSharedIpGroup(HttpRequest request) {
assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\",\"server\":3}}", request.getPayload().getRawContent());
}
}

View File

@ -1,84 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static org.jclouds.cloudservers.options.ListOptions.Builder.changesSince;
import static org.jclouds.cloudservers.options.ListOptions.Builder.maxResults;
import static org.jclouds.cloudservers.options.ListOptions.Builder.startAt;
import static org.jclouds.cloudservers.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.assertEquals;
import java.util.Date;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
/**
* Tests behavior of {@code ListOptions}
*/
@Test(groups = "unit")
public class ListOptionsTest {
public void testWithDetails() {
ListOptions options = new ListOptions().withDetails();
assertEquals(options.buildPathSuffix(), "/detail");
}
public void testWithDetailsStatic() {
ListOptions options = withDetails();
assertEquals(options.buildPathSuffix(), "/detail");
}
public void testChangesSince() {
Date ifModifiedSince = new Date();
ListOptions options = new ListOptions().changesSince(ifModifiedSince);
assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), options
.buildQueryParameters().get("changes-since"));
}
public void testStartAt() {
long offset = 1;
ListOptions options = new ListOptions().startAt(offset);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("offset"));
}
public void testMaxResults() {
int limit = 1;
ListOptions options = new ListOptions().maxResults(limit);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("limit"));
}
public void testChangesSinceStatic() {
Date ifModifiedSince = new Date();
ListOptions options = changesSince(ifModifiedSince);
assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), options
.buildQueryParameters().get("changes-since"));
}
public void testStartAtStatic() {
long offset = 1;
ListOptions options = startAt(offset);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("offset"));
}
public void testMaxResultsStatic() {
int limit = 1;
ListOptions options = maxResults(limit);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("limit"));
}
}

View File

@ -1,72 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.cloudservers.options;
import static org.jclouds.cloudservers.options.RebuildServerOptions.Builder.withImage;
import static org.testng.Assert.assertEquals;
import java.util.HashMap;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ParseFlavorFromJsonResponse}
*/
@Test(groups = "unit")
public class RebuildServerOptionsTest {
Injector injector = Guice.createInjector(new GsonModule());
@Test
public void testAddPayloadToRequestMapOfStringStringHttpRequest() {
RebuildServerOptions options = new RebuildServerOptions();
HttpRequest request = buildRequest(options);
assertEquals("{\"rebuild\":{}}", request.getPayload().getRawContent());
}
private HttpRequest buildRequest(RebuildServerOptions options) {
injector.injectMembers(options);
HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
options.bindToRequest(request, new HashMap<String, Object>());
return request;
}
@Test
public void testWithServer() {
RebuildServerOptions options = new RebuildServerOptions();
options.withImage(3);
HttpRequest request = buildRequest(options);
assertRebuild(request);
}
@Test
public void testWithServerStatic() {
RebuildServerOptions options = withImage(3);
HttpRequest request = buildRequest(options);
assertRebuild(request);
}
private void assertRebuild(HttpRequest request) {
assertEquals("{\"rebuild\":{\"imageId\":3}}", request.getPayload().getRawContent());
}
}

View File

@ -1,149 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!--
For more configuration infromation and examples see the Apache
Log4j website: http://logging.apache.org/log4j/
-->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<!-- A time/date based rolling appender -->
<appender name="WIREFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-wire.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="COMPUTEFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-compute.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="SSHFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-ssh.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<appender name="ASYNCCOMPUTE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="COMPUTEFILE" />
</appender>
<appender name="ASYNCSSH" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="SSHFILE" />
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="FILE" />
</appender>
<appender name="ASYNCWIRE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="WIREFILE" />
</appender>
<!-- ================ -->
<!-- Limit categories -->
<!-- ================ -->
<category name="org.jclouds">
<priority value="DEBUG" />
<appender-ref ref="ASYNC" />
</category>
<category name="jclouds.headers">
<priority value="DEBUG" />
<appender-ref ref="ASYNCWIRE" />
</category>
<category name="jclouds.ssh">
<priority value="DEBUG" />
<appender-ref ref="ASYNCSSH" />
</category>
<category name="jclouds.wire">
<priority value="DEBUG" />
<appender-ref ref="ASYNCWIRE" />
</category>
<category name="jclouds.compute">
<priority value="TRACE" />
<appender-ref ref="ASYNCCOMPUTE" />
</category>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<priority value="WARN" />
</root>
</log4j:configuration>

View File

@ -1,8 +0,0 @@
{
"flavor" : {
"id" : 1,
"name" : "256 MB Server",
"ram" : 256,
"disk" : 10
}
}

View File

@ -1,11 +0,0 @@
{
"image" : {
"id" : 2,
"name" : "CentOS 5.2",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE",
"progress" : 100
}
}

View File

@ -1,11 +0,0 @@
{
"image" : {
"id" : 2,
"name" : "CentOS 5.2",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "SAVING",
"progress" : 80
}
}

View File

@ -1,25 +0,0 @@
{
"server" : {
"id" : 1234,
"name" : "sample-server",
"imageId" : 2,
"flavorId" : 1,
"hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0",
"status" : "BUILD",
"progress" : 60,
"addresses" : {
"public" : [
"67.23.10.132",
"67.23.10.131"
],
"private" : [
"10.176.42.16"
]
},
"metadata" : {
"Server Label" : "Web Head 1",
"Image Version" : "2.1"
}
}
}

View File

@ -1,7 +0,0 @@
{
"sharedIpGroup" : {
"id" : 1234,
"name" : "Shared IP Group 1",
"servers" : [422]
}
}

View File

@ -1,12 +0,0 @@
{
"addresses" : {
"public" : [
"67.23.10.132",
"67.23.10.131"
],
"private" : [
"10.176.42.16"
]
}
}

View File

@ -1,8 +0,0 @@
{
"private" : [
"10.176.42.16"
]
}

View File

@ -1,7 +0,0 @@
{
"public" : [
"67.23.10.132",
"67.23.10.131"
]
}

View File

@ -1,7 +0,0 @@
{
"backupSchedule" : {
"enabled" : true,
"weekly" : "THURSDAY",
"daily" : "H_0400_0600"
}
}

View File

@ -1,12 +0,0 @@
{
"flavors" : [
{
"id" : 1,
"name" : "256 MB Server"
},
{
"id" : 2,
"name" : "512 MB Server"
}
]
}

View File

@ -1,16 +0,0 @@
{
"flavors" : [
{
"id" : 1,
"name" : "256 MB Server",
"ram" : 256,
"disk" : 10
},
{
"id" : 2,
"name" : "512 MB Server",
"ram" : 512,
"disk" : 20
}
]
}

View File

@ -1,12 +0,0 @@
{
"images" : [
{
"id" : 2,
"name" : "CentOS 5.2"
},
{
"id" : 743,
"name" : "My Server Backup"
}
]
}

View File

@ -1,20 +0,0 @@
{
"images" : [
{
"id" : 2,
"name" : "CentOS 5.2",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE"
},
{
"id" : 743,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "SAVING",
"progress" : 80
}
]
}

View File

@ -1,65 +0,0 @@
{
"images" : [
{
"id" : 2,
"name" : "CentOS 5.2",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE"
},
{
"id" : 743,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "SAVING",
"progress" : 80
}
,
{
"id" : 744,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "QUEUED"
}
,
{
"id" : 745,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "UNRECOGNIZED"
}
,
{
"id" : 746,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "UNKNOWN"
}
,
{
"id" : 747,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "PREPARING"
}
,
{
"id" : 748,
"name" : "My Server Backup",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2009-07-07T09:56:16-05:00",
"status" : "FAILED"
}
]
}

View File

@ -1,12 +0,0 @@
{
"servers" : [
{
"id" : 1234,
"name" : "sample-server"
},
{
"id" : 5678,
"name" : "sample-server2"
}
]
}

View File

@ -1,45 +0,0 @@
{
"servers" : [
{
"id" : 1234,
"name" : "sample-server",
"imageId" : 2,
"flavorId" : 1,
"hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0",
"status" : "BUILD",
"progress" : 60,
"addresses" : {
"public" : [
"67.23.10.132",
"67.23.10.131"
],
"private" : [
"10.176.42.16"
]
},
"metadata" : {
"Server Label" : "Web Head 1",
"Image Version" : "2.1"
}
},
{
"id" : 5678,
"name" : "sample-server2",
"imageId" : 2,
"flavorId" : 1,
"hostId" : "9e107d9d372bb6826bd81d3542a419d6",
"status" : "ACTIVE",
"addresses" : {
"public" : [
"67.23.10.133"
],
"private" : [
"10.176.42.17"
]
},
"metadata" : {
"Server Label" : "DB 1"
}
}
]
}

View File

@ -1,12 +0,0 @@
{
"sharedIpGroups" : [
{
"id" : 1234,
"name" : "Shared IP Group 1"
},
{
"id" : 5678,
"name" : "Shared IP Group 2"
}
]
}

View File

@ -1,14 +0,0 @@
{
"sharedIpGroups" : [
{
"id" : 1234,
"name" : "Shared IP Group 1",
"servers" : [422, 3445]
},
{
"id" : 5678,
"name" : "Shared IP Group 2",
"servers" : [23203, 2456, 9891]
}
]
}

View File

@ -46,7 +46,6 @@
<module>openstack-swift</module>
<module>openstack-trove</module>
<module>cloudfiles</module>
<module>cloudservers</module>
<module>rackspace-cloudidentity</module>
<module>rackspace-cloudloadbalancers</module>
<module>rackspace-clouddns</module>

View File

@ -1,8 +0,0 @@
#
# The jclouds provider for Rackspace's UK Cloud Servers (http://www.rackspacecloud.com/cloud_hosting_products/servers/).
#
# Expects the jclouds cloudservers API to be present on your application's classpath.
#
# TODO: Implementation status.
# TODO: Supported features.
# TODO: Usage example.

View File

@ -1,131 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF 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.apache.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.apache.jclouds.provider</groupId>
<artifactId>cloudservers-uk</artifactId>
<name>jclouds CloudServers UK provider</name>
<description>CloudServers implementation targeted to Rackspace UK</description>
<packaging>bundle</packaging>
<properties>
<test.cloudservers-uk.endpoint>https://lon.auth.api.rackspacecloud.com</test.cloudservers-uk.endpoint>
<test.cloudservers-uk.api-version>1.0</test.cloudservers-uk.api-version>
<test.cloudservers-uk.build-version />
<test.cloudservers-uk.identity>${test.rackspace-uk.identity}</test.cloudservers-uk.identity>
<test.cloudservers-uk.credential>${test.rackspace-uk.credential}</test.cloudservers-uk.credential>
<test.cloudservers-uk.template />
<jclouds.osgi.export>org.jclouds.rackspace.cloudservers*;version="${project.version}"</jclouds.osgi.export>
<jclouds.osgi.import>
org.jclouds.compute.internal;version="${project.version}",
org.jclouds.rest.internal;version="${project.version}",
org.jclouds*;version="${project.version}",
*
</jclouds.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.jclouds.common</groupId>
<artifactId>openstack-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds.api</groupId>
<artifactId>cloudservers</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds.api</groupId>
<artifactId>cloudservers</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-sshj</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.cloudservers-uk.endpoint>${test.cloudservers-uk.endpoint}</test.cloudservers-uk.endpoint>
<test.cloudservers-uk.api-version>${test.cloudservers-uk.api-version}</test.cloudservers-uk.api-version>
<test.cloudservers-uk.build-version>${test.cloudservers-uk.build-version}</test.cloudservers-uk.build-version>
<test.cloudservers-uk.identity>${test.cloudservers-uk.identity}</test.cloudservers-uk.identity>
<test.cloudservers-uk.credential>${test.cloudservers-uk.credential}</test.cloudservers-uk.credential>
<test.cloudservers-uk.template>${test.cloudservers-uk.template}</test.cloudservers-uk.template>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,80 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.rackspace.cloudservers;
import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;
import java.net.URI;
import java.util.Properties;
import org.jclouds.cloudservers.CloudServersApiMetadata;
import org.jclouds.providers.ProviderMetadata;
import org.jclouds.providers.internal.BaseProviderMetadata;
/**
* Implementation of {@link org.jclouds.types.ProviderMetadata} for Rackspace Cloud Servers UK.
*/
public class CloudServersUKProviderMetadata extends BaseProviderMetadata {
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return builder().fromProviderMetadata(this);
}
public CloudServersUKProviderMetadata() {
super(builder());
}
public CloudServersUKProviderMetadata(Builder builder) {
super(builder);
}
public static Properties defaultProperties() {
Properties properties = new Properties();
properties.setProperty(PROPERTY_REGIONS, "UK");
return properties;
}
public static class Builder extends BaseProviderMetadata.Builder {
protected Builder() {
id("cloudservers-uk")
.name("Rackspace Cloud Servers UK")
.apiMetadata(new CloudServersApiMetadata())
.endpoint("https://lon.auth.api.rackspacecloud.com")
.homepage(URI.create("http://www.rackspace.co.uk/cloud-hosting/cloud-products/cloud-servers"))
.console(URI.create("https://lon.manage.rackspacecloud.com"))
.linkedServices("cloudloadbalancers-uk", "cloudservers-uk", "cloudfiles-uk")
.iso3166Codes("GB-SLG");
}
@Override
public CloudServersUKProviderMetadata build() {
return new CloudServersUKProviderMetadata(this);
}
@Override
public Builder fromProviderMetadata(
ProviderMetadata in) {
super.fromProviderMetadata(in);
return this;
}
}
}

View File

@ -1 +0,0 @@
org.jclouds.rackspace.cloudservers.CloudServersUKProviderMetadata

View File

@ -1,27 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.rackspace.cloudservers;
import org.jclouds.cloudservers.CloudServersClientLiveTest;
import org.testng.annotations.Test;
@Test(groups = "live", sequential = true)
public class CloudServersUKClientLiveTest extends CloudServersClientLiveTest {
public CloudServersUKClientLiveTest() {
provider = "cloudservers-uk";
}
}

View File

@ -1,46 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*
* ====================================================================
* Licensed 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.rackspace.cloudservers;
import org.jclouds.cloudservers.CloudServersApiMetadata;
import org.jclouds.providers.internal.BaseProviderMetadataTest;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "CloudServersUKProviderTest")
public class CloudServersUKProviderTest extends BaseProviderMetadataTest {
public CloudServersUKProviderTest() {
super(new CloudServersUKProviderMetadata(), new CloudServersApiMetadata());
}
}

View File

@ -1,30 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.rackspace.cloudservers.compute;
import org.jclouds.cloudservers.compute.CloudServersComputeServiceLiveTest;
import org.testng.annotations.Test;
@Test(groups = "live", singleThreaded = true, testName = "CloudServersUKComputeServiceLiveTest")
public class CloudServersUKComputeServiceLiveTest extends CloudServersComputeServiceLiveTest {
public CloudServersUKComputeServiceLiveTest() {
provider = "cloudservers-uk";
group = "cs";
}
}

View File

@ -1,52 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.rackspace.cloudservers.compute;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.testng.Assert.assertEquals;
import java.util.Set;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
@Test(groups = "live")
public class CloudServersUKTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {
public CloudServersUKTemplateBuilderLiveTest() {
provider = "cloudservers-uk";
}
@Test
public void testTemplateBuilder() {
Template defaultTemplate = this.view.getComputeService().templateBuilder().build();
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "11.10");
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(defaultTemplate.getLocation().getId(), provider);
assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);
}
@Override
protected Set<String> getIso3166Codes() {
return ImmutableSet.<String> of("GB-SLG");
}
}

View File

@ -1,8 +0,0 @@
#
# The jclouds provider for Rackspace's US Cloud Servers (http://www.rackspacecloud.com/cloud_hosting_products/servers/).
#
# Expects the jclouds cloudservers API to be present on your application's classpath.
#
# TODO: Implementation status.
# TODO: Supported features.
# TODO: Usage example.

View File

@ -1,130 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF 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.apache.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.apache.jclouds.provider</groupId>
<artifactId>cloudservers-us</artifactId>
<name>jclouds CloudServers US provider</name>
<description>CloudServers implementation targeted to Rackspace US</description>
<packaging>bundle</packaging>
<properties>
<test.cloudservers-us.endpoint>https://auth.api.rackspacecloud.com</test.cloudservers-us.endpoint>
<test.cloudservers-us.api-version>1.0</test.cloudservers-us.api-version>
<test.cloudservers-us.build-version />
<test.cloudservers-us.identity>${test.rackspace-us.identity}</test.cloudservers-us.identity>
<test.cloudservers-us.credential>${test.rackspace-us.credential}</test.cloudservers-us.credential>
<test.cloudservers-us.template />
<jclouds.osgi.export>org.jclouds.rackspace.cloudservers*;version="${project.version}"</jclouds.osgi.export>
<jclouds.osgi.import>
org.jclouds.compute.internal;version="${project.version}",
org.jclouds.rest.internal;version="${project.version}",
org.jclouds*;version="${project.version}",
*
</jclouds.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.jclouds.common</groupId>
<artifactId>openstack-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds.api</groupId>
<artifactId>cloudservers</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds.api</groupId>
<artifactId>cloudservers</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-sshj</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>
<threadCount>1</threadCount>
<systemPropertyVariables>
<test.cloudservers-us.endpoint>${test.cloudservers-us.endpoint}</test.cloudservers-us.endpoint>
<test.cloudservers-us.api-version>${test.cloudservers-us.api-version}</test.cloudservers-us.api-version>
<test.cloudservers-us.build-version>${test.cloudservers-us.build-version}</test.cloudservers-us.build-version>
<test.cloudservers-us.identity>${test.cloudservers-us.identity}</test.cloudservers-us.identity>
<test.cloudservers-us.credential>${test.cloudservers-us.credential}</test.cloudservers-us.credential>
<test.cloudservers-us.template>${test.cloudservers-us.template}</test.cloudservers-us.template>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

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